blob: 006d67b603478af8ff730e7720075a59567f34a4 [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"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
49#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000055#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056#include "llvm/Support/MathExtras.h"
57#include "llvm/Support/PatternMatch.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/SmallPtrSet.h"
62#include "llvm/ADT/Statistic.h"
63#include "llvm/ADT/STLExtras.h"
64#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000065#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066using namespace llvm;
67using namespace llvm::PatternMatch;
68
69STATISTIC(NumCombined , "Number of insts combined");
70STATISTIC(NumConstProp, "Number of constant folds");
71STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73STATISTIC(NumSunkInst , "Number of instructions sunk");
74
75namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000076 /// InstCombineWorklist - This is the worklist management logic for
77 /// InstCombine.
78 class InstCombineWorklist {
79 SmallVector<Instruction*, 256> Worklist;
80 DenseMap<Instruction*, unsigned> WorklistMap;
81
82 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
83 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
84 public:
85 InstCombineWorklist() {}
86
87 bool isEmpty() const { return Worklist.empty(); }
88
89 /// Add - Add the specified instruction to the worklist if it isn't already
90 /// in it.
91 void Add(Instruction *I) {
92 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
93 Worklist.push_back(I);
94 }
95
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000096 void AddValue(Value *V) {
97 if (Instruction *I = dyn_cast<Instruction>(V))
98 Add(I);
99 }
100
Chris Lattner3183fb62009-08-30 06:13:40 +0000101 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000102 void Remove(Instruction *I) {
103 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
104 if (It == WorklistMap.end()) return; // Not in worklist.
105
106 // Don't bother moving everything down, just null out the slot.
107 Worklist[It->second] = 0;
108
109 WorklistMap.erase(It);
110 }
111
112 Instruction *RemoveOne() {
113 Instruction *I = Worklist.back();
114 Worklist.pop_back();
115 WorklistMap.erase(I);
116 return I;
117 }
118
Chris Lattner4796b622009-08-30 06:22:51 +0000119 /// AddUsersToWorkList - When an instruction is simplified, add all users of
120 /// the instruction to the work lists because they might get more simplified
121 /// now.
122 ///
123 void AddUsersToWorkList(Instruction &I) {
124 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
125 UI != UE; ++UI)
126 Add(cast<Instruction>(*UI));
127 }
128
Chris Lattner5119c702009-08-30 05:55:36 +0000129
130 /// Zap - check that the worklist is empty and nuke the backing store for
131 /// the map if it is large.
132 void Zap() {
133 assert(WorklistMap.empty() && "Worklist empty, but map not?");
134
135 // Do an explicit clear, this shrinks the map if needed.
136 WorklistMap.clear();
137 }
138 };
139} // end anonymous namespace.
140
141
142namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000143 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
144 /// just like the normal insertion helper, but also adds any new instructions
145 /// to the instcombine worklist.
146 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
147 InstCombineWorklist &Worklist;
148 public:
149 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
150
151 void InsertHelper(Instruction *I, const Twine &Name,
152 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
153 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
154 Worklist.Add(I);
155 }
156 };
157} // end anonymous namespace
158
159
160namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000161 class InstCombiner : public FunctionPass,
162 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 TargetData *TD;
164 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000165 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000167 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000168 InstCombineWorklist Worklist;
169
Chris Lattnerc7694852009-08-30 07:44:24 +0000170 /// Builder - This is an IRBuilder that automatically inserts new
171 /// instructions into the worklist when they are created.
Chris Lattnerad7516a2009-08-30 18:50:58 +0000172 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
173 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000174
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000176 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177
Owen Anderson175b6542009-07-22 00:24:57 +0000178 LLVMContext *Context;
179 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000180
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 public:
182 virtual bool runOnFunction(Function &F);
183
184 bool DoOneIteration(Function &F, unsigned ItNum);
185
186 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 AU.addPreservedID(LCSSAID);
188 AU.setPreservesCFG();
189 }
190
Dan Gohmana80e2712009-07-21 23:21:54 +0000191 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192
193 // Visitation implementation - Implement instruction combining for different
194 // instruction types. The semantics are as follows:
195 // Return Value:
196 // null - No change was made
197 // I - Change was made, I is still valid, I may be dead though
198 // otherwise - Change was made, replace I with returned instruction
199 //
200 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000201 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000203 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000205 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 Instruction *visitURem(BinaryOperator &I);
207 Instruction *visitSRem(BinaryOperator &I);
208 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000209 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 Instruction *commonRemTransforms(BinaryOperator &I);
211 Instruction *commonIRemTransforms(BinaryOperator &I);
212 Instruction *commonDivTransforms(BinaryOperator &I);
213 Instruction *commonIDivTransforms(BinaryOperator &I);
214 Instruction *visitUDiv(BinaryOperator &I);
215 Instruction *visitSDiv(BinaryOperator &I);
216 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000217 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000218 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000220 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000221 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000222 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000223 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 Instruction *visitOr (BinaryOperator &I);
225 Instruction *visitXor(BinaryOperator &I);
226 Instruction *visitShl(BinaryOperator &I);
227 Instruction *visitAShr(BinaryOperator &I);
228 Instruction *visitLShr(BinaryOperator &I);
229 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000230 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
231 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 Instruction *visitFCmpInst(FCmpInst &I);
233 Instruction *visitICmpInst(ICmpInst &I);
234 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
235 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
236 Instruction *LHS,
237 ConstantInt *RHS);
238 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
239 ConstantInt *DivRHS);
240
Dan Gohman17f46f72009-07-28 01:40:03 +0000241 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 ICmpInst::Predicate Cond, Instruction &I);
243 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
244 BinaryOperator &I);
245 Instruction *commonCastTransforms(CastInst &CI);
246 Instruction *commonIntCastTransforms(CastInst &CI);
247 Instruction *commonPointerCastTransforms(CastInst &CI);
248 Instruction *visitTrunc(TruncInst &CI);
249 Instruction *visitZExt(ZExtInst &CI);
250 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000251 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000253 Instruction *visitFPToUI(FPToUIInst &FI);
254 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 Instruction *visitUIToFP(CastInst &CI);
256 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000257 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000258 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 Instruction *visitBitCast(BitCastInst &CI);
260 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
261 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000262 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000263 Instruction *visitSelectInst(SelectInst &SI);
264 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 Instruction *visitCallInst(CallInst &CI);
266 Instruction *visitInvokeInst(InvokeInst &II);
267 Instruction *visitPHINode(PHINode &PN);
268 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
269 Instruction *visitAllocationInst(AllocationInst &AI);
270 Instruction *visitFreeInst(FreeInst &FI);
271 Instruction *visitLoadInst(LoadInst &LI);
272 Instruction *visitStoreInst(StoreInst &SI);
273 Instruction *visitBranchInst(BranchInst &BI);
274 Instruction *visitSwitchInst(SwitchInst &SI);
275 Instruction *visitInsertElementInst(InsertElementInst &IE);
276 Instruction *visitExtractElementInst(ExtractElementInst &EI);
277 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000278 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279
280 // visitInstruction - Specify what to return for unhandled instructions...
281 Instruction *visitInstruction(Instruction &I) { return 0; }
282
283 private:
284 Instruction *visitCallSite(CallSite CS);
285 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000286 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000287 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
288 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000289 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000290 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
291
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292
293 public:
294 // InsertNewInstBefore - insert an instruction New before instruction Old
295 // in the program. Add the new instruction to the worklist.
296 //
297 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
298 assert(New && New->getParent() == 0 &&
299 "New instruction already inserted into a basic block!");
300 BasicBlock *BB = Old.getParent();
301 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000302 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 return New;
304 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000305
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 // ReplaceInstUsesWith - This method is to be used when an instruction is
307 // found to be dead, replacable with another preexisting expression. Here
308 // we add all uses of I to the worklist, replace all uses of I with the new
309 // value, then return I, so that the inst combiner will know that I was
310 // modified.
311 //
312 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000313 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000314
315 // If we are replacing the instruction with itself, this must be in a
316 // segment of unreachable code, so just clobber the instruction.
317 if (&I == V)
318 V = UndefValue::get(I.getType());
319
320 I.replaceAllUsesWith(V);
321 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 }
323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 // EraseInstFromFunction - When dealing with an instruction that has side
325 // effects or produces a void value, we can't rely on DCE to delete the
326 // instruction. Instead, visit methods should return the value returned by
327 // this function.
328 Instruction *EraseInstFromFunction(Instruction &I) {
Dan Gohman37a534b2009-09-16 02:01:52 +0000329 DEBUG(errs() << "IC: erase " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000330
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000332 // Make sure that we reprocess all operands now that we reduced their
333 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000334 if (I.getNumOperands() < 8) {
335 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
336 if (Instruction *Op = dyn_cast<Instruction>(*i))
337 Worklist.Add(Op);
338 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000339 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000341 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 return 0; // Don't do anything with FI
343 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000344
345 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
346 APInt &KnownOne, unsigned Depth = 0) const {
347 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
348 }
349
350 bool MaskedValueIsZero(Value *V, const APInt &Mask,
351 unsigned Depth = 0) const {
352 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
353 }
354 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
355 return llvm::ComputeNumSignBits(Op, TD, Depth);
356 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357
358 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359
360 /// SimplifyCommutative - This performs a few simplifications for
361 /// commutative operators.
362 bool SimplifyCommutative(BinaryOperator &I);
363
364 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
365 /// most-complex to least-complex order.
366 bool SimplifyCompare(CmpInst &I);
367
Chris Lattner676c78e2009-01-31 08:15:18 +0000368 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
369 /// based on the demanded bits.
370 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
371 APInt& KnownZero, APInt& KnownOne,
372 unsigned Depth);
373 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000375 unsigned Depth=0);
376
377 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
378 /// SimplifyDemandedBits knows about. See if the instruction has any
379 /// properties that allow us to simplify its operands.
380 bool SimplifyDemandedInstructionBits(Instruction &Inst);
381
Evan Cheng63295ab2009-02-03 10:05:09 +0000382 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
383 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
385 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
386 // PHI node as operand #0, see if we can fold the instruction into the PHI
387 // (which is only possible if all operands to the PHI are constants).
388 Instruction *FoldOpIntoPhi(Instruction &I);
389
390 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
391 // operator and they all are only used by the PHI, PHI together their
392 // inputs, and do the operation once, to the result of the PHI.
393 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
394 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000395 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
396
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397
398 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
399 ConstantInt *AndRHS, BinaryOperator &TheAnd);
400
401 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
402 bool isSub, Instruction &I);
403 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
404 bool isSigned, bool Inside, Instruction &IB);
405 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
406 Instruction *MatchBSwap(BinaryOperator &I);
407 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000408 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000409 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000410
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411
412 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000413
Dan Gohman8fd520a2009-06-15 22:12:54 +0000414 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000415 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000416 unsigned GetOrEnforceKnownAlignment(Value *V,
417 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 };
Chris Lattner5119c702009-08-30 05:55:36 +0000420} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421
Dan Gohman089efff2008-05-13 00:00:25 +0000422char InstCombiner::ID = 0;
423static RegisterPass<InstCombiner>
424X("instcombine", "Combine redundant instructions");
425
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426// getComplexity: Assign a complexity or rank value to LLVM Values...
427// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000428static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000430 if (BinaryOperator::isNeg(V) ||
431 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000432 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 return 3;
434 return 4;
435 }
436 if (isa<Argument>(V)) return 3;
437 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
438}
439
440// isOnlyUse - Return true if this instruction will be deleted if we stop using
441// it.
442static bool isOnlyUse(Value *V) {
443 return V->hasOneUse() || isa<Constant>(V);
444}
445
446// getPromotedType - Return the specified type promoted as it would be to pass
447// though a va_arg area...
448static const Type *getPromotedType(const Type *Ty) {
449 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
450 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000451 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 }
453 return Ty;
454}
455
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000456/// getBitCastOperand - If the specified operand is a CastInst, a constant
457/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
458/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000460 if (Operator *O = dyn_cast<Operator>(V)) {
461 if (O->getOpcode() == Instruction::BitCast)
462 return O->getOperand(0);
463 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
464 if (GEP->hasAllZeroIndices())
465 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000466 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 return 0;
468}
469
470/// This function is a wrapper around CastInst::isEliminableCastPair. It
471/// simply extracts arguments and returns what that function returns.
472static Instruction::CastOps
473isEliminableCastPair(
474 const CastInst *CI, ///< The first cast instruction
475 unsigned opcode, ///< The opcode of the second cast instruction
476 const Type *DstTy, ///< The target type for the second cast instruction
477 TargetData *TD ///< The target data for pointer size
478) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000479
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
481 const Type *MidTy = CI->getType(); // B from above
482
483 // Get the opcodes of the two Cast instructions
484 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
486
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000487 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000488 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000489 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000490
491 // We don't want to form an inttoptr or ptrtoint that converts to an integer
492 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000493 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000494 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000495 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000496 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000497 Res = 0;
498
499 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500}
501
502/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
503/// in any code being generated. It does not require codegen if V is simple
504/// enough or if the cast can be folded into other casts.
505static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
506 const Type *Ty, TargetData *TD) {
507 if (V->getType() == Ty || isa<Constant>(V)) return false;
508
509 // If this is another cast that can be eliminated, it isn't codegen either.
510 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000511 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 return false;
513 return true;
514}
515
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516// SimplifyCommutative - This performs a few simplifications for commutative
517// operators:
518//
519// 1. Order operands such that they are listed from right (least complex) to
520// left (most complex). This puts constants before unary operators before
521// binary operators.
522//
523// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
524// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
525//
526bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
527 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000528 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 Changed = !I.swapOperands();
530
531 if (!I.isAssociative()) return Changed;
532 Instruction::BinaryOps Opcode = I.getOpcode();
533 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
534 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
535 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000536 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 cast<Constant>(I.getOperand(1)),
538 cast<Constant>(Op->getOperand(1)));
539 I.setOperand(0, Op->getOperand(0));
540 I.setOperand(1, Folded);
541 return true;
542 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
543 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
544 isOnlyUse(Op) && isOnlyUse(Op1)) {
545 Constant *C1 = cast<Constant>(Op->getOperand(1));
546 Constant *C2 = cast<Constant>(Op1->getOperand(1));
547
548 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000549 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000550 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551 Op1->getOperand(0),
552 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000553 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 I.setOperand(0, New);
555 I.setOperand(1, Folded);
556 return true;
557 }
558 }
559 return Changed;
560}
561
562/// SimplifyCompare - For a CmpInst this function just orders the operands
563/// so that theyare listed from right (least complex) to left (most complex).
564/// This puts constants before unary operators before binary operators.
565bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman5d138f92009-08-29 23:39:38 +0000566 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 return false;
568 I.swapOperands();
569 // Compare instructions are not associative so there's nothing else we can do.
570 return true;
571}
572
573// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
574// if the LHS is a constant zero (which is the 'negate' form).
575//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000576static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000577 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 return BinaryOperator::getNegArgument(V);
579
580 // Constants can be considered to be negated values if they can be folded.
581 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000582 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000583
584 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
585 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000586 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000587
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 return 0;
589}
590
Dan Gohman7ce405e2009-06-04 22:49:04 +0000591// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
592// instruction if the LHS is a constant negative zero (which is the 'negate'
593// form).
594//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000595static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000596 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000597 return BinaryOperator::getFNegArgument(V);
598
599 // Constants can be considered to be negated values if they can be folded.
600 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000601 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000602
603 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
604 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000605 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000606
607 return 0;
608}
609
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000610static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 if (BinaryOperator::isNot(V))
612 return BinaryOperator::getNotArgument(V);
613
614 // Constants can be considered to be not'ed values...
615 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000616 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 return 0;
618}
619
620// dyn_castFoldableMul - If this value is a multiply that can be folded into
621// other computations (because it has a constant operand), return the
622// non-constant operand of the multiply, and set CST to point to the multiplier.
623// Otherwise, return null.
624//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000625static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 if (V->hasOneUse() && V->getType()->isInteger())
627 if (Instruction *I = dyn_cast<Instruction>(V)) {
628 if (I->getOpcode() == Instruction::Mul)
629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
630 return I->getOperand(0);
631 if (I->getOpcode() == Instruction::Shl)
632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
633 // The multiplier is really 1 << CST.
634 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
635 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000636 CST = ConstantInt::get(V->getType()->getContext(),
637 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 return I->getOperand(0);
639 }
640 }
641 return 0;
642}
643
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000645static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000646 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000647 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648}
649/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000650static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000651 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000652 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000654/// MultiplyOverflows - True if the multiply can not be expressed in an int
655/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000656static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000657 uint32_t W = C1->getBitWidth();
658 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
659 if (sign) {
660 LHSExt.sext(W * 2);
661 RHSExt.sext(W * 2);
662 } else {
663 LHSExt.zext(W * 2);
664 RHSExt.zext(W * 2);
665 }
666
667 APInt MulExt = LHSExt * RHSExt;
668
669 if (sign) {
670 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672 return MulExt.slt(Min) || MulExt.sgt(Max);
673 } else
674 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
675}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677
678/// ShrinkDemandedConstant - Check to see if the specified operand of the
679/// specified instruction is a constant integer. If so, check to see if there
680/// are any bits set in the constant that are not demanded. If so, shrink the
681/// constant and return true.
682static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000683 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 assert(I && "No instruction?");
685 assert(OpNo < I->getNumOperands() && "Operand index too large");
686
687 // If the operand is not a constant integer, nothing to do.
688 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689 if (!OpC) return false;
690
691 // If there are no bits set that aren't demanded, nothing to do.
692 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693 if ((~Demanded & OpC->getValue()) == 0)
694 return false;
695
696 // This instruction is producing bits that are not demanded. Shrink the RHS.
697 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000698 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 return true;
700}
701
702// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
703// set of known zero and one bits, compute the maximum and minimum values that
704// could have the specified known zero and known one bits, returning them in
705// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000706static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 const APInt& KnownOne,
708 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000709 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
710 KnownZero.getBitWidth() == Min.getBitWidth() &&
711 KnownZero.getBitWidth() == Max.getBitWidth() &&
712 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 APInt UnknownBits = ~(KnownZero|KnownOne);
714
715 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
716 // bit if it is unknown.
717 Min = KnownOne;
718 Max = KnownOne|UnknownBits;
719
Dan Gohman7934d592009-04-25 17:12:48 +0000720 if (UnknownBits.isNegative()) { // Sign bit is unknown
721 Min.set(Min.getBitWidth()-1);
722 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 }
724}
725
726// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
727// a set of known zero and one bits, compute the maximum and minimum values that
728// could have the specified known zero and known one bits, returning them in
729// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000730static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000731 const APInt &KnownOne,
732 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000733 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
734 KnownZero.getBitWidth() == Min.getBitWidth() &&
735 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
737 APInt UnknownBits = ~(KnownZero|KnownOne);
738
739 // The minimum value is when the unknown bits are all zeros.
740 Min = KnownOne;
741 // The maximum value is when the unknown bits are all ones.
742 Max = KnownOne|UnknownBits;
743}
744
Chris Lattner676c78e2009-01-31 08:15:18 +0000745/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
746/// SimplifyDemandedBits knows about. See if the instruction has any
747/// properties that allow us to simplify its operands.
748bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000749 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000750 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
751 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
752
753 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
754 KnownZero, KnownOne, 0);
755 if (V == 0) return false;
756 if (V == &Inst) return true;
757 ReplaceInstUsesWith(Inst, V);
758 return true;
759}
760
761/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
762/// specified instruction operand if possible, updating it in place. It returns
763/// true if it made any change and false otherwise.
764bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
765 APInt &KnownZero, APInt &KnownOne,
766 unsigned Depth) {
767 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
768 KnownZero, KnownOne, Depth);
769 if (NewVal == 0) return false;
770 U.set(NewVal);
771 return true;
772}
773
774
775/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
776/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777/// that only the bits set in DemandedMask of the result of V are ever used
778/// downstream. Consequently, depending on the mask and V, it may be possible
779/// to replace V with a constant or one of its operands. In such cases, this
780/// function does the replacement and returns true. In all other cases, it
781/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000782/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783/// to be zero in the expression. These are provided to potentially allow the
784/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
785/// the expression. KnownOne and KnownZero always follow the invariant that
786/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
787/// the bits in KnownOne and KnownZero may only be accurate for those bits set
788/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
789/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000790///
791/// This returns null if it did not change anything and it permits no
792/// simplification. This returns V itself if it did some simplification of V's
793/// operands based on the information about what bits are demanded. This returns
794/// some other non-null value if it found out that V is equal to another value
795/// in the context where the specified bits are demanded, but not for all users.
796Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
797 APInt &KnownZero, APInt &KnownOne,
798 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 assert(V != 0 && "Null pointer of Value???");
800 assert(Depth <= 6 && "Limit Search Depth");
801 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000802 const Type *VTy = V->getType();
803 assert((TD || !isa<PointerType>(VTy)) &&
804 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000805 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
806 (!VTy->isIntOrIntVector() ||
807 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000808 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000810 "Value *V, DemandedMask, KnownZero and KnownOne "
811 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
813 // We know all of the bits for a constant!
814 KnownOne = CI->getValue() & DemandedMask;
815 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000816 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 }
Dan Gohman7934d592009-04-25 17:12:48 +0000818 if (isa<ConstantPointerNull>(V)) {
819 // We know all of the bits for a constant!
820 KnownOne.clear();
821 KnownZero = DemandedMask;
822 return 0;
823 }
824
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000825 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000827 if (DemandedMask == 0) { // Not demanding any bits from V.
828 if (isa<UndefValue>(V))
829 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000830 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 }
832
Chris Lattner08817332009-01-31 08:24:16 +0000833 if (Depth == 6) // Limit search depth.
834 return 0;
835
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000836 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
837 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
838
Dan Gohman7934d592009-04-25 17:12:48 +0000839 Instruction *I = dyn_cast<Instruction>(V);
840 if (!I) {
841 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
842 return 0; // Only analyze instructions.
843 }
844
Chris Lattner08817332009-01-31 08:24:16 +0000845 // If there are multiple uses of this value and we aren't at the root, then
846 // we can't do any simplifications of the operands, because DemandedMask
847 // only reflects the bits demanded by *one* of the users.
848 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000849 // Despite the fact that we can't simplify this instruction in all User's
850 // context, we can at least compute the knownzero/knownone bits, and we can
851 // do simplifications that apply to *just* the one user if we know that
852 // this instruction has a simpler value in that context.
853 if (I->getOpcode() == Instruction::And) {
854 // If either the LHS or the RHS are Zero, the result is zero.
855 ComputeMaskedBits(I->getOperand(1), DemandedMask,
856 RHSKnownZero, RHSKnownOne, Depth+1);
857 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
858 LHSKnownZero, LHSKnownOne, Depth+1);
859
860 // If all of the demanded bits are known 1 on one side, return the other.
861 // These bits cannot contribute to the result of the 'and' in this
862 // context.
863 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
864 (DemandedMask & ~LHSKnownZero))
865 return I->getOperand(0);
866 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
867 (DemandedMask & ~RHSKnownZero))
868 return I->getOperand(1);
869
870 // If all of the demanded bits in the inputs are known zeros, return zero.
871 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000872 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000873
874 } else if (I->getOpcode() == Instruction::Or) {
875 // We can simplify (X|Y) -> X or Y in the user's context if we know that
876 // only bits from X or Y are demanded.
877
878 // If either the LHS or the RHS are One, the result is One.
879 ComputeMaskedBits(I->getOperand(1), DemandedMask,
880 RHSKnownZero, RHSKnownOne, Depth+1);
881 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
882 LHSKnownZero, LHSKnownOne, Depth+1);
883
884 // If all of the demanded bits are known zero on one side, return the
885 // other. These bits cannot contribute to the result of the 'or' in this
886 // context.
887 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
888 (DemandedMask & ~LHSKnownOne))
889 return I->getOperand(0);
890 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
891 (DemandedMask & ~RHSKnownOne))
892 return I->getOperand(1);
893
894 // If all of the potentially set bits on one side are known to be set on
895 // the other side, just use the 'other' side.
896 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
897 (DemandedMask & (~RHSKnownZero)))
898 return I->getOperand(0);
899 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
900 (DemandedMask & (~LHSKnownZero)))
901 return I->getOperand(1);
902 }
903
Chris Lattner08817332009-01-31 08:24:16 +0000904 // Compute the KnownZero/KnownOne bits to simplify things downstream.
905 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
906 return 0;
907 }
908
909 // If this is the root being simplified, allow it to have multiple uses,
910 // just set the DemandedMask to all bits so that we can try to simplify the
911 // operands. This allows visitTruncInst (for example) to simplify the
912 // operand of a trunc without duplicating all the logic below.
913 if (Depth == 0 && !V->hasOneUse())
914 DemandedMask = APInt::getAllOnesValue(BitWidth);
915
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000917 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000918 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000919 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 case Instruction::And:
921 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000922 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
923 RHSKnownZero, RHSKnownOne, Depth+1) ||
924 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000926 return I;
927 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
928 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929
930 // If all of the demanded bits are known 1 on one side, return the other.
931 // These bits cannot contribute to the result of the 'and'.
932 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
933 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000934 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
936 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000937 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938
939 // If all of the demanded bits in the inputs are known zeros, return zero.
940 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000941 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942
943 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000944 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000945 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946
947 // Output known-1 bits are only known if set in both the LHS & RHS.
948 RHSKnownOne &= LHSKnownOne;
949 // Output known-0 are known to be clear if zero in either the LHS | RHS.
950 RHSKnownZero |= LHSKnownZero;
951 break;
952 case Instruction::Or:
953 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000954 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
955 RHSKnownZero, RHSKnownOne, Depth+1) ||
956 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000958 return I;
959 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
960 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961
962 // If all of the demanded bits are known zero on one side, return the other.
963 // These bits cannot contribute to the result of the 'or'.
964 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
965 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000966 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
968 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000969 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970
971 // If all of the potentially set bits on one side are known to be set on
972 // the other side, just use the 'other' side.
973 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
974 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000975 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
977 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000978 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979
980 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000981 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000982 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983
984 // Output known-0 bits are only known if clear in both the LHS & RHS.
985 RHSKnownZero &= LHSKnownZero;
986 // Output known-1 are known to be set if set in either the LHS | RHS.
987 RHSKnownOne |= LHSKnownOne;
988 break;
989 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
991 RHSKnownZero, RHSKnownOne, Depth+1) ||
992 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000994 return I;
995 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
996 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997
998 // If all of the demanded bits are known zero on one side, return the other.
999 // These bits cannot contribute to the result of the 'xor'.
1000 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001001 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001003 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004
1005 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1006 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1007 (RHSKnownOne & LHSKnownOne);
1008 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1009 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1010 (RHSKnownOne & LHSKnownZero);
1011
1012 // If all of the demanded bits are known to be zero on one side or the
1013 // other, turn this into an *inclusive* or.
1014 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001015 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1016 Instruction *Or =
1017 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1018 I->getName());
1019 return InsertNewInstBefore(Or, *I);
1020 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021
1022 // If all of the demanded bits on one side are known, and all of the set
1023 // bits on that side are also known to be set on the other side, turn this
1024 // into an AND, as we know the bits will be cleared.
1025 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1026 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1027 // all known
1028 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001029 Constant *AndC = Constant::getIntegerValue(VTy,
1030 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001032 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001033 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 }
1035 }
1036
1037 // If the RHS is a constant, see if we can simplify it.
1038 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001039 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001040 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041
1042 RHSKnownZero = KnownZeroOut;
1043 RHSKnownOne = KnownOneOut;
1044 break;
1045 }
1046 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001047 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1048 RHSKnownZero, RHSKnownOne, Depth+1) ||
1049 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001051 return I;
1052 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1053 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054
1055 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001056 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1057 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001058 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
1060 // Only known if known in both the LHS and RHS.
1061 RHSKnownOne &= LHSKnownOne;
1062 RHSKnownZero &= LHSKnownZero;
1063 break;
1064 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001065 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 DemandedMask.zext(truncBf);
1067 RHSKnownZero.zext(truncBf);
1068 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001069 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001071 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 DemandedMask.trunc(BitWidth);
1073 RHSKnownZero.trunc(BitWidth);
1074 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001075 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 break;
1077 }
1078 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001079 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001080 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001081
1082 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1083 if (const VectorType *SrcVTy =
1084 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1085 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1086 // Don't touch a bitcast between vectors of different element counts.
1087 return false;
1088 } else
1089 // Don't touch a scalar-to-vector bitcast.
1090 return false;
1091 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1092 // Don't touch a vector-to-scalar bitcast.
1093 return false;
1094
Chris Lattner676c78e2009-01-31 08:15:18 +00001095 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001097 return I;
1098 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 break;
1100 case Instruction::ZExt: {
1101 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001102 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103
1104 DemandedMask.trunc(SrcBitWidth);
1105 RHSKnownZero.trunc(SrcBitWidth);
1106 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001107 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001109 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 DemandedMask.zext(BitWidth);
1111 RHSKnownZero.zext(BitWidth);
1112 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001113 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 // The top bits are known to be zero.
1115 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1116 break;
1117 }
1118 case Instruction::SExt: {
1119 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001120 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121
1122 APInt InputDemandedBits = DemandedMask &
1123 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1124
1125 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1126 // If any of the sign extended bits are demanded, we know that the sign
1127 // bit is demanded.
1128 if ((NewBits & DemandedMask) != 0)
1129 InputDemandedBits.set(SrcBitWidth-1);
1130
1131 InputDemandedBits.trunc(SrcBitWidth);
1132 RHSKnownZero.trunc(SrcBitWidth);
1133 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001134 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001136 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 InputDemandedBits.zext(BitWidth);
1138 RHSKnownZero.zext(BitWidth);
1139 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001140 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141
1142 // If the sign bit of the input is known set or clear, then we know the
1143 // top bits of the result.
1144
1145 // If the input sign bit is known zero, or if the NewBits are not demanded
1146 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001147 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001149 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1150 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1152 RHSKnownOne |= NewBits;
1153 }
1154 break;
1155 }
1156 case Instruction::Add: {
1157 // Figure out what the input bits are. If the top bits of the and result
1158 // are not demanded, then the add doesn't demand them from its input
1159 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001160 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161
1162 // If there is a constant on the RHS, there are a variety of xformations
1163 // we can do.
1164 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1165 // If null, this should be simplified elsewhere. Some of the xforms here
1166 // won't work if the RHS is zero.
1167 if (RHS->isZero())
1168 break;
1169
1170 // If the top bit of the output is demanded, demand everything from the
1171 // input. Otherwise, we demand all the input bits except NLZ top bits.
1172 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1173
1174 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001175 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001176 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001177 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178
1179 // If the RHS of the add has bits set that can't affect the input, reduce
1180 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001181 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001182 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183
1184 // Avoid excess work.
1185 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1186 break;
1187
1188 // Turn it into OR if input bits are zero.
1189 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1190 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001191 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001193 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 }
1195
1196 // We can say something about the output known-zero and known-one bits,
1197 // depending on potential carries from the input constant and the
1198 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1199 // bits set and the RHS constant is 0x01001, then we know we have a known
1200 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1201
1202 // To compute this, we first compute the potential carry bits. These are
1203 // the bits which may be modified. I'm not aware of a better way to do
1204 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001205 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1207
1208 // Now that we know which bits have carries, compute the known-1/0 sets.
1209
1210 // Bits are known one if they are known zero in one operand and one in the
1211 // other, and there is no input carry.
1212 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1213 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1214
1215 // Bits are known zero if they are known zero in both operands and there
1216 // is no input carry.
1217 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1218 } else {
1219 // If the high-bits of this ADD are not demanded, then it does not demand
1220 // the high bits of its LHS or RHS.
1221 if (DemandedMask[BitWidth-1] == 0) {
1222 // Right fill the mask of bits for this ADD to demand the most
1223 // significant bit and all those below it.
1224 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001225 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1226 LHSKnownZero, LHSKnownOne, Depth+1) ||
1227 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001229 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 }
1231 }
1232 break;
1233 }
1234 case Instruction::Sub:
1235 // If the high-bits of this SUB are not demanded, then it does not demand
1236 // the high bits of its LHS or RHS.
1237 if (DemandedMask[BitWidth-1] == 0) {
1238 // Right fill the mask of bits for this SUB to demand the most
1239 // significant bit and all those below it.
1240 uint32_t NLZ = DemandedMask.countLeadingZeros();
1241 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001242 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1243 LHSKnownZero, LHSKnownOne, Depth+1) ||
1244 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001246 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001248 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1249 // the known zeros and ones.
1250 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 break;
1252 case Instruction::Shl:
1253 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1254 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1255 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001256 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001258 return I;
1259 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 RHSKnownZero <<= ShiftAmt;
1261 RHSKnownOne <<= ShiftAmt;
1262 // low bits known zero.
1263 if (ShiftAmt)
1264 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1265 }
1266 break;
1267 case Instruction::LShr:
1268 // For a logical shift right
1269 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1271
1272 // Unsigned shift right.
1273 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001274 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001276 return I;
1277 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1279 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1280 if (ShiftAmt) {
1281 // Compute the new bits that are at the top now.
1282 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1283 RHSKnownZero |= HighBits; // high bits known zero.
1284 }
1285 }
1286 break;
1287 case Instruction::AShr:
1288 // If this is an arithmetic shift right and only the low-bit is set, we can
1289 // always convert this into a logical shr, even if the shift amount is
1290 // variable. The low bit of the shift cannot be an input sign bit unless
1291 // the shift amount is >= the size of the datatype, which is undefined.
1292 if (DemandedMask == 1) {
1293 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001294 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001296 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 }
1298
1299 // If the sign bit is the only bit demanded by this ashr, then there is no
1300 // need to do it, the shift doesn't change the high bit.
1301 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001302 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303
1304 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1305 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1306
1307 // Signed shift right.
1308 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1309 // If any of the "high bits" are demanded, we should set the sign bit as
1310 // demanded.
1311 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1312 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001313 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001315 return I;
1316 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 // Compute the new bits that are at the top now.
1318 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1319 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1320 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1321
1322 // Handle the sign bits.
1323 APInt SignBit(APInt::getSignBit(BitWidth));
1324 // Adjust to where it is now in the mask.
1325 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1326
1327 // If the input sign bit is known to be zero, or if none of the top bits
1328 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001329 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 (HighBits & ~DemandedMask) == HighBits) {
1331 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001332 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001334 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1336 RHSKnownOne |= HighBits;
1337 }
1338 }
1339 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001340 case Instruction::SRem:
1341 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001342 APInt RA = Rem->getValue().abs();
1343 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001344 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001345 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001346
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001347 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001348 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001349 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001350 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001351 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001352
1353 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1354 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001355
1356 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001357
Chris Lattner676c78e2009-01-31 08:15:18 +00001358 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001359 }
1360 }
1361 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001362 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001363 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1364 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001365 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1366 KnownZero2, KnownOne2, Depth+1) ||
1367 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001368 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001369 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001370
Chris Lattneree5417c2009-01-21 18:09:24 +00001371 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001372 Leaders = std::max(Leaders,
1373 KnownZero2.countLeadingOnes());
1374 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001375 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 }
Chris Lattner989ba312008-06-18 04:33:20 +00001377 case Instruction::Call:
1378 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1379 switch (II->getIntrinsicID()) {
1380 default: break;
1381 case Intrinsic::bswap: {
1382 // If the only bits demanded come from one byte of the bswap result,
1383 // just shift the input byte into position to eliminate the bswap.
1384 unsigned NLZ = DemandedMask.countLeadingZeros();
1385 unsigned NTZ = DemandedMask.countTrailingZeros();
1386
1387 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1388 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1389 // have 14 leading zeros, round to 8.
1390 NLZ &= ~7;
1391 NTZ &= ~7;
1392 // If we need exactly one byte, we can do this transformation.
1393 if (BitWidth-NLZ-NTZ == 8) {
1394 unsigned ResultBit = NTZ;
1395 unsigned InputBit = BitWidth-NTZ-8;
1396
1397 // Replace this with either a left or right shift to get the byte into
1398 // the right place.
1399 Instruction *NewVal;
1400 if (InputBit > ResultBit)
1401 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001402 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001403 else
1404 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001405 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001406 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001407 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001408 }
1409
1410 // TODO: Could compute known zero/one bits based on the input.
1411 break;
1412 }
1413 }
1414 }
Chris Lattner4946e222008-06-18 18:11:55 +00001415 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001416 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418
1419 // If the client is only demanding bits that we know, return the known
1420 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001421 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1422 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 return false;
1424}
1425
1426
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001427/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001428/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429/// actually used by the caller. This method analyzes which elements of the
1430/// operand are undef and returns that information in UndefElts.
1431///
1432/// If the information about demanded elements can be used to simplify the
1433/// operation, the operation is simplified, then the resultant value is
1434/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001435Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1436 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 unsigned Depth) {
1438 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001439 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001440 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441
1442 if (isa<UndefValue>(V)) {
1443 // If the entire vector is undefined, just return this info.
1444 UndefElts = EltMask;
1445 return 0;
1446 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1447 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001448 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001450
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 UndefElts = 0;
1452 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1453 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001454 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455
1456 std::vector<Constant*> Elts;
1457 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001458 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001460 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001461 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1462 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001463 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 } else { // Otherwise, defined.
1465 Elts.push_back(CP->getOperand(i));
1466 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001467
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001469 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 return NewCP != CP ? NewCP : 0;
1471 } else if (isa<ConstantAggregateZero>(V)) {
1472 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1473 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001474
1475 // Check if this is identity. If so, return 0 since we are not simplifying
1476 // anything.
1477 if (DemandedElts == ((1ULL << VWidth) -1))
1478 return 0;
1479
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001480 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001481 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001482 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001484 for (unsigned i = 0; i != VWidth; ++i) {
1485 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1486 Elts.push_back(Elt);
1487 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001489 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 }
1491
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001492 // Limit search depth.
1493 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001494 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001495
1496 // If multiple users are using the root value, procede with
1497 // simplification conservatively assuming that all elements
1498 // are needed.
1499 if (!V->hasOneUse()) {
1500 // Quit if we find multiple users of a non-root value though.
1501 // They'll be handled when it's their turn to be visited by
1502 // the main instcombine process.
1503 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001505 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001506
1507 // Conservatively assume that all elements are needed.
1508 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 }
1510
1511 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001512 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513
1514 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001515 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 Value *TmpV;
1517 switch (I->getOpcode()) {
1518 default: break;
1519
1520 case Instruction::InsertElement: {
1521 // If this is a variable index, we don't know which element it overwrites.
1522 // demand exactly the same input as we produce.
1523 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1524 if (Idx == 0) {
1525 // Note that we can't propagate undef elt info, because we don't know
1526 // which elt is getting updated.
1527 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1528 UndefElts2, Depth+1);
1529 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1530 break;
1531 }
1532
1533 // If this is inserting an element that isn't demanded, remove this
1534 // insertelement.
1535 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001536 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1537 Worklist.Add(I);
1538 return I->getOperand(0);
1539 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540
1541 // Otherwise, the element inserted overwrites whatever was there, so the
1542 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001543 APInt DemandedElts2 = DemandedElts;
1544 DemandedElts2.clear(IdxNo);
1545 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 UndefElts, Depth+1);
1547 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1548
1549 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001550 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001551 break;
1552 }
1553 case Instruction::ShuffleVector: {
1554 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001555 uint64_t LHSVWidth =
1556 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001557 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001558 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001559 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001560 unsigned MaskVal = Shuffle->getMaskValue(i);
1561 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001562 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001563 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001564 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001565 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001566 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001567 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001568 }
1569 }
1570 }
1571
Nate Begemanb4d176f2009-02-11 22:36:25 +00001572 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001573 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001574 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001575 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1576
Nate Begemanb4d176f2009-02-11 22:36:25 +00001577 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001578 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1579 UndefElts3, Depth+1);
1580 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1581
1582 bool NewUndefElts = false;
1583 for (unsigned i = 0; i < VWidth; i++) {
1584 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001585 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001586 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001587 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001588 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001589 NewUndefElts = true;
1590 UndefElts.set(i);
1591 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001592 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001593 if (UndefElts3[MaskVal - LHSVWidth]) {
1594 NewUndefElts = true;
1595 UndefElts.set(i);
1596 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001597 }
1598 }
1599
1600 if (NewUndefElts) {
1601 // Add additional discovered undefs.
1602 std::vector<Constant*> Elts;
1603 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001604 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001605 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001606 else
Owen Anderson35b47072009-08-13 21:58:54 +00001607 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001608 Shuffle->getMaskValue(i)));
1609 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001610 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001611 MadeChange = true;
1612 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001613 break;
1614 }
1615 case Instruction::BitCast: {
1616 // Vector->vector casts only.
1617 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1618 if (!VTy) break;
1619 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001620 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001621 unsigned Ratio;
1622
1623 if (VWidth == InVWidth) {
1624 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1625 // elements as are demanded of us.
1626 Ratio = 1;
1627 InputDemandedElts = DemandedElts;
1628 } else if (VWidth > InVWidth) {
1629 // Untested so far.
1630 break;
1631
1632 // If there are more elements in the result than there are in the source,
1633 // then an input element is live if any of the corresponding output
1634 // elements are live.
1635 Ratio = VWidth/InVWidth;
1636 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001637 if (DemandedElts[OutIdx])
1638 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 }
1640 } else {
1641 // Untested so far.
1642 break;
1643
1644 // If there are more elements in the source than there are in the result,
1645 // then an input element is live if the corresponding output element is
1646 // live.
1647 Ratio = InVWidth/VWidth;
1648 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001649 if (DemandedElts[InIdx/Ratio])
1650 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001651 }
1652
1653 // div/rem demand all inputs, because they don't want divide by zero.
1654 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1655 UndefElts2, Depth+1);
1656 if (TmpV) {
1657 I->setOperand(0, TmpV);
1658 MadeChange = true;
1659 }
1660
1661 UndefElts = UndefElts2;
1662 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001663 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664 // If there are more elements in the result than there are in the source,
1665 // then an output element is undef if the corresponding input element is
1666 // undef.
1667 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001668 if (UndefElts2[OutIdx/Ratio])
1669 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001671 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672 // If there are more elements in the source than there are in the result,
1673 // then a result element is undef if all of the corresponding input
1674 // elements are undef.
1675 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1676 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001677 if (!UndefElts2[InIdx]) // Not undef?
1678 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 }
1680 break;
1681 }
1682 case Instruction::And:
1683 case Instruction::Or:
1684 case Instruction::Xor:
1685 case Instruction::Add:
1686 case Instruction::Sub:
1687 case Instruction::Mul:
1688 // div/rem demand all inputs, because they don't want divide by zero.
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1690 UndefElts, Depth+1);
1691 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1692 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1693 UndefElts2, Depth+1);
1694 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1695
1696 // Output elements are undefined if both are undefined. Consider things
1697 // like undef&0. The result is known zero, not undef.
1698 UndefElts &= UndefElts2;
1699 break;
1700
1701 case Instruction::Call: {
1702 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1703 if (!II) break;
1704 switch (II->getIntrinsicID()) {
1705 default: break;
1706
1707 // Binary vector operations that work column-wise. A dest element is a
1708 // function of the corresponding input elements from the two inputs.
1709 case Intrinsic::x86_sse_sub_ss:
1710 case Intrinsic::x86_sse_mul_ss:
1711 case Intrinsic::x86_sse_min_ss:
1712 case Intrinsic::x86_sse_max_ss:
1713 case Intrinsic::x86_sse2_sub_sd:
1714 case Intrinsic::x86_sse2_mul_sd:
1715 case Intrinsic::x86_sse2_min_sd:
1716 case Intrinsic::x86_sse2_max_sd:
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1718 UndefElts, Depth+1);
1719 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1720 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1721 UndefElts2, Depth+1);
1722 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1723
1724 // If only the low elt is demanded and this is a scalarizable intrinsic,
1725 // scalarize it now.
1726 if (DemandedElts == 1) {
1727 switch (II->getIntrinsicID()) {
1728 default: break;
1729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse_mul_ss:
1731 case Intrinsic::x86_sse2_sub_sd:
1732 case Intrinsic::x86_sse2_mul_sd:
1733 // TODO: Lower MIN/MAX/ABS/etc
1734 Value *LHS = II->getOperand(1);
1735 Value *RHS = II->getOperand(2);
1736 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001737 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001738 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001739 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001740 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741
1742 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001743 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 case Intrinsic::x86_sse_sub_ss:
1745 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747 II->getName()), *II);
1748 break;
1749 case Intrinsic::x86_sse_mul_ss:
1750 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001751 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752 II->getName()), *II);
1753 break;
1754 }
1755
1756 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001757 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001758 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001759 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 return New;
1762 }
1763 }
1764
1765 // Output elements are undefined if both are undefined. Consider things
1766 // like undef&0. The result is known zero, not undef.
1767 UndefElts &= UndefElts2;
1768 break;
1769 }
1770 break;
1771 }
1772 }
1773 return MadeChange ? I : 0;
1774}
1775
Dan Gohman5d56fd42008-05-19 22:14:15 +00001776
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777/// AssociativeOpt - Perform an optimization on an associative operator. This
1778/// function is designed to check a chain of associative operators for a
1779/// potential to apply a certain optimization. Since the optimization may be
1780/// applicable if the expression was reassociated, this checks the chain, then
1781/// reassociates the expression as necessary to expose the optimization
1782/// opportunity. This makes use of a special Functor, which must define
1783/// 'shouldApply' and 'apply' methods.
1784///
1785template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001786static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001787 unsigned Opcode = Root.getOpcode();
1788 Value *LHS = Root.getOperand(0);
1789
1790 // Quick check, see if the immediate LHS matches...
1791 if (F.shouldApply(LHS))
1792 return F.apply(Root);
1793
1794 // Otherwise, if the LHS is not of the same opcode as the root, return.
1795 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1796 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1797 // Should we apply this transform to the RHS?
1798 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1799
1800 // If not to the RHS, check to see if we should apply to the LHS...
1801 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1802 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1803 ShouldApply = true;
1804 }
1805
1806 // If the functor wants to apply the optimization to the RHS of LHSI,
1807 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1808 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809 // Now all of the instructions are in the current basic block, go ahead
1810 // and perform the reassociation.
1811 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1812
1813 // First move the selected RHS to the LHS of the root...
1814 Root.setOperand(0, LHSI->getOperand(1));
1815
1816 // Make what used to be the LHS of the root be the user of the root...
1817 Value *ExtraOperand = TmpLHSI->getOperand(1);
1818 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001819 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001820 return 0;
1821 }
1822 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1823 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001824 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001825 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001826 ARI = Root;
1827
1828 // Now propagate the ExtraOperand down the chain of instructions until we
1829 // get to LHSI.
1830 while (TmpLHSI != LHSI) {
1831 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1832 // Move the instruction to immediately before the chain we are
1833 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001834 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 ARI = NextLHSI;
1836
1837 Value *NextOp = NextLHSI->getOperand(1);
1838 NextLHSI->setOperand(1, ExtraOperand);
1839 TmpLHSI = NextLHSI;
1840 ExtraOperand = NextOp;
1841 }
1842
1843 // Now that the instructions are reassociated, have the functor perform
1844 // the transformation...
1845 return F.apply(Root);
1846 }
1847
1848 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1849 }
1850 return 0;
1851}
1852
Dan Gohman089efff2008-05-13 00:00:25 +00001853namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854
Nick Lewycky27f6c132008-05-23 04:34:58 +00001855// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001856struct AddRHS {
1857 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001858 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001859 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1860 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001861 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001862 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 }
1864};
1865
1866// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1867// iff C1&C2 == 0
1868struct AddMaskingAnd {
1869 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001870 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871 bool shouldApply(Value *LHS) const {
1872 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001873 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001874 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875 }
1876 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001877 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001878 }
1879};
1880
Dan Gohman089efff2008-05-13 00:00:25 +00001881}
1882
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1884 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001885 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001886 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887
1888 // Figure out if the constant is the left or the right argument.
1889 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1890 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1891
1892 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1893 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001894 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1895 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 }
1897
1898 Value *Op0 = SO, *Op1 = ConstOperand;
1899 if (!ConstIsRHS)
1900 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001901
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001903 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1904 SO->getName()+".op");
1905 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1906 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1907 SO->getName()+".cmp");
1908 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1909 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1910 SO->getName()+".cmp");
1911 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001912}
1913
1914// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1915// constant as the other operand, try to fold the binary operator into the
1916// select arguments. This also works for Cast instructions, which obviously do
1917// not have a second operand.
1918static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1919 InstCombiner *IC) {
1920 // Don't modify shared select instructions
1921 if (!SI->hasOneUse()) return 0;
1922 Value *TV = SI->getOperand(1);
1923 Value *FV = SI->getOperand(2);
1924
1925 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1926 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00001927 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928
1929 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1930 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1931
Gabor Greifd6da1d02008-04-06 20:25:17 +00001932 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1933 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001934 }
1935 return 0;
1936}
1937
1938
1939/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1940/// node as operand #0, see if we can fold the instruction into the PHI (which
1941/// is only possible if all operands to the PHI are constants).
1942Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1943 PHINode *PN = cast<PHINode>(I.getOperand(0));
1944 unsigned NumPHIValues = PN->getNumIncomingValues();
1945 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1946
1947 // Check to see if all of the operands of the PHI are constants. If there is
1948 // one non-constant value, remember the BB it is. If there is more than one
1949 // or if *it* is a PHI, bail out.
1950 BasicBlock *NonConstBB = 0;
1951 for (unsigned i = 0; i != NumPHIValues; ++i)
1952 if (!isa<Constant>(PN->getIncomingValue(i))) {
1953 if (NonConstBB) return 0; // More than one non-const value.
1954 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1955 NonConstBB = PN->getIncomingBlock(i);
1956
1957 // If the incoming non-constant value is in I's block, we have an infinite
1958 // loop.
1959 if (NonConstBB == I.getParent())
1960 return 0;
1961 }
1962
1963 // If there is exactly one non-constant value, we can insert a copy of the
1964 // operation in that block. However, if this is a critical edge, we would be
1965 // inserting the computation one some other paths (e.g. inside a loop). Only
1966 // do this if the pred block is unconditionally branching into the phi block.
1967 if (NonConstBB) {
1968 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1969 if (!BI || !BI->isUnconditional()) return 0;
1970 }
1971
1972 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001973 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1975 InsertNewInstBefore(NewPN, *PN);
1976 NewPN->takeName(PN);
1977
1978 // Next, add all of the operands to the PHI.
1979 if (I.getNumOperands() == 2) {
1980 Constant *C = cast<Constant>(I.getOperand(1));
1981 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001982 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001983 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1984 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00001985 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986 else
Owen Anderson02b48c32009-07-29 18:55:55 +00001987 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 } else {
1989 assert(PN->getIncomingBlock(i) == NonConstBB);
1990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001991 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 PN->getIncomingValue(i), C, "phitmp",
1993 NonConstBB->getTerminator());
1994 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00001995 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 CI->getPredicate(),
1997 PN->getIncomingValue(i), C, "phitmp",
1998 NonConstBB->getTerminator());
1999 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002000 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001
Chris Lattner3183fb62009-08-30 06:13:40 +00002002 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002003 }
2004 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2005 }
2006 } else {
2007 CastInst *CI = cast<CastInst>(&I);
2008 const Type *RetTy = CI->getType();
2009 for (unsigned i = 0; i != NumPHIValues; ++i) {
2010 Value *InV;
2011 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002012 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013 } else {
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002015 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002016 I.getType(), "phitmp",
2017 NonConstBB->getTerminator());
Chris Lattner3183fb62009-08-30 06:13:40 +00002018 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019 }
2020 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2021 }
2022 }
2023 return ReplaceInstUsesWith(I, NewPN);
2024}
2025
Chris Lattner55476162008-01-29 06:52:45 +00002026
Chris Lattner3554f972008-05-20 05:46:13 +00002027/// WillNotOverflowSignedAdd - Return true if we can prove that:
2028/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2029/// This basically requires proving that the add in the original type would not
2030/// overflow to change the sign bit or have a carry out.
2031bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2032 // There are different heuristics we can use for this. Here are some simple
2033 // ones.
2034
2035 // Add has the property that adding any two 2's complement numbers can only
2036 // have one carry bit which can change a sign. As such, if LHS and RHS each
2037 // have at least two sign bits, we know that the addition of the two values will
2038 // sign extend fine.
2039 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2040 return true;
2041
2042
2043 // If one of the operands only has one non-zero bit, and if the other operand
2044 // has a known-zero bit in a more significant place than it (not including the
2045 // sign bit) the ripple may go up to and fill the zero, but won't change the
2046 // sign. For example, (X & ~4) + 1.
2047
2048 // TODO: Implement.
2049
2050 return false;
2051}
2052
Chris Lattner55476162008-01-29 06:52:45 +00002053
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2055 bool Changed = SimplifyCommutative(I);
2056 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2057
2058 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2059 // X + undef -> undef
2060 if (isa<UndefValue>(RHS))
2061 return ReplaceInstUsesWith(I, RHS);
2062
2063 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002064 if (RHSC->isNullValue())
2065 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002066
2067 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2068 // X + (signbit) --> X ^ signbit
2069 const APInt& Val = CI->getValue();
2070 uint32_t BitWidth = Val.getBitWidth();
2071 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002072 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002073
2074 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2075 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002076 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002077 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002078
Eli Friedmana21526d2009-07-13 22:27:52 +00002079 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002080 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002081 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002082 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002083 }
2084
2085 if (isa<PHINode>(LHS))
2086 if (Instruction *NV = FoldOpIntoPhi(I))
2087 return NV;
2088
2089 ConstantInt *XorRHS = 0;
2090 Value *XorLHS = 0;
2091 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002092 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002093 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002094 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2095
2096 uint32_t Size = TySizeBits / 2;
2097 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2098 APInt CFF80Val(-C0080Val);
2099 do {
2100 if (TySizeBits > Size) {
2101 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2102 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2103 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2104 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2105 // This is a sign extend if the top bits are known zero.
2106 if (!MaskedValueIsZero(XorLHS,
2107 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2108 Size = 0; // Not a sign ext, but can't be any others either.
2109 break;
2110 }
2111 }
2112 Size >>= 1;
2113 C0080Val = APIntOps::lshr(C0080Val, Size);
2114 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2115 } while (Size >= 1);
2116
2117 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002118 // with funny bit widths then this switch statement should be removed. It
2119 // is just here to get the size of the "middle" type back up to something
2120 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121 const Type *MiddleType = 0;
2122 switch (Size) {
2123 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002124 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2125 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2126 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 }
2128 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002129 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 return new SExtInst(NewTrunc, I.getType(), I.getName());
2131 }
2132 }
2133 }
2134
Owen Anderson35b47072009-08-13 21:58:54 +00002135 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002136 return BinaryOperator::CreateXor(LHS, RHS);
2137
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002138 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002139 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002140 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002141 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002142
2143 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2144 if (RHSI->getOpcode() == Instruction::Sub)
2145 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2146 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2147 }
2148 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2149 if (LHSI->getOpcode() == Instruction::Sub)
2150 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2151 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2152 }
2153 }
2154
2155 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002156 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002157 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002158 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002159 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002160 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002161 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002162 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002163 }
2164
Gabor Greifa645dd32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002166 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167
2168 // A + -B --> A - B
2169 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002170 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002171 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172
2173
2174 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002175 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002177 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 // X*C1 + X*C2 --> X * (C1+C2)
2180 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002181 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002182 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 }
2184
2185 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002186 if (dyn_castFoldableMul(RHS, C2) == LHS)
2187 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188
2189 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002190 if (dyn_castNotVal(LHS) == RHS ||
2191 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002192 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193
2194
2195 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002196 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2197 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002199
2200 // A+B --> A|B iff A and B have no bits set in common.
2201 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2202 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2203 APInt LHSKnownOne(IT->getBitWidth(), 0);
2204 APInt LHSKnownZero(IT->getBitWidth(), 0);
2205 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2206 if (LHSKnownZero != 0) {
2207 APInt RHSKnownOne(IT->getBitWidth(), 0);
2208 APInt RHSKnownZero(IT->getBitWidth(), 0);
2209 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2210
2211 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002212 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002213 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002214 }
2215 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002216
Nick Lewycky83598a72008-02-03 07:42:09 +00002217 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002218 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002219 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002220 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2221 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002222 if (W != Y) {
2223 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002224 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002225 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002226 std::swap(W, X);
2227 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002228 std::swap(Y, Z);
2229 std::swap(W, X);
2230 }
2231 }
2232
2233 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002234 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002235 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002236 }
2237 }
2238 }
2239
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2241 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002242 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002243 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244
2245 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002246 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002247 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002248 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249 if (Anded == CRHS) {
2250 // See if all bits from the first bit set in the Add RHS up are included
2251 // in the mask. First, get the rightmost bit.
2252 const APInt& AddRHSV = CRHS->getValue();
2253
2254 // Form a mask of all bits from the lowest bit added through the top.
2255 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2256
2257 // See if the and mask includes all of these bits.
2258 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2259
2260 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2261 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002262 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002263 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264 }
2265 }
2266 }
2267
2268 // Try to fold constant add into select arguments.
2269 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2271 return R;
2272 }
2273
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002274 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002275 {
2276 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002277 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002278 if (!SI) {
2279 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002280 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002281 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002282 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002283 Value *TV = SI->getTrueValue();
2284 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002285 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002286
2287 // Can we fold the add into the argument of the select?
2288 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002289 if (match(FV, m_Zero()) &&
2290 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002291 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002292 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002293 if (match(TV, m_Zero()) &&
2294 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002295 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002296 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002297 }
2298 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299
Chris Lattner3554f972008-05-20 05:46:13 +00002300 // Check for (add (sext x), y), see if we can merge this into an
2301 // integer add followed by a sext.
2302 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2303 // (add (sext x), cst) --> (sext (add x, cst'))
2304 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2305 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002306 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002307 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002308 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002309 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2310 // Insert the new, smaller add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002311 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2312 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002313 return new SExtInst(NewAdd, I.getType());
2314 }
2315 }
2316
2317 // (add (sext x), (sext y)) --> (sext (add int x, y))
2318 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2319 // Only do this if x/y have the same type, if at last one of them has a
2320 // single use (so we don't increase the number of sexts), and if the
2321 // integer add will not overflow.
2322 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2323 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2324 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2325 RHSConv->getOperand(0))) {
2326 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002327 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2328 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002329 return new SExtInst(NewAdd, I.getType());
2330 }
2331 }
2332 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002333
2334 return Changed ? &I : 0;
2335}
2336
2337Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2338 bool Changed = SimplifyCommutative(I);
2339 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2340
2341 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2342 // X + 0 --> X
2343 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002344 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002345 (I.getType())->getValueAPF()))
2346 return ReplaceInstUsesWith(I, LHS);
2347 }
2348
2349 if (isa<PHINode>(LHS))
2350 if (Instruction *NV = FoldOpIntoPhi(I))
2351 return NV;
2352 }
2353
2354 // -A + B --> B - A
2355 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002356 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002357 return BinaryOperator::CreateFSub(RHS, LHSV);
2358
2359 // A + -B --> A - B
2360 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002361 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002362 return BinaryOperator::CreateFSub(LHS, V);
2363
2364 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2365 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2366 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2367 return ReplaceInstUsesWith(I, LHS);
2368
Chris Lattner3554f972008-05-20 05:46:13 +00002369 // Check for (add double (sitofp x), y), see if we can merge this into an
2370 // integer add followed by a promotion.
2371 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2372 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2373 // ... if the constant fits in the integer value. This is useful for things
2374 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2375 // requires a constant pool load, and generally allows the add to be better
2376 // instcombined.
2377 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2378 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002379 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002380 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002381 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002382 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2383 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002384 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2385 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002386 return new SIToFPInst(NewAdd, I.getType());
2387 }
2388 }
2389
2390 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2391 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2392 // Only do this if x/y have the same type, if at last one of them has a
2393 // single use (so we don't increase the number of int->fp conversions),
2394 // and if the integer add will not overflow.
2395 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2396 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2397 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2398 RHSConv->getOperand(0))) {
2399 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002400 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2401 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002402 return new SIToFPInst(NewAdd, I.getType());
2403 }
2404 }
2405 }
2406
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002407 return Changed ? &I : 0;
2408}
2409
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2412
Dan Gohman7ce405e2009-06-04 22:49:04 +00002413 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415
2416 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002417 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002418 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002419
2420 if (isa<UndefValue>(Op0))
2421 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2422 if (isa<UndefValue>(Op1))
2423 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2424
2425 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2426 // Replace (-1 - A) with (~A)...
2427 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002428 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429
2430 // C - ~X == X + (1+C)
2431 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002432 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002433 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434
2435 // -(X >>u 31) -> (X >>s 31)
2436 // -(X >>s 31) -> (X >>u 31)
2437 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002438 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002439 if (SI->getOpcode() == Instruction::LShr) {
2440 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2441 // Check to see if we are shifting out everything but the sign bit.
2442 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2443 SI->getType()->getPrimitiveSizeInBits()-1) {
2444 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002445 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002446 SI->getOperand(0), CU, SI->getName());
2447 }
2448 }
2449 }
2450 else if (SI->getOpcode() == Instruction::AShr) {
2451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452 // Check to see if we are shifting out everything but the sign bit.
2453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2454 SI->getType()->getPrimitiveSizeInBits()-1) {
2455 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002456 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457 SI->getOperand(0), CU, SI->getName());
2458 }
2459 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002460 }
2461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002462 }
2463
2464 // Try to fold constant sub into select arguments.
2465 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2466 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2467 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002468
2469 // C - zext(bool) -> bool ? C - 1 : C
2470 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002471 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002472 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 }
2474
Owen Anderson35b47072009-08-13 21:58:54 +00002475 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002476 return BinaryOperator::CreateXor(Op0, Op1);
2477
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002479 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002481 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002482 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002484 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002485 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2488 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002489 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002490 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 }
2492 }
2493
2494 if (Op1I->hasOneUse()) {
2495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2496 // is not used by anyone else...
2497 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002498 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 // Swap the two operands of the subexpr...
2500 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2501 Op1I->setOperand(0, IIOp1);
2502 Op1I->setOperand(1, IIOp0);
2503
2504 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002505 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 }
2507
2508 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2509 //
2510 if (Op1I->getOpcode() == Instruction::And &&
2511 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2512 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2513
Chris Lattnerc7694852009-08-30 07:44:24 +00002514 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002515 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002516 }
2517
2518 // 0 - (X sdiv C) -> (X sdiv -C)
2519 if (Op1I->getOpcode() == Instruction::SDiv)
2520 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2521 if (CSI->isZero())
2522 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002523 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002524 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525
2526 // X - X*C --> X * (1-C)
2527 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002528 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002529 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002530 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002531 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002532 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533 }
2534 }
2535 }
2536
Dan Gohman7ce405e2009-06-04 22:49:04 +00002537 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2538 if (Op0I->getOpcode() == Instruction::Add) {
2539 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2540 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2541 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2542 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2543 } else if (Op0I->getOpcode() == Instruction::Sub) {
2544 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002545 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002546 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002547 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002548 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549
2550 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002551 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002552 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002553 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002554
2555 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002556 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002557 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 }
2559 return 0;
2560}
2561
Dan Gohman7ce405e2009-06-04 22:49:04 +00002562Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2563 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2564
2565 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002566 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002567 return BinaryOperator::CreateFAdd(Op0, V);
2568
2569 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2570 if (Op1I->getOpcode() == Instruction::FAdd) {
2571 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002572 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002573 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002574 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002575 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002576 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002577 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002578 }
2579
2580 return 0;
2581}
2582
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002583/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2584/// comparison only checks the sign bit. If it only checks the sign bit, set
2585/// TrueIfSigned if the result of the comparison is true when the input value is
2586/// signed.
2587static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2588 bool &TrueIfSigned) {
2589 switch (pred) {
2590 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2591 TrueIfSigned = true;
2592 return RHS->isZero();
2593 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2594 TrueIfSigned = true;
2595 return RHS->isAllOnesValue();
2596 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2597 TrueIfSigned = false;
2598 return RHS->isAllOnesValue();
2599 case ICmpInst::ICMP_UGT:
2600 // True if LHS u> RHS and RHS == high-bit-mask - 1
2601 TrueIfSigned = true;
2602 return RHS->getValue() ==
2603 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2604 case ICmpInst::ICMP_UGE:
2605 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2606 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002607 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608 default:
2609 return false;
2610 }
2611}
2612
2613Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2614 bool Changed = SimplifyCommutative(I);
2615 Value *Op0 = I.getOperand(0);
2616
Eli Friedmane426ded2009-07-18 09:12:15 +00002617 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002618 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619
2620 // Simplify mul instructions with a constant RHS...
2621 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2622 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2623
2624 // ((X << C1)*C2) == (X * (C2 << C1))
2625 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2626 if (SI->getOpcode() == Instruction::Shl)
2627 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002628 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002629 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002630
2631 if (CI->isZero())
2632 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2633 if (CI->equalsInt(1)) // X * 1 == X
2634 return ReplaceInstUsesWith(I, Op0);
2635 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002636 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002637
2638 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2639 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002640 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002641 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002642 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002643 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002644 if (Op1->isNullValue())
2645 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002646
2647 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2648 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002649 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002650
2651 // As above, vector X*splat(1.0) -> X in all defined cases.
2652 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002653 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2654 if (CI->equalsInt(1))
2655 return ReplaceInstUsesWith(I, Op0);
2656 }
2657 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002658 }
2659
2660 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2661 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002662 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002663 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnerc7694852009-08-30 07:44:24 +00002664 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2665 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002666 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667
2668 }
2669
2670 // Try to fold constant mul into select arguments.
2671 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2672 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2673 return R;
2674
2675 if (isa<PHINode>(Op0))
2676 if (Instruction *NV = FoldOpIntoPhi(I))
2677 return NV;
2678 }
2679
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002680 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2681 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002683
Nick Lewycky1c246402008-11-21 07:33:58 +00002684 // (X / Y) * Y = X - (X % Y)
2685 // (X / Y) * -Y = (X % Y) - X
2686 {
2687 Value *Op1 = I.getOperand(1);
2688 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2689 if (!BO ||
2690 (BO->getOpcode() != Instruction::UDiv &&
2691 BO->getOpcode() != Instruction::SDiv)) {
2692 Op1 = Op0;
2693 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2694 }
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002695 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002696 if (BO && BO->hasOneUse() &&
2697 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2698 (BO->getOpcode() == Instruction::UDiv ||
2699 BO->getOpcode() == Instruction::SDiv)) {
2700 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2701
Dan Gohman07878902009-08-12 16:33:09 +00002702 // If the division is exact, X % Y is zero.
2703 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2704 if (SDiv->isExact()) {
2705 if (Op1BO == Op1)
2706 return ReplaceInstUsesWith(I, Op0BO);
2707 else
2708 return BinaryOperator::CreateNeg(Op0BO);
2709 }
2710
Chris Lattnerc7694852009-08-30 07:44:24 +00002711 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00002712 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00002713 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002714 else
Chris Lattnerc7694852009-08-30 07:44:24 +00002715 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002716 Rem->takeName(BO);
2717
2718 if (Op1BO == Op1)
2719 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00002720 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002721 }
2722 }
2723
Owen Anderson35b47072009-08-13 21:58:54 +00002724 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002725 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2726
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727 // If one of the operands of the multiply is a cast from a boolean value, then
2728 // we know the bool is either zero or one, so this is a 'masking' multiply.
2729 // See if we can simplify things based on how the boolean was originally
2730 // formed.
2731 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002732 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson35b47072009-08-13 21:58:54 +00002733 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734 BoolCast = CI;
2735 if (!BoolCast)
2736 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson35b47072009-08-13 21:58:54 +00002737 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738 BoolCast = CI;
2739 if (BoolCast) {
2740 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2741 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2742 const Type *SCOpTy = SCIOp0->getType();
2743 bool TIS = false;
2744
2745 // If the icmp is true iff the sign bit of X is set, then convert this
2746 // multiply into a shift/and combination.
2747 if (isa<ConstantInt>(SCIOp1) &&
2748 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2749 TIS) {
2750 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002751 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnerc7694852009-08-30 07:44:24 +00002753 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2754 BoolCast->getOperand(0)->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755
2756 // If the multiply type is not the same as the source type, sign extend
2757 // or truncate to the multiply type.
Chris Lattnerd6164c22009-08-30 20:01:10 +00002758 if (I.getType() != V->getType())
2759 V = Builder->CreateIntCast(V, I.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002760
2761 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 }
2764 }
2765 }
2766
2767 return Changed ? &I : 0;
2768}
2769
Dan Gohman7ce405e2009-06-04 22:49:04 +00002770Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2771 bool Changed = SimplifyCommutative(I);
2772 Value *Op0 = I.getOperand(0);
2773
2774 // Simplify mul instructions with a constant RHS...
2775 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2776 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2777 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2778 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2779 if (Op1F->isExactlyValue(1.0))
2780 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2781 } else if (isa<VectorType>(Op1->getType())) {
2782 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2783 // As above, vector X*splat(1.0) -> X in all defined cases.
2784 if (Constant *Splat = Op1V->getSplatValue()) {
2785 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2786 if (F->isExactlyValue(1.0))
2787 return ReplaceInstUsesWith(I, Op0);
2788 }
2789 }
2790 }
2791
2792 // Try to fold constant mul into select arguments.
2793 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2794 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2795 return R;
2796
2797 if (isa<PHINode>(Op0))
2798 if (Instruction *NV = FoldOpIntoPhi(I))
2799 return NV;
2800 }
2801
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002802 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2803 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002804 return BinaryOperator::CreateFMul(Op0v, Op1v);
2805
2806 return Changed ? &I : 0;
2807}
2808
Chris Lattner76972db2008-07-14 00:15:52 +00002809/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2810/// instruction.
2811bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2812 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2813
2814 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2815 int NonNullOperand = -1;
2816 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2817 if (ST->isNullValue())
2818 NonNullOperand = 2;
2819 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2820 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2821 if (ST->isNullValue())
2822 NonNullOperand = 1;
2823
2824 if (NonNullOperand == -1)
2825 return false;
2826
2827 Value *SelectCond = SI->getOperand(0);
2828
2829 // Change the div/rem to use 'Y' instead of the select.
2830 I.setOperand(1, SI->getOperand(NonNullOperand));
2831
2832 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2833 // problem. However, the select, or the condition of the select may have
2834 // multiple uses. Based on our knowledge that the operand must be non-zero,
2835 // propagate the known value for the select into other uses of it, and
2836 // propagate a known value of the condition into its other users.
2837
2838 // If the select and condition only have a single use, don't bother with this,
2839 // early exit.
2840 if (SI->use_empty() && SelectCond->hasOneUse())
2841 return true;
2842
2843 // Scan the current block backward, looking for other uses of SI.
2844 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2845
2846 while (BBI != BBFront) {
2847 --BBI;
2848 // If we found a call to a function, we can't assume it will return, so
2849 // information from below it cannot be propagated above it.
2850 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2851 break;
2852
2853 // Replace uses of the select or its condition with the known values.
2854 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2855 I != E; ++I) {
2856 if (*I == SI) {
2857 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00002858 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002859 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002860 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2861 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00002862 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002863 }
2864 }
2865
2866 // If we past the instruction, quit looking for it.
2867 if (&*BBI == SI)
2868 SI = 0;
2869 if (&*BBI == SelectCond)
2870 SelectCond = 0;
2871
2872 // If we ran out of things to eliminate, break out of the loop.
2873 if (SelectCond == 0 && SI == 0)
2874 break;
2875
2876 }
2877 return true;
2878}
2879
2880
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002881/// This function implements the transforms on div instructions that work
2882/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2883/// used by the visitors to those instructions.
2884/// @brief Transforms common to all three div instructions
2885Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2886 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2887
Chris Lattner653ef3c2008-02-19 06:12:18 +00002888 // undef / X -> 0 for integer.
2889 // undef / X -> undef for FP (the undef could be a snan).
2890 if (isa<UndefValue>(Op0)) {
2891 if (Op0->getType()->isFPOrFPVector())
2892 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002893 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002894 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895
2896 // X / undef -> undef
2897 if (isa<UndefValue>(Op1))
2898 return ReplaceInstUsesWith(I, Op1);
2899
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002900 return 0;
2901}
2902
2903/// This function implements the transforms common to both integer division
2904/// instructions (udiv and sdiv). It is called by the visitors to those integer
2905/// division instructions.
2906/// @brief Common integer divide transforms
2907Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2908 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2909
Chris Lattnercefb36c2008-05-16 02:59:42 +00002910 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002911 if (Op0 == Op1) {
2912 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002913 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002914 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002915 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002916 }
2917
Owen Andersoneacb44d2009-07-24 23:12:02 +00002918 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002919 return ReplaceInstUsesWith(I, CI);
2920 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002921
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922 if (Instruction *Common = commonDivTransforms(I))
2923 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002924
2925 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2926 // This does not apply for fdiv.
2927 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2928 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002929
2930 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2931 // div X, 1 == X
2932 if (RHS->equalsInt(1))
2933 return ReplaceInstUsesWith(I, Op0);
2934
2935 // (X / C1) / C2 -> X / (C1*C2)
2936 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2937 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2938 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002939 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002940 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00002941 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002942 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002943 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002944 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945 }
2946
2947 if (!RHS->isZero()) { // avoid X udiv 0
2948 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2949 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2950 return R;
2951 if (isa<PHINode>(Op0))
2952 if (Instruction *NV = FoldOpIntoPhi(I))
2953 return NV;
2954 }
2955 }
2956
2957 // 0 / X == 0, we don't need to preserve faults!
2958 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2959 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00002960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002961
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002962 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00002963 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002964 return ReplaceInstUsesWith(I, Op0);
2965
Nick Lewycky94418732008-11-27 20:21:08 +00002966 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2967 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2968 // div X, 1 == X
2969 if (X->isOne())
2970 return ReplaceInstUsesWith(I, Op0);
2971 }
2972
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973 return 0;
2974}
2975
2976Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2978
2979 // Handle the integer div common cases
2980 if (Instruction *Common = commonIDivTransforms(I))
2981 return Common;
2982
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002984 // X udiv C^2 -> X >> C
2985 // Check to see if this is an unsigned division with an exact power of 2,
2986 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002987 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002988 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002989 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00002990
2991 // X udiv C, where C >= signbit
2992 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002993 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00002994 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00002995 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00002996 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002997 }
2998
2999 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3000 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3001 if (RHSI->getOpcode() == Instruction::Shl &&
3002 isa<ConstantInt>(RHSI->getOperand(0))) {
3003 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3004 if (C1.isPowerOf2()) {
3005 Value *N = RHSI->getOperand(1);
3006 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003007 if (uint32_t C2 = C1.logBase2())
3008 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 }
3011 }
3012 }
3013
3014 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3015 // where C1&C2 are powers of two.
3016 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3017 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3018 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3019 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3020 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3021 // Compute the shift amounts
3022 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3023 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003024 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003025 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003026
3027 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003028 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003029 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003030
3031 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003032 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 }
3034 }
3035 return 0;
3036}
3037
3038Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3040
3041 // Handle the integer div common cases
3042 if (Instruction *Common = commonIDivTransforms(I))
3043 return Common;
3044
3045 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3046 // sdiv X, -1 == -X
3047 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003048 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003049
Dan Gohman07878902009-08-12 16:33:09 +00003050 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003051 if (cast<SDivOperator>(&I)->isExact() &&
3052 RHS->getValue().isNonNegative() &&
3053 RHS->getValue().isPowerOf2()) {
3054 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3055 RHS->getValue().exactLogBase2());
3056 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3057 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003058
3059 // -X/C --> X/-C provided the negation doesn't overflow.
3060 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3061 if (isa<Constant>(Sub->getOperand(0)) &&
3062 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003063 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003064 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3065 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003066 }
3067
3068 // If the sign bits of both operands are zero (i.e. we can prove they are
3069 // unsigned inputs), turn this into a udiv.
3070 if (I.getType()->isInteger()) {
3071 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003072 if (MaskedValueIsZero(Op0, Mask)) {
3073 if (MaskedValueIsZero(Op1, Mask)) {
3074 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3075 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3076 }
3077 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003078 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003079 ShiftedInt->getValue().isPowerOf2()) {
3080 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3081 // Safe because the only negative value (1 << Y) can take on is
3082 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3083 // the sign bit set.
3084 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3085 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003087 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088
3089 return 0;
3090}
3091
3092Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3093 return commonDivTransforms(I);
3094}
3095
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096/// This function implements the transforms on rem instructions that work
3097/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3098/// is used by the visitors to those instructions.
3099/// @brief Transforms common to all three rem instructions
3100Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3102
Chris Lattner653ef3c2008-02-19 06:12:18 +00003103 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3104 if (I.getType()->isFPOrFPVector())
3105 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003107 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108 if (isa<UndefValue>(Op1))
3109 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3110
3111 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003112 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3113 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003114
3115 return 0;
3116}
3117
3118/// This function implements the transforms common to both integer remainder
3119/// instructions (urem and srem). It is called by the visitors to those integer
3120/// remainder instructions.
3121/// @brief Common integer remainder transforms
3122Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3123 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3124
3125 if (Instruction *common = commonRemTransforms(I))
3126 return common;
3127
Dale Johannesena51f7372009-01-21 00:35:19 +00003128 // 0 % X == 0 for integer, we don't need to preserve faults!
3129 if (Constant *LHS = dyn_cast<Constant>(Op0))
3130 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003131 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003132
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003133 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3134 // X % 0 == undef, we don't need to preserve faults!
3135 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003136 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137
3138 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003139 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140
3141 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3144 return R;
3145 } else if (isa<PHINode>(Op0I)) {
3146 if (Instruction *NV = FoldOpIntoPhi(I))
3147 return NV;
3148 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003149
3150 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003151 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003152 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003153 }
3154 }
3155
3156 return 0;
3157}
3158
3159Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3161
3162 if (Instruction *common = commonIRemTransforms(I))
3163 return common;
3164
3165 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3166 // X urem C^2 -> X and C
3167 // Check to see if this is an unsigned remainder with an exact power of 2,
3168 // if so, convert to a bitwise and.
3169 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3170 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003171 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172 }
3173
3174 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3175 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3176 if (RHSI->getOpcode() == Instruction::Shl &&
3177 isa<ConstantInt>(RHSI->getOperand(0))) {
3178 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003179 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003180 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003181 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182 }
3183 }
3184 }
3185
3186 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3187 // where C1&C2 are powers of two.
3188 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3189 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3190 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3191 // STO == 0 and SFO == 0 handled above.
3192 if ((STO->getValue().isPowerOf2()) &&
3193 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003194 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3195 SI->getName()+".t");
3196 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3197 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003198 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199 }
3200 }
3201 }
3202
3203 return 0;
3204}
3205
3206Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3208
Dan Gohmandb3dd962007-11-05 23:16:33 +00003209 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003210 if (Instruction *Common = commonIRemTransforms(I))
3211 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003212
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003213 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003214 if (!isa<Constant>(RHSNeg) ||
3215 (isa<ConstantInt>(RHSNeg) &&
3216 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003217 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003218 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 I.setOperand(1, RHSNeg);
3220 return &I;
3221 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003222
Dan Gohmandb3dd962007-11-05 23:16:33 +00003223 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003225 if (I.getType()->isInteger()) {
3226 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3227 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3228 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003229 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003230 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003231 }
3232
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003233 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003234 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3235 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003236
Nick Lewyckyfd746832008-12-20 16:48:00 +00003237 bool hasNegative = false;
3238 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3239 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3240 if (RHS->getValue().isNegative())
3241 hasNegative = true;
3242
3243 if (hasNegative) {
3244 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003245 for (unsigned i = 0; i != VWidth; ++i) {
3246 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3247 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003248 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003249 else
3250 Elts[i] = RHS;
3251 }
3252 }
3253
Owen Anderson2f422e02009-07-28 21:19:26 +00003254 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003255 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003256 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003257 I.setOperand(1, NewRHSV);
3258 return &I;
3259 }
3260 }
3261 }
3262
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003263 return 0;
3264}
3265
3266Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3267 return commonRemTransforms(I);
3268}
3269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270// isOneBitSet - Return true if there is exactly one bit set in the specified
3271// constant.
3272static bool isOneBitSet(const ConstantInt *CI) {
3273 return CI->getValue().isPowerOf2();
3274}
3275
3276// isHighOnes - Return true if the constant is of the form 1+0+.
3277// This is the same as lowones(~X).
3278static bool isHighOnes(const ConstantInt *CI) {
3279 return (~CI->getValue() + 1).isPowerOf2();
3280}
3281
3282/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3283/// are carefully arranged to allow folding of expressions such as:
3284///
3285/// (A < B) | (A > B) --> (A != B)
3286///
3287/// Note that this is only valid if the first and second predicates have the
3288/// same sign. Is illegal to do: (A u< B) | (A s> B)
3289///
3290/// Three bits are used to represent the condition, as follows:
3291/// 0 A > B
3292/// 1 A == B
3293/// 2 A < B
3294///
3295/// <=> Value Definition
3296/// 000 0 Always false
3297/// 001 1 A > B
3298/// 010 2 A == B
3299/// 011 3 A >= B
3300/// 100 4 A < B
3301/// 101 5 A != B
3302/// 110 6 A <= B
3303/// 111 7 Always true
3304///
3305static unsigned getICmpCode(const ICmpInst *ICI) {
3306 switch (ICI->getPredicate()) {
3307 // False -> 0
3308 case ICmpInst::ICMP_UGT: return 1; // 001
3309 case ICmpInst::ICMP_SGT: return 1; // 001
3310 case ICmpInst::ICMP_EQ: return 2; // 010
3311 case ICmpInst::ICMP_UGE: return 3; // 011
3312 case ICmpInst::ICMP_SGE: return 3; // 011
3313 case ICmpInst::ICMP_ULT: return 4; // 100
3314 case ICmpInst::ICMP_SLT: return 4; // 100
3315 case ICmpInst::ICMP_NE: return 5; // 101
3316 case ICmpInst::ICMP_ULE: return 6; // 110
3317 case ICmpInst::ICMP_SLE: return 6; // 110
3318 // True -> 7
3319 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003320 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003321 return 0;
3322 }
3323}
3324
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003325/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3326/// predicate into a three bit mask. It also returns whether it is an ordered
3327/// predicate by reference.
3328static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3329 isOrdered = false;
3330 switch (CC) {
3331 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3332 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003333 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3334 case FCmpInst::FCMP_UGT: return 1; // 001
3335 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3336 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003337 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3338 case FCmpInst::FCMP_UGE: return 3; // 011
3339 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3340 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003341 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3342 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003343 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3344 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003345 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003346 default:
3347 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003348 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003349 return 0;
3350 }
3351}
3352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353/// getICmpValue - This is the complement of getICmpCode, which turns an
3354/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003355/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003356/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003357static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003358 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003360 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003361 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003362 case 1:
3363 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003364 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003366 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3367 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003368 case 3:
3369 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003370 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003372 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003373 case 4:
3374 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003375 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003376 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003377 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3378 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379 case 6:
3380 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003381 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003383 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003384 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385 }
3386}
3387
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003388/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3389/// opcode and two operands into either a FCmp instruction. isordered is passed
3390/// in to determine which kind of predicate to use in the new fcmp instruction.
3391static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003392 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003393 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003394 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003395 case 0:
3396 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003397 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003398 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003399 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003400 case 1:
3401 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003402 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003403 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003404 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003405 case 2:
3406 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003407 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003408 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003409 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003410 case 3:
3411 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003412 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003413 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003414 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003415 case 4:
3416 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003417 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003418 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003419 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003420 case 5:
3421 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003422 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003423 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003425 case 6:
3426 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003427 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003428 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003430 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003431 }
3432}
3433
Chris Lattner2972b822008-11-16 04:55:20 +00003434/// PredicatesFoldable - Return true if both predicates match sign or if at
3435/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3437 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003438 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3439 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003440}
3441
3442namespace {
3443// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3444struct FoldICmpLogical {
3445 InstCombiner &IC;
3446 Value *LHS, *RHS;
3447 ICmpInst::Predicate pred;
3448 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3449 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3450 pred(ICI->getPredicate()) {}
3451 bool shouldApply(Value *V) const {
3452 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3453 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003454 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3455 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 return false;
3457 }
3458 Instruction *apply(Instruction &Log) const {
3459 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3460 if (ICI->getOperand(0) != LHS) {
3461 assert(ICI->getOperand(1) == LHS);
3462 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3463 }
3464
3465 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3466 unsigned LHSCode = getICmpCode(ICI);
3467 unsigned RHSCode = getICmpCode(RHSICI);
3468 unsigned Code;
3469 switch (Log.getOpcode()) {
3470 case Instruction::And: Code = LHSCode & RHSCode; break;
3471 case Instruction::Or: Code = LHSCode | RHSCode; break;
3472 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003473 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003474 }
3475
3476 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3477 ICmpInst::isSignedPredicate(ICI->getPredicate());
3478
Owen Anderson24be4c12009-07-03 00:17:18 +00003479 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003480 if (Instruction *I = dyn_cast<Instruction>(RV))
3481 return I;
3482 // Otherwise, it's a constant boolean value...
3483 return IC.ReplaceInstUsesWith(Log, RV);
3484 }
3485};
3486} // end anonymous namespace
3487
3488// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3489// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3490// guaranteed to be a binary operator.
3491Instruction *InstCombiner::OptAndOp(Instruction *Op,
3492 ConstantInt *OpRHS,
3493 ConstantInt *AndRHS,
3494 BinaryOperator &TheAnd) {
3495 Value *X = Op->getOperand(0);
3496 Constant *Together = 0;
3497 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003498 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499
3500 switch (Op->getOpcode()) {
3501 case Instruction::Xor:
3502 if (Op->hasOneUse()) {
3503 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003504 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003506 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507 }
3508 break;
3509 case Instruction::Or:
3510 if (Together == AndRHS) // (X | C) & C --> C
3511 return ReplaceInstUsesWith(TheAnd, AndRHS);
3512
3513 if (Op->hasOneUse() && Together != OpRHS) {
3514 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003515 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003517 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 }
3519 break;
3520 case Instruction::Add:
3521 if (Op->hasOneUse()) {
3522 // Adding a one to a single bit bit-field should be turned into an XOR
3523 // of the bit. First thing to check is to see if this AND is with a
3524 // single bit constant.
3525 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3526
3527 // If there is only one bit set...
3528 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3529 // Ok, at this point, we know that we are masking the result of the
3530 // ADD down to exactly one bit. If the constant we are adding has
3531 // no bits set below this bit, then we can eliminate the ADD.
3532 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3533
3534 // Check to see if any bits below the one bit set in AndRHSV are set.
3535 if ((AddRHS & (AndRHSV-1)) == 0) {
3536 // If not, the only thing that can effect the output of the AND is
3537 // the bit specified by AndRHSV. If that bit is set, the effect of
3538 // the XOR is to toggle the bit. If it is clear, then the ADD has
3539 // no effect.
3540 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3541 TheAnd.setOperand(0, X);
3542 return &TheAnd;
3543 } else {
3544 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003545 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003547 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548 }
3549 }
3550 }
3551 }
3552 break;
3553
3554 case Instruction::Shl: {
3555 // We know that the AND will not produce any of the bits shifted in, so if
3556 // the anded constant includes them, clear them now!
3557 //
3558 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3559 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3560 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003561 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562
3563 if (CI->getValue() == ShlMask) {
3564 // Masking out bits that the shift already masks
3565 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3566 } else if (CI != AndRHS) { // Reducing bits set in and.
3567 TheAnd.setOperand(1, CI);
3568 return &TheAnd;
3569 }
3570 break;
3571 }
3572 case Instruction::LShr:
3573 {
3574 // We know that the AND will not produce any of the bits shifted in, so if
3575 // the anded constant includes them, clear them now! This only applies to
3576 // unsigned shifts, because a signed shr may bring in set bits!
3577 //
3578 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3579 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3580 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003581 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003582
3583 if (CI->getValue() == ShrMask) {
3584 // Masking out bits that the shift already masks.
3585 return ReplaceInstUsesWith(TheAnd, Op);
3586 } else if (CI != AndRHS) {
3587 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3588 return &TheAnd;
3589 }
3590 break;
3591 }
3592 case Instruction::AShr:
3593 // Signed shr.
3594 // See if this is shifting in some sign extension, then masking it out
3595 // with an and.
3596 if (Op->hasOneUse()) {
3597 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3598 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3599 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003600 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003601 if (C == AndRHS) { // Masking out bits shifted in.
3602 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3603 // Make the argument unsigned.
3604 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003605 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003606 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003607 }
3608 }
3609 break;
3610 }
3611 return 0;
3612}
3613
3614
3615/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3616/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3617/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3618/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3619/// insert new instructions.
3620Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3621 bool isSigned, bool Inside,
3622 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003623 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003624 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3625 "Lo is not <= Hi in range emission code!");
3626
3627 if (Inside) {
3628 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003629 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003630
3631 // V >= Min && V < Hi --> V < Hi
3632 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3633 ICmpInst::Predicate pred = (isSigned ?
3634 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003635 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003636 }
3637
3638 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003639 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003640 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003641 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003642 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003643 }
3644
3645 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003646 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647
3648 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003649 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3651 ICmpInst::Predicate pred = (isSigned ?
3652 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003653 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 }
3655
3656 // Emit V-Lo >u Hi-1-Lo
3657 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003658 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003659 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003660 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003661 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003662}
3663
3664// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3665// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3666// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3667// not, since all 1s are not contiguous.
3668static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3669 const APInt& V = Val->getValue();
3670 uint32_t BitWidth = Val->getType()->getBitWidth();
3671 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3672
3673 // look for the first zero bit after the run of ones
3674 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3675 // look for the first non-zero bit
3676 ME = V.getActiveBits();
3677 return true;
3678}
3679
3680/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3681/// where isSub determines whether the operator is a sub. If we can fold one of
3682/// the following xforms:
3683///
3684/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3685/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3686/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3687///
3688/// return (A +/- B).
3689///
3690Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3691 ConstantInt *Mask, bool isSub,
3692 Instruction &I) {
3693 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3694 if (!LHSI || LHSI->getNumOperands() != 2 ||
3695 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3696
3697 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3698
3699 switch (LHSI->getOpcode()) {
3700 default: return 0;
3701 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003702 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003703 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3704 if ((Mask->getValue().countLeadingZeros() +
3705 Mask->getValue().countPopulation()) ==
3706 Mask->getValue().getBitWidth())
3707 break;
3708
3709 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3710 // part, we don't need any explicit masks to take them out of A. If that
3711 // is all N is, ignore it.
3712 uint32_t MB = 0, ME = 0;
3713 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3714 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3715 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3716 if (MaskedValueIsZero(RHS, Mask))
3717 break;
3718 }
3719 }
3720 return 0;
3721 case Instruction::Or:
3722 case Instruction::Xor:
3723 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3724 if ((Mask->getValue().countLeadingZeros() +
3725 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003726 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003727 break;
3728 return 0;
3729 }
3730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003731 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00003732 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3733 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003734}
3735
Chris Lattner0631ea72008-11-16 05:06:21 +00003736/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3737Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3738 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003739 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003740 ConstantInt *LHSCst, *RHSCst;
3741 ICmpInst::Predicate LHSCC, RHSCC;
3742
Chris Lattnerf3803482008-11-16 05:10:52 +00003743 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003744 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003745 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003746 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003747 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003748 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003749
3750 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3751 // where C is a power of 2
3752 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3753 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003754 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00003755 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003756 }
3757
3758 // From here on, we only handle:
3759 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3760 if (Val != Val2) return 0;
3761
Chris Lattner0631ea72008-11-16 05:06:21 +00003762 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3763 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3764 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3765 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3766 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3767 return 0;
3768
3769 // We can't fold (ugt x, C) & (sgt x, C2).
3770 if (!PredicatesFoldable(LHSCC, RHSCC))
3771 return 0;
3772
3773 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003774 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003775 if (ICmpInst::isSignedPredicate(LHSCC) ||
3776 (ICmpInst::isEquality(LHSCC) &&
3777 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003778 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003779 else
Chris Lattner665298f2008-11-16 05:14:43 +00003780 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3781
3782 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003783 std::swap(LHS, RHS);
3784 std::swap(LHSCst, RHSCst);
3785 std::swap(LHSCC, RHSCC);
3786 }
3787
3788 // At this point, we know we have have two icmp instructions
3789 // comparing a value against two constants and and'ing the result
3790 // together. Because of the above check, we know that we only have
3791 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3792 // (from the FoldICmpLogical check above), that the two constants
3793 // are not equal and that the larger constant is on the RHS
3794 assert(LHSCst != RHSCst && "Compares not folded above?");
3795
3796 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003797 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003798 case ICmpInst::ICMP_EQ:
3799 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003800 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003801 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3802 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3803 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003804 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003805 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3806 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3807 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3808 return ReplaceInstUsesWith(I, LHS);
3809 }
3810 case ICmpInst::ICMP_NE:
3811 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003812 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003813 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003814 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003815 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003816 break; // (X != 13 & X u< 15) -> no change
3817 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003818 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003819 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003820 break; // (X != 13 & X s< 15) -> no change
3821 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3822 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3823 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3824 return ReplaceInstUsesWith(I, RHS);
3825 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003826 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003827 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003828 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00003829 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003830 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003831 }
3832 break; // (X != 13 & X != 15) -> no change
3833 }
3834 break;
3835 case ICmpInst::ICMP_ULT:
3836 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003837 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003838 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3839 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003840 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003841 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3842 break;
3843 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3844 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3845 return ReplaceInstUsesWith(I, LHS);
3846 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3847 break;
3848 }
3849 break;
3850 case ICmpInst::ICMP_SLT:
3851 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003852 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003853 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3854 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003855 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3857 break;
3858 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3859 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3860 return ReplaceInstUsesWith(I, LHS);
3861 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3862 break;
3863 }
3864 break;
3865 case ICmpInst::ICMP_UGT:
3866 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003867 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003868 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3869 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3870 return ReplaceInstUsesWith(I, RHS);
3871 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3872 break;
3873 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003874 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003875 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003876 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003877 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003878 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003879 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3881 break;
3882 }
3883 break;
3884 case ICmpInst::ICMP_SGT:
3885 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003886 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003887 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3888 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3889 return ReplaceInstUsesWith(I, RHS);
3890 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3891 break;
3892 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003893 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003894 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003895 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003896 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003897 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003898 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003899 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3900 break;
3901 }
3902 break;
3903 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003904
3905 return 0;
3906}
3907
Chris Lattner93a359a2009-07-23 05:14:02 +00003908Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3909 FCmpInst *RHS) {
3910
3911 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3912 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3913 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3914 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3915 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3916 // If either of the constants are nans, then the whole thing returns
3917 // false.
3918 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003919 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00003920 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00003921 LHS->getOperand(0), RHS->getOperand(0));
3922 }
Chris Lattnercf373552009-07-23 05:32:17 +00003923
3924 // Handle vector zeros. This occurs because the canonical form of
3925 // "fcmp ord x,x" is "fcmp ord x, 0".
3926 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3927 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00003928 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00003929 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003930 return 0;
3931 }
3932
3933 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3934 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3935 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3936
3937
3938 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3939 // Swap RHS operands to match LHS.
3940 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3941 std::swap(Op1LHS, Op1RHS);
3942 }
3943
3944 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3945 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3946 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00003947 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00003948
3949 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003950 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003951 if (Op0CC == FCmpInst::FCMP_TRUE)
3952 return ReplaceInstUsesWith(I, RHS);
3953 if (Op1CC == FCmpInst::FCMP_TRUE)
3954 return ReplaceInstUsesWith(I, LHS);
3955
3956 bool Op0Ordered;
3957 bool Op1Ordered;
3958 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3959 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3960 if (Op1Pred == 0) {
3961 std::swap(LHS, RHS);
3962 std::swap(Op0Pred, Op1Pred);
3963 std::swap(Op0Ordered, Op1Ordered);
3964 }
3965 if (Op0Pred == 0) {
3966 // uno && ueq -> uno && (uno || eq) -> ueq
3967 // ord && olt -> ord && (ord && lt) -> olt
3968 if (Op0Ordered == Op1Ordered)
3969 return ReplaceInstUsesWith(I, RHS);
3970
3971 // uno && oeq -> uno && (ord && eq) -> false
3972 // uno && ord -> false
3973 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003974 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003975 // ord && ueq -> ord && (uno || eq) -> oeq
3976 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3977 Op0LHS, Op0RHS, Context));
3978 }
3979 }
3980
3981 return 0;
3982}
3983
Chris Lattner0631ea72008-11-16 05:06:21 +00003984
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003985Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3986 bool Changed = SimplifyCommutative(I);
3987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3988
3989 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00003990 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003991
3992 // and X, X = X
3993 if (Op0 == Op1)
3994 return ReplaceInstUsesWith(I, Op1);
3995
3996 // See if we can simplify any instructions used by the instruction whose sole
3997 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003998 if (SimplifyDemandedInstructionBits(I))
3999 return &I;
4000 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004001 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4002 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4003 return ReplaceInstUsesWith(I, I.getOperand(0));
4004 } else if (isa<ConstantAggregateZero>(Op1)) {
4005 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4006 }
4007 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004008
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4010 const APInt& AndRHSMask = AndRHS->getValue();
4011 APInt NotAndRHS(~AndRHSMask);
4012
4013 // Optimize a variety of ((val OP C1) & C2) combinations...
4014 if (isa<BinaryOperator>(Op0)) {
4015 Instruction *Op0I = cast<Instruction>(Op0);
4016 Value *Op0LHS = Op0I->getOperand(0);
4017 Value *Op0RHS = Op0I->getOperand(1);
4018 switch (Op0I->getOpcode()) {
4019 case Instruction::Xor:
4020 case Instruction::Or:
4021 // If the mask is only needed on one incoming arm, push it up.
4022 if (Op0I->hasOneUse()) {
4023 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4024 // Not masking anything out for the LHS, move to RHS.
Chris Lattnerc7694852009-08-30 07:44:24 +00004025 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4026 Op0RHS->getName()+".masked");
Gabor Greifa645dd32008-05-16 19:29:10 +00004027 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004028 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4029 }
4030 if (!isa<Constant>(Op0RHS) &&
4031 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4032 // Not masking anything out for the RHS, move to LHS.
Chris Lattnerc7694852009-08-30 07:44:24 +00004033 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4034 Op0LHS->getName()+".masked");
Gabor Greifa645dd32008-05-16 19:29:10 +00004035 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004036 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4037 }
4038 }
4039
4040 break;
4041 case Instruction::Add:
4042 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4043 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4044 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4045 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004046 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004047 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004048 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004049 break;
4050
4051 case Instruction::Sub:
4052 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4053 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4054 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4055 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004056 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004057
Nick Lewyckya349ba42008-07-10 05:51:40 +00004058 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4059 // has 1's for all bits that the subtraction with A might affect.
4060 if (Op0I->hasOneUse()) {
4061 uint32_t BitWidth = AndRHSMask.getBitWidth();
4062 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4063 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4064
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004065 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004066 if (!(A && A->isZero()) && // avoid infinite recursion.
4067 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004068 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004069 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4070 }
4071 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004072 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004073
4074 case Instruction::Shl:
4075 case Instruction::LShr:
4076 // (1 << x) & 1 --> zext(x == 0)
4077 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004078 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004079 Value *NewICmp =
4080 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004081 return new ZExtInst(NewICmp, I.getType());
4082 }
4083 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 }
4085
4086 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4087 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4088 return Res;
4089 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4090 // If this is an integer truncation or change from signed-to-unsigned, and
4091 // if the source is an and/or with immediate, transform it. This
4092 // frequently occurs for bitfield accesses.
4093 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4094 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4095 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004096 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004097 if (CastOp->getOpcode() == Instruction::And) {
4098 // Change: and (cast (and X, C1) to T), C2
4099 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4100 // This will fold the two constants together, which may allow
4101 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004102 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004103 CastOp->getOperand(0), I.getType(),
4104 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004105 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004106 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004107 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004108 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004109 } else if (CastOp->getOpcode() == Instruction::Or) {
4110 // Change: and (cast (or X, C1) to T), C2
4111 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004112 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004113 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004114 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004115 return ReplaceInstUsesWith(I, AndRHS);
4116 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004117 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118 }
4119 }
4120
4121 // Try to fold constant and into select arguments.
4122 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4123 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4124 return R;
4125 if (isa<PHINode>(Op0))
4126 if (Instruction *NV = FoldOpIntoPhi(I))
4127 return NV;
4128 }
4129
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004130 Value *Op0NotVal = dyn_castNotVal(Op0);
4131 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004132
4133 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135
4136 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4137 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004138 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4139 I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004140 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004141 }
4142
4143 {
4144 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004145 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4147 return ReplaceInstUsesWith(I, Op1);
4148
4149 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004150 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004151 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004152 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004153 }
4154 }
4155
Dan Gohmancdff2122009-08-12 16:23:25 +00004156 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4158 return ReplaceInstUsesWith(I, Op0);
4159
4160 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004161 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004162 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004163 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004164 }
4165 }
4166
4167 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004168 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004169 if (A == Op1) { // (A^B)&A -> A&(A^B)
4170 I.swapOperands(); // Simplify below
4171 std::swap(Op0, Op1);
4172 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4173 cast<BinaryOperator>(Op0)->swapOperands();
4174 I.swapOperands(); // Simplify below
4175 std::swap(Op0, Op1);
4176 }
4177 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004178
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004179 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004180 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004181 if (B == Op0) { // B&(A^B) -> B&(B^A)
4182 cast<BinaryOperator>(Op1)->swapOperands();
4183 std::swap(A, B);
4184 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004185 if (A == Op0) // A&(A^B) -> A & ~B
4186 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004188
4189 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004190 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4191 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004192 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004193 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4194 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004195 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004196 }
4197
4198 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4199 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004200 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201 return R;
4202
Chris Lattner0631ea72008-11-16 05:06:21 +00004203 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4204 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4205 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 }
4207
4208 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4209 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4210 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4211 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4212 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004213 if (SrcTy == Op1C->getOperand(0)->getType() &&
4214 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004215 // Only do this if the casts both really cause code to be generated.
4216 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4217 I.getType(), TD) &&
4218 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4219 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004220 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4221 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004222 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223 }
4224 }
4225
4226 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4227 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4228 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4229 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4230 SI0->getOperand(1) == SI1->getOperand(1) &&
4231 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004232 Value *NewOp =
4233 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4234 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004235 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004236 SI1->getOperand(1));
4237 }
4238 }
4239
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004240 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004241 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004242 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4243 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4244 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004245 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004246
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004247 return Changed ? &I : 0;
4248}
4249
Chris Lattner567f5112008-10-05 02:13:19 +00004250/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4251/// capable of providing pieces of a bswap. The subexpression provides pieces
4252/// of a bswap if it is proven that each of the non-zero bytes in the output of
4253/// the expression came from the corresponding "byte swapped" byte in some other
4254/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4255/// we know that the expression deposits the low byte of %X into the high byte
4256/// of the bswap result and that all other bytes are zero. This expression is
4257/// accepted, the high byte of ByteValues is set to X to indicate a correct
4258/// match.
4259///
4260/// This function returns true if the match was unsuccessful and false if so.
4261/// On entry to the function the "OverallLeftShift" is a signed integer value
4262/// indicating the number of bytes that the subexpression is later shifted. For
4263/// example, if the expression is later right shifted by 16 bits, the
4264/// OverallLeftShift value would be -2 on entry. This is used to specify which
4265/// byte of ByteValues is actually being set.
4266///
4267/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4268/// byte is masked to zero by a user. For example, in (X & 255), X will be
4269/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4270/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4271/// always in the local (OverallLeftShift) coordinate space.
4272///
4273static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4274 SmallVector<Value*, 8> &ByteValues) {
4275 if (Instruction *I = dyn_cast<Instruction>(V)) {
4276 // If this is an or instruction, it may be an inner node of the bswap.
4277 if (I->getOpcode() == Instruction::Or) {
4278 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4279 ByteValues) ||
4280 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4281 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004282 }
Chris Lattner567f5112008-10-05 02:13:19 +00004283
4284 // If this is a logical shift by a constant multiple of 8, recurse with
4285 // OverallLeftShift and ByteMask adjusted.
4286 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4287 unsigned ShAmt =
4288 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4289 // Ensure the shift amount is defined and of a byte value.
4290 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4291 return true;
4292
4293 unsigned ByteShift = ShAmt >> 3;
4294 if (I->getOpcode() == Instruction::Shl) {
4295 // X << 2 -> collect(X, +2)
4296 OverallLeftShift += ByteShift;
4297 ByteMask >>= ByteShift;
4298 } else {
4299 // X >>u 2 -> collect(X, -2)
4300 OverallLeftShift -= ByteShift;
4301 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004302 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004303 }
4304
4305 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4306 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4307
4308 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4309 ByteValues);
4310 }
4311
4312 // If this is a logical 'and' with a mask that clears bytes, clear the
4313 // corresponding bytes in ByteMask.
4314 if (I->getOpcode() == Instruction::And &&
4315 isa<ConstantInt>(I->getOperand(1))) {
4316 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4317 unsigned NumBytes = ByteValues.size();
4318 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4319 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4320
4321 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4322 // If this byte is masked out by a later operation, we don't care what
4323 // the and mask is.
4324 if ((ByteMask & (1 << i)) == 0)
4325 continue;
4326
4327 // If the AndMask is all zeros for this byte, clear the bit.
4328 APInt MaskB = AndMask & Byte;
4329 if (MaskB == 0) {
4330 ByteMask &= ~(1U << i);
4331 continue;
4332 }
4333
4334 // If the AndMask is not all ones for this byte, it's not a bytezap.
4335 if (MaskB != Byte)
4336 return true;
4337
4338 // Otherwise, this byte is kept.
4339 }
4340
4341 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4342 ByteValues);
4343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004344 }
4345
Chris Lattner567f5112008-10-05 02:13:19 +00004346 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4347 // the input value to the bswap. Some observations: 1) if more than one byte
4348 // is demanded from this input, then it could not be successfully assembled
4349 // into a byteswap. At least one of the two bytes would not be aligned with
4350 // their ultimate destination.
4351 if (!isPowerOf2_32(ByteMask)) return true;
4352 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004353
Chris Lattner567f5112008-10-05 02:13:19 +00004354 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4355 // is demanded, it needs to go into byte 0 of the result. This means that the
4356 // byte needs to be shifted until it lands in the right byte bucket. The
4357 // shift amount depends on the position: if the byte is coming from the high
4358 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4359 // low part, it must be shifted left.
4360 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4361 if (InputByteNo < ByteValues.size()/2) {
4362 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4363 return true;
4364 } else {
4365 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4366 return true;
4367 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368
4369 // If the destination byte value is already defined, the values are or'd
4370 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004371 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004372 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004373 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004374 return false;
4375}
4376
4377/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4378/// If so, insert the new bswap intrinsic and return it.
4379Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4380 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004381 if (!ITy || ITy->getBitWidth() % 16 ||
4382 // ByteMask only allows up to 32-byte values.
4383 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4385
4386 /// ByteValues - For each byte of the result, we keep track of which value
4387 /// defines each byte.
4388 SmallVector<Value*, 8> ByteValues;
4389 ByteValues.resize(ITy->getBitWidth()/8);
4390
4391 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004392 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4393 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004394 return 0;
4395
4396 // Check to see if all of the bytes come from the same value.
4397 Value *V = ByteValues[0];
4398 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4399
4400 // Check to make sure that all of the bytes come from the same value.
4401 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4402 if (ByteValues[i] != V)
4403 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004404 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004405 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004406 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004407 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004408}
4409
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004410/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4411/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4412/// we can simplify this expression to "cond ? C : D or B".
4413static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004414 Value *C, Value *D,
4415 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004416 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004417 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004418 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004419 return 0;
4420
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004421 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004422 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004423 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004424 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004425 return SelectInst::Create(Cond, C, B);
4426 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004427 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004428 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004429 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004430 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004431 return 0;
4432}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433
Chris Lattner0c678e52008-11-16 05:20:07 +00004434/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4435Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4436 ICmpInst *LHS, ICmpInst *RHS) {
4437 Value *Val, *Val2;
4438 ConstantInt *LHSCst, *RHSCst;
4439 ICmpInst::Predicate LHSCC, RHSCC;
4440
4441 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004442 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004443 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004444 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004445 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004446 return 0;
4447
4448 // From here on, we only handle:
4449 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4450 if (Val != Val2) return 0;
4451
4452 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4453 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4454 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4455 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4456 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4457 return 0;
4458
4459 // We can't fold (ugt x, C) | (sgt x, C2).
4460 if (!PredicatesFoldable(LHSCC, RHSCC))
4461 return 0;
4462
4463 // Ensure that the larger constant is on the RHS.
4464 bool ShouldSwap;
4465 if (ICmpInst::isSignedPredicate(LHSCC) ||
4466 (ICmpInst::isEquality(LHSCC) &&
4467 ICmpInst::isSignedPredicate(RHSCC)))
4468 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4469 else
4470 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4471
4472 if (ShouldSwap) {
4473 std::swap(LHS, RHS);
4474 std::swap(LHSCst, RHSCst);
4475 std::swap(LHSCC, RHSCC);
4476 }
4477
4478 // At this point, we know we have have two icmp instructions
4479 // comparing a value against two constants and or'ing the result
4480 // together. Because of the above check, we know that we only have
4481 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4482 // FoldICmpLogical check above), that the two constants are not
4483 // equal.
4484 assert(LHSCst != RHSCst && "Compares not folded above?");
4485
4486 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004487 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004488 case ICmpInst::ICMP_EQ:
4489 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004490 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004491 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004492 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004493 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004494 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004495 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004496 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004497 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004498 }
4499 break; // (X == 13 | X == 15) -> no change
4500 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4501 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4502 break;
4503 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4504 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4505 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4506 return ReplaceInstUsesWith(I, RHS);
4507 }
4508 break;
4509 case ICmpInst::ICMP_NE:
4510 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004511 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004512 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4513 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4514 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4515 return ReplaceInstUsesWith(I, LHS);
4516 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4517 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4518 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004519 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004520 }
4521 break;
4522 case ICmpInst::ICMP_ULT:
4523 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004524 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004525 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4526 break;
4527 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4528 // If RHSCst is [us]MAXINT, it is always false. Not handling
4529 // this can cause overflow.
4530 if (RHSCst->isMaxValue(false))
4531 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004532 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004533 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004534 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4535 break;
4536 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4537 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4538 return ReplaceInstUsesWith(I, RHS);
4539 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4540 break;
4541 }
4542 break;
4543 case ICmpInst::ICMP_SLT:
4544 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004545 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004546 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4547 break;
4548 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4549 // If RHSCst is [us]MAXINT, it is always false. Not handling
4550 // this can cause overflow.
4551 if (RHSCst->isMaxValue(true))
4552 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004553 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004554 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004555 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4556 break;
4557 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4558 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4559 return ReplaceInstUsesWith(I, RHS);
4560 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4561 break;
4562 }
4563 break;
4564 case ICmpInst::ICMP_UGT:
4565 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4568 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4569 return ReplaceInstUsesWith(I, LHS);
4570 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4571 break;
4572 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4573 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004574 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004575 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4576 break;
4577 }
4578 break;
4579 case ICmpInst::ICMP_SGT:
4580 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004581 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004582 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4583 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4584 return ReplaceInstUsesWith(I, LHS);
4585 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4586 break;
4587 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4588 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004589 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004590 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4591 break;
4592 }
4593 break;
4594 }
4595 return 0;
4596}
4597
Chris Lattner57e66fa2009-07-23 05:46:22 +00004598Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4599 FCmpInst *RHS) {
4600 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4601 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4602 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4603 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4604 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4605 // If either of the constants are nans, then the whole thing returns
4606 // true.
4607 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004608 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004609
4610 // Otherwise, no need to compare the two constants, compare the
4611 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004612 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004613 LHS->getOperand(0), RHS->getOperand(0));
4614 }
4615
4616 // Handle vector zeros. This occurs because the canonical form of
4617 // "fcmp uno x,x" is "fcmp uno x, 0".
4618 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4619 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004620 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004621 LHS->getOperand(0), RHS->getOperand(0));
4622
4623 return 0;
4624 }
4625
4626 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4627 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4628 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4629
4630 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4631 // Swap RHS operands to match LHS.
4632 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4633 std::swap(Op1LHS, Op1RHS);
4634 }
4635 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4636 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4637 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004638 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004639 Op0LHS, Op0RHS);
4640 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004641 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004642 if (Op0CC == FCmpInst::FCMP_FALSE)
4643 return ReplaceInstUsesWith(I, RHS);
4644 if (Op1CC == FCmpInst::FCMP_FALSE)
4645 return ReplaceInstUsesWith(I, LHS);
4646 bool Op0Ordered;
4647 bool Op1Ordered;
4648 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4649 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4650 if (Op0Ordered == Op1Ordered) {
4651 // If both are ordered or unordered, return a new fcmp with
4652 // or'ed predicates.
4653 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4654 Op0LHS, Op0RHS, Context);
4655 if (Instruction *I = dyn_cast<Instruction>(RV))
4656 return I;
4657 // Otherwise, it's a constant boolean value...
4658 return ReplaceInstUsesWith(I, RV);
4659 }
4660 }
4661 return 0;
4662}
4663
Bill Wendlingdae376a2008-12-01 08:23:25 +00004664/// FoldOrWithConstants - This helper function folds:
4665///
Bill Wendling236a1192008-12-02 05:09:00 +00004666/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004667///
4668/// into:
4669///
Bill Wendling236a1192008-12-02 05:09:00 +00004670/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004671///
Bill Wendling236a1192008-12-02 05:09:00 +00004672/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004673Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004674 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004675 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4676 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004677
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004678 Value *V1 = 0;
4679 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004680 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004681
Bill Wendling86ee3162008-12-02 06:18:11 +00004682 APInt Xor = CI1->getValue() ^ CI2->getValue();
4683 if (!Xor.isAllOnesValue()) return 0;
4684
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004685 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004686 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004687 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004688 }
4689
4690 return 0;
4691}
4692
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004693Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4694 bool Changed = SimplifyCommutative(I);
4695 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4696
4697 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004698 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004699
4700 // or X, X = X
4701 if (Op0 == Op1)
4702 return ReplaceInstUsesWith(I, Op0);
4703
4704 // See if we can simplify any instructions used by the instruction whose sole
4705 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004706 if (SimplifyDemandedInstructionBits(I))
4707 return &I;
4708 if (isa<VectorType>(I.getType())) {
4709 if (isa<ConstantAggregateZero>(Op1)) {
4710 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4711 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4712 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4713 return ReplaceInstUsesWith(I, I.getOperand(1));
4714 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004715 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004716
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004717 // or X, -1 == -1
4718 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4719 ConstantInt *C1 = 0; Value *X = 0;
4720 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004721 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004722 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004723 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004724 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004725 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004726 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004727 }
4728
4729 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004730 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004731 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004732 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004733 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004734 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004735 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004736 }
4737
4738 // Try to fold constant and into select arguments.
4739 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4740 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4741 return R;
4742 if (isa<PHINode>(Op0))
4743 if (Instruction *NV = FoldOpIntoPhi(I))
4744 return NV;
4745 }
4746
4747 Value *A = 0, *B = 0;
4748 ConstantInt *C1 = 0, *C2 = 0;
4749
Dan Gohmancdff2122009-08-12 16:23:25 +00004750 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4752 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004753 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004754 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4755 return ReplaceInstUsesWith(I, Op0);
4756
4757 // (A | B) | C and A | (B | C) -> bswap if possible.
4758 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004759 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4760 match(Op1, m_Or(m_Value(), m_Value())) ||
4761 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4762 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004763 if (Instruction *BSwap = MatchBSwap(I))
4764 return BSwap;
4765 }
4766
4767 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004768 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004769 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004770 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004771 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004773 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004774 }
4775
4776 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004777 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004778 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004779 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004780 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004782 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004783 }
4784
4785 // (A & C)|(B & D)
4786 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004787 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4788 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004789 Value *V1 = 0, *V2 = 0, *V3 = 0;
4790 C1 = dyn_cast<ConstantInt>(C);
4791 C2 = dyn_cast<ConstantInt>(D);
4792 if (C1 && C2) { // (A & C1)|(B & C2)
4793 // If we have: ((V + N) & C1) | (V & C2)
4794 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4795 // replace with V+N.
4796 if (C1->getValue() == ~C2->getValue()) {
4797 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004798 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004799 // Add commutes, try both ways.
4800 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4801 return ReplaceInstUsesWith(I, A);
4802 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4803 return ReplaceInstUsesWith(I, A);
4804 }
4805 // Or commutes, try both ways.
4806 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004807 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004808 // Add commutes, try both ways.
4809 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4810 return ReplaceInstUsesWith(I, B);
4811 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4812 return ReplaceInstUsesWith(I, B);
4813 }
4814 }
4815 V1 = 0; V2 = 0; V3 = 0;
4816 }
4817
4818 // Check to see if we have any common things being and'ed. If so, find the
4819 // terms for V1 & (V2|V3).
4820 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4821 if (A == B) // (A & C)|(A & D) == A & (C|D)
4822 V1 = A, V2 = C, V3 = D;
4823 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4824 V1 = A, V2 = B, V3 = C;
4825 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4826 V1 = C, V2 = A, V3 = D;
4827 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4828 V1 = C, V2 = A, V3 = B;
4829
4830 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004831 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00004832 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004833 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834 }
Dan Gohman279952c2008-10-28 22:38:57 +00004835
Dan Gohman35b76162008-10-30 20:40:10 +00004836 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004837 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004838 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004839 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004840 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004841 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004842 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004843 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004844 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004845
Bill Wendling22ca8352008-11-30 13:52:49 +00004846 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004847 if ((match(C, m_Not(m_Specific(D))) &&
4848 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004849 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004850 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004851 if ((match(A, m_Not(m_Specific(D))) &&
4852 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004853 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004854 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004855 if ((match(C, m_Not(m_Specific(B))) &&
4856 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004857 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004858 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004859 if ((match(A, m_Not(m_Specific(B))) &&
4860 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004861 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004862 }
4863
4864 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4865 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4866 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4867 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4868 SI0->getOperand(1) == SI1->getOperand(1) &&
4869 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004870 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4871 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004872 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004873 SI1->getOperand(1));
4874 }
4875 }
4876
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004877 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004878 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4879 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004880 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004881 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004882 }
4883 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004884 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4885 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004886 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004887 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004888 }
4889
Dan Gohmancdff2122009-08-12 16:23:25 +00004890 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004891 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004892 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004893 } else {
4894 A = 0;
4895 }
4896 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004897 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004898 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004899 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004900
4901 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4902 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004903 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004904 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004905 }
4906 }
4907
4908 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4909 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004910 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004911 return R;
4912
Chris Lattner0c678e52008-11-16 05:20:07 +00004913 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4914 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4915 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004916 }
4917
4918 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004919 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004920 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4921 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004922 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4923 !isa<ICmpInst>(Op1C->getOperand(0))) {
4924 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004925 if (SrcTy == Op1C->getOperand(0)->getType() &&
4926 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004927 // Only do this if the casts both really cause code to be
4928 // generated.
4929 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4930 I.getType(), TD) &&
4931 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4932 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004933 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4934 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004935 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004936 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004937 }
4938 }
Chris Lattner91882432007-10-24 05:38:08 +00004939 }
4940
4941
4942 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4943 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00004944 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4945 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4946 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004947 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004948
4949 return Changed ? &I : 0;
4950}
4951
Dan Gohman089efff2008-05-13 00:00:25 +00004952namespace {
4953
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004954// XorSelf - Implements: X ^ X --> 0
4955struct XorSelf {
4956 Value *RHS;
4957 XorSelf(Value *rhs) : RHS(rhs) {}
4958 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4959 Instruction *apply(BinaryOperator &Xor) const {
4960 return &Xor;
4961 }
4962};
4963
Dan Gohman089efff2008-05-13 00:00:25 +00004964}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004965
4966Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4967 bool Changed = SimplifyCommutative(I);
4968 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4969
Evan Chenge5cd8032008-03-25 20:07:13 +00004970 if (isa<UndefValue>(Op1)) {
4971 if (isa<UndefValue>(Op0))
4972 // Handle undef ^ undef -> 0 special case. This is a common
4973 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00004974 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004975 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004976 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004977
4978 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004979 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004980 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00004981 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004982 }
4983
4984 // See if we can simplify any instructions used by the instruction whose sole
4985 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004986 if (SimplifyDemandedInstructionBits(I))
4987 return &I;
4988 if (isa<VectorType>(I.getType()))
4989 if (isa<ConstantAggregateZero>(Op1))
4990 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004991
4992 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004993 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004994 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4995 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4996 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4997 if (Op0I->getOpcode() == Instruction::And ||
4998 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004999 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5000 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005001 Value *NotY =
5002 Builder->CreateNot(Op0I->getOperand(1),
5003 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005004 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005005 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005006 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005007 }
5008 }
5009 }
5010 }
5011
5012
5013 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005014 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005015 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005016 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005017 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005018 ICI->getOperand(0), ICI->getOperand(1));
5019
Nick Lewycky1405e922007-08-06 20:04:16 +00005020 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005021 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005022 FCI->getOperand(0), FCI->getOperand(1));
5023 }
5024
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005025 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5026 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5027 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5028 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5029 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005030 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5031 (RHS == ConstantExpr::getCast(Opcode,
5032 ConstantInt::getTrue(*Context),
5033 Op0C->getDestTy()))) {
5034 CI->setPredicate(CI->getInversePredicate());
5035 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005036 }
5037 }
5038 }
5039 }
5040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005041 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5042 // ~(c-X) == X-c-1 == X+(-c-1)
5043 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5044 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005045 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5046 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005047 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005048 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 }
5050
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005051 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005052 if (Op0I->getOpcode() == Instruction::Add) {
5053 // ~(X-c) --> (-c-1)-X
5054 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005055 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005056 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005057 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005058 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005059 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 } else if (RHS->getValue().isSignBit()) {
5061 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005062 Constant *C = ConstantInt::get(*Context,
5063 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005064 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065
5066 }
5067 } else if (Op0I->getOpcode() == Instruction::Or) {
5068 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5069 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005070 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005071 // Anything in both C1 and C2 is known to be zero, remove it from
5072 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005073 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5074 NewRHS = ConstantExpr::getAnd(NewRHS,
5075 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005076 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005077 I.setOperand(0, Op0I->getOperand(0));
5078 I.setOperand(1, NewRHS);
5079 return &I;
5080 }
5081 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005082 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005083 }
5084
5085 // Try to fold constant and into select arguments.
5086 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5087 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5088 return R;
5089 if (isa<PHINode>(Op0))
5090 if (Instruction *NV = FoldOpIntoPhi(I))
5091 return NV;
5092 }
5093
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005094 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005095 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005096 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005097
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005098 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005099 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005100 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005101
5102
5103 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5104 if (Op1I) {
5105 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005106 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005107 if (A == Op0) { // B^(B|A) == (A|B)^B
5108 Op1I->swapOperands();
5109 I.swapOperands();
5110 std::swap(Op0, Op1);
5111 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5112 I.swapOperands(); // Simplified below.
5113 std::swap(Op0, Op1);
5114 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005115 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005116 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005117 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005118 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005119 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005120 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005121 if (A == Op0) { // A^(A&B) -> A^(B&A)
5122 Op1I->swapOperands();
5123 std::swap(A, B);
5124 }
5125 if (B == Op0) { // A^(B&A) -> (B&A)^A
5126 I.swapOperands(); // Simplified below.
5127 std::swap(Op0, Op1);
5128 }
5129 }
5130 }
5131
5132 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5133 if (Op0I) {
5134 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005135 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005136 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005137 if (A == Op1) // (B|A)^B == (A|B)^B
5138 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005139 if (B == Op1) // (A|B)^B == A & ~B
5140 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005141 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005142 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005143 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005144 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005145 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005146 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005147 if (A == Op1) // (A&B)^A -> (B&A)^A
5148 std::swap(A, B);
5149 if (B == Op1 && // (B&A)^A == ~B & A
5150 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005151 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005152 }
5153 }
5154 }
5155
5156 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5157 if (Op0I && Op1I && Op0I->isShift() &&
5158 Op0I->getOpcode() == Op1I->getOpcode() &&
5159 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5160 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005161 Value *NewOp =
5162 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5163 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005164 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005165 Op1I->getOperand(1));
5166 }
5167
5168 if (Op0I && Op1I) {
5169 Value *A, *B, *C, *D;
5170 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005171 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5172 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005173 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005175 }
5176 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005177 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5178 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005179 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005180 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 }
5182
5183 // (A & B)^(C & D)
5184 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005185 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5186 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005187 // (X & Y)^(X & Y) -> (Y^Z) & X
5188 Value *X = 0, *Y = 0, *Z = 0;
5189 if (A == C)
5190 X = A, Y = B, Z = D;
5191 else if (A == D)
5192 X = A, Y = B, Z = C;
5193 else if (B == C)
5194 X = B, Y = A, Z = D;
5195 else if (B == D)
5196 X = B, Y = A, Z = C;
5197
5198 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005199 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005200 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005201 }
5202 }
5203 }
5204
5205 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5206 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005207 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005208 return R;
5209
5210 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005211 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005212 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5213 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5214 const Type *SrcTy = Op0C->getOperand(0)->getType();
5215 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5216 // Only do this if the casts both really cause code to be generated.
5217 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5218 I.getType(), TD) &&
5219 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5220 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005221 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5222 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005223 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005224 }
5225 }
Chris Lattner91882432007-10-24 05:38:08 +00005226 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005227
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005228 return Changed ? &I : 0;
5229}
5230
Owen Anderson24be4c12009-07-03 00:17:18 +00005231static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005232 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005233 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005234}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005235
Dan Gohman8fd520a2009-06-15 22:12:54 +00005236static bool HasAddOverflow(ConstantInt *Result,
5237 ConstantInt *In1, ConstantInt *In2,
5238 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 if (IsSigned)
5240 if (In2->getValue().isNegative())
5241 return Result->getValue().sgt(In1->getValue());
5242 else
5243 return Result->getValue().slt(In1->getValue());
5244 else
5245 return Result->getValue().ult(In1->getValue());
5246}
5247
Dan Gohman8fd520a2009-06-15 22:12:54 +00005248/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005249/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005250static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005251 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005252 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005253 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005254
Dan Gohman8fd520a2009-06-15 22:12:54 +00005255 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5256 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005257 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005258 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5259 ExtractElement(In1, Idx, Context),
5260 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005261 IsSigned))
5262 return true;
5263 }
5264 return false;
5265 }
5266
5267 return HasAddOverflow(cast<ConstantInt>(Result),
5268 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5269 IsSigned);
5270}
5271
5272static bool HasSubOverflow(ConstantInt *Result,
5273 ConstantInt *In1, ConstantInt *In2,
5274 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005275 if (IsSigned)
5276 if (In2->getValue().isNegative())
5277 return Result->getValue().slt(In1->getValue());
5278 else
5279 return Result->getValue().sgt(In1->getValue());
5280 else
5281 return Result->getValue().ugt(In1->getValue());
5282}
5283
Dan Gohman8fd520a2009-06-15 22:12:54 +00005284/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5285/// overflowed for this type.
5286static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005287 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005288 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005289 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005290
5291 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5292 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005293 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005294 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5295 ExtractElement(In1, Idx, Context),
5296 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005297 IsSigned))
5298 return true;
5299 }
5300 return false;
5301 }
5302
5303 return HasSubOverflow(cast<ConstantInt>(Result),
5304 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5305 IsSigned);
5306}
5307
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005308/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5309/// code necessary to compute the offset from the base pointer (without adding
5310/// in the base pointer). Return the result as a signed integer of intptr size.
5311static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005312 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005313 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson35b47072009-08-13 21:58:54 +00005314 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersonaac28372009-07-31 20:28:14 +00005315 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005316
5317 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005318 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005319 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5320
Gabor Greif17396002008-06-12 21:37:33 +00005321 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5322 ++i, ++GTI) {
5323 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005324 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005325 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5326 if (OpC->isZero()) continue;
5327
5328 // Handle a struct index, which adds its field offset to the pointer.
5329 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5330 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5331
Chris Lattnerc7694852009-08-30 07:44:24 +00005332 Result = IC.Builder->CreateAdd(Result,
5333 ConstantInt::get(IntPtrTy, Size),
5334 GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005335 continue;
5336 }
5337
Owen Andersoneacb44d2009-07-24 23:12:02 +00005338 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005339 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005340 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5341 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnerc7694852009-08-30 07:44:24 +00005342 // Emit an add instruction.
5343 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005344 continue;
5345 }
5346 // Convert to correct type.
Chris Lattnerc7694852009-08-30 07:44:24 +00005347 if (Op->getType() != IntPtrTy)
5348 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005349 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005350 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnerc7694852009-08-30 07:44:24 +00005351 // We'll let instcombine(mul) convert this to a shl if possible.
5352 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005353 }
5354
5355 // Emit an add instruction.
Chris Lattnerc7694852009-08-30 07:44:24 +00005356 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005357 }
5358 return Result;
5359}
5360
Chris Lattnereba75862008-04-22 02:53:33 +00005361
Dan Gohmanff9b4732009-07-17 22:16:21 +00005362/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5363/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5364/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5365/// be complex, and scales are involved. The above expression would also be
5366/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5367/// This later form is less amenable to optimization though, and we are allowed
5368/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005369///
5370/// If we can't emit an optimized form for this expression, this returns null.
5371///
5372static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5373 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005374 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005375 gep_type_iterator GTI = gep_type_begin(GEP);
5376
5377 // Check to see if this gep only has a single variable index. If so, and if
5378 // any constant indices are a multiple of its scale, then we can compute this
5379 // in terms of the scale of the variable index. For example, if the GEP
5380 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5381 // because the expression will cross zero at the same point.
5382 unsigned i, e = GEP->getNumOperands();
5383 int64_t Offset = 0;
5384 for (i = 1; i != e; ++i, ++GTI) {
5385 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5386 // Compute the aggregate offset of constant indices.
5387 if (CI->isZero()) continue;
5388
5389 // Handle a struct index, which adds its field offset to the pointer.
5390 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5391 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5392 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005393 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005394 Offset += Size*CI->getSExtValue();
5395 }
5396 } else {
5397 // Found our variable index.
5398 break;
5399 }
5400 }
5401
5402 // If there are no variable indices, we must have a constant offset, just
5403 // evaluate it the general way.
5404 if (i == e) return 0;
5405
5406 Value *VariableIdx = GEP->getOperand(i);
5407 // Determine the scale factor of the variable element. For example, this is
5408 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005409 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005410
5411 // Verify that there are no other variable indices. If so, emit the hard way.
5412 for (++i, ++GTI; i != e; ++i, ++GTI) {
5413 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5414 if (!CI) return 0;
5415
5416 // Compute the aggregate offset of constant indices.
5417 if (CI->isZero()) continue;
5418
5419 // Handle a struct index, which adds its field offset to the pointer.
5420 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5421 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5422 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005423 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005424 Offset += Size*CI->getSExtValue();
5425 }
5426 }
5427
5428 // Okay, we know we have a single variable index, which must be a
5429 // pointer/array/vector index. If there is no offset, life is simple, return
5430 // the index.
5431 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5432 if (Offset == 0) {
5433 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5434 // we don't need to bother extending: the extension won't affect where the
5435 // computation crosses zero.
5436 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson35b47072009-08-13 21:58:54 +00005437 VariableIdx = new TruncInst(VariableIdx,
5438 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005439 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005440 return VariableIdx;
5441 }
5442
5443 // Otherwise, there is an index. The computation we will do will be modulo
5444 // the pointer size, so get it.
5445 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5446
5447 Offset &= PtrSizeMask;
5448 VariableScale &= PtrSizeMask;
5449
5450 // To do this transformation, any constant index must be a multiple of the
5451 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5452 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5453 // multiple of the variable scale.
5454 int64_t NewOffs = Offset / (int64_t)VariableScale;
5455 if (Offset != NewOffs*(int64_t)VariableScale)
5456 return 0;
5457
5458 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson35b47072009-08-13 21:58:54 +00005459 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattnereba75862008-04-22 02:53:33 +00005460 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005461 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005462 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005463 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005464 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005465 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005466}
5467
5468
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005469/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5470/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005471Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005472 ICmpInst::Predicate Cond,
5473 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005474 // Look through bitcasts.
5475 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5476 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005477
5478 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005479 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005480 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005481 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005482 // know pointers can't overflow since the gep is inbounds. See if we can
5483 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005484 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5485
5486 // If not, synthesize the offset the hard way.
5487 if (Offset == 0)
5488 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005489 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005490 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005491 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005492 // If the base pointers are different, but the indices are the same, just
5493 // compare the base pointer.
5494 if (PtrBase != GEPRHS->getOperand(0)) {
5495 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5496 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5497 GEPRHS->getOperand(0)->getType();
5498 if (IndicesTheSame)
5499 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5500 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5501 IndicesTheSame = false;
5502 break;
5503 }
5504
5505 // If all indices are the same, just compare the base pointers.
5506 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005507 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005508 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5509
5510 // Otherwise, the base pointers are different and the indices are
5511 // different, bail out.
5512 return 0;
5513 }
5514
5515 // If one of the GEPs has all zero indices, recurse.
5516 bool AllZeros = true;
5517 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5518 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5519 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5520 AllZeros = false;
5521 break;
5522 }
5523 if (AllZeros)
5524 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5525 ICmpInst::getSwappedPredicate(Cond), I);
5526
5527 // If the other GEP has all zero indices, recurse.
5528 AllZeros = true;
5529 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5530 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5531 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5532 AllZeros = false;
5533 break;
5534 }
5535 if (AllZeros)
5536 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5537
5538 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5539 // If the GEPs only differ by one index, compare it.
5540 unsigned NumDifferences = 0; // Keep track of # differences.
5541 unsigned DiffOperand = 0; // The operand that differs.
5542 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5543 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5544 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5545 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5546 // Irreconcilable differences.
5547 NumDifferences = 2;
5548 break;
5549 } else {
5550 if (NumDifferences++) break;
5551 DiffOperand = i;
5552 }
5553 }
5554
5555 if (NumDifferences == 0) // SAME GEP?
5556 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005557 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005558 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005560 else if (NumDifferences == 1) {
5561 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5562 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5563 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005564 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005565 }
5566 }
5567
5568 // Only lower this if the icmp is the only user of the GEP or if we expect
5569 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005570 if (TD &&
5571 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005572 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5573 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5574 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5575 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005576 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005577 }
5578 }
5579 return 0;
5580}
5581
Chris Lattnere6b62d92008-05-19 20:18:56 +00005582/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5583///
5584Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5585 Instruction *LHSI,
5586 Constant *RHSC) {
5587 if (!isa<ConstantFP>(RHSC)) return 0;
5588 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5589
5590 // Get the width of the mantissa. We don't want to hack on conversions that
5591 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005592 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005593 if (MantissaWidth == -1) return 0; // Unknown.
5594
5595 // Check to see that the input is converted from an integer type that is small
5596 // enough that preserves all bits. TODO: check here for "known" sign bits.
5597 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005598 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005599
5600 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005601 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5602 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005603 ++InputSize;
5604
5605 // If the conversion would lose info, don't hack on this.
5606 if ((int)InputSize > MantissaWidth)
5607 return 0;
5608
5609 // Otherwise, we can potentially simplify the comparison. We know that it
5610 // will always come through as an integer value and we know the constant is
5611 // not a NAN (it would have been previously simplified).
5612 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5613
5614 ICmpInst::Predicate Pred;
5615 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005616 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005617 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005618 case FCmpInst::FCMP_OEQ:
5619 Pred = ICmpInst::ICMP_EQ;
5620 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005621 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005622 case FCmpInst::FCMP_OGT:
5623 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5624 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005625 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005626 case FCmpInst::FCMP_OGE:
5627 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5628 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005629 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005630 case FCmpInst::FCMP_OLT:
5631 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5632 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005633 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005634 case FCmpInst::FCMP_OLE:
5635 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5636 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005637 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005638 case FCmpInst::FCMP_ONE:
5639 Pred = ICmpInst::ICMP_NE;
5640 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005641 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005642 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005643 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005644 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005645 }
5646
5647 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5648
5649 // Now we know that the APFloat is a normal number, zero or inf.
5650
Chris Lattnerf13ff492008-05-20 03:50:52 +00005651 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005652 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005653 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005654
Bill Wendling20636df2008-11-09 04:26:50 +00005655 if (!LHSUnsigned) {
5656 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5657 // and large values.
5658 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5659 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5660 APFloat::rmNearestTiesToEven);
5661 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5662 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5663 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005664 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5665 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005666 }
5667 } else {
5668 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5669 // +INF and large values.
5670 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5671 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5672 APFloat::rmNearestTiesToEven);
5673 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5674 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5675 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005676 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5677 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005678 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005679 }
5680
Bill Wendling20636df2008-11-09 04:26:50 +00005681 if (!LHSUnsigned) {
5682 // See if the RHS value is < SignedMin.
5683 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5684 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5685 APFloat::rmNearestTiesToEven);
5686 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5687 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5688 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005689 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5690 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005691 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005692 }
5693
Bill Wendling20636df2008-11-09 04:26:50 +00005694 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5695 // [0, UMAX], but it may still be fractional. See if it is fractional by
5696 // casting the FP value to the integer value and back, checking for equality.
5697 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005698 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005699 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5700 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005701 if (!RHS.isZero()) {
5702 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005703 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5704 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005705 if (!Equal) {
5706 // If we had a comparison against a fractional value, we have to adjust
5707 // the compare predicate and sometimes the value. RHSC is rounded towards
5708 // zero at this point.
5709 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005710 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005711 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005712 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005713 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005714 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005715 case ICmpInst::ICMP_ULE:
5716 // (float)int <= 4.4 --> int <= 4
5717 // (float)int <= -4.4 --> false
5718 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005719 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005720 break;
5721 case ICmpInst::ICMP_SLE:
5722 // (float)int <= 4.4 --> int <= 4
5723 // (float)int <= -4.4 --> int < -4
5724 if (RHS.isNegative())
5725 Pred = ICmpInst::ICMP_SLT;
5726 break;
5727 case ICmpInst::ICMP_ULT:
5728 // (float)int < -4.4 --> false
5729 // (float)int < 4.4 --> int <= 4
5730 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005731 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005732 Pred = ICmpInst::ICMP_ULE;
5733 break;
5734 case ICmpInst::ICMP_SLT:
5735 // (float)int < -4.4 --> int < -4
5736 // (float)int < 4.4 --> int <= 4
5737 if (!RHS.isNegative())
5738 Pred = ICmpInst::ICMP_SLE;
5739 break;
5740 case ICmpInst::ICMP_UGT:
5741 // (float)int > 4.4 --> int > 4
5742 // (float)int > -4.4 --> true
5743 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005744 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005745 break;
5746 case ICmpInst::ICMP_SGT:
5747 // (float)int > 4.4 --> int > 4
5748 // (float)int > -4.4 --> int >= -4
5749 if (RHS.isNegative())
5750 Pred = ICmpInst::ICMP_SGE;
5751 break;
5752 case ICmpInst::ICMP_UGE:
5753 // (float)int >= -4.4 --> true
5754 // (float)int >= 4.4 --> int > 4
5755 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005757 Pred = ICmpInst::ICMP_UGT;
5758 break;
5759 case ICmpInst::ICMP_SGE:
5760 // (float)int >= -4.4 --> int >= -4
5761 // (float)int >= 4.4 --> int > 4
5762 if (!RHS.isNegative())
5763 Pred = ICmpInst::ICMP_SGT;
5764 break;
5765 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005766 }
5767 }
5768
5769 // Lower this FP comparison into an appropriate integer version of the
5770 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005771 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005772}
5773
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005774Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5775 bool Changed = SimplifyCompare(I);
5776 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5777
5778 // Fold trivial predicates.
5779 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner41c09932009-09-02 05:12:37 +00005780 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005781 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner41c09932009-09-02 05:12:37 +00005782 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005783
5784 // Simplify 'fcmp pred X, X'
5785 if (Op0 == Op1) {
5786 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005787 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005788 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5789 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5790 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner41c09932009-09-02 05:12:37 +00005791 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005792 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5793 case FCmpInst::FCMP_OLT: // True if ordered and less than
5794 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner41c09932009-09-02 05:12:37 +00005795 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005796
5797 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5798 case FCmpInst::FCMP_ULT: // True if unordered or less than
5799 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5800 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5801 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5802 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005803 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005804 return &I;
5805
5806 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5807 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5808 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5809 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5810 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5811 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005812 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005813 return &I;
5814 }
5815 }
5816
5817 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005818 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005819
5820 // Handle fcmp with constant RHS
5821 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005822 // If the constant is a nan, see if we can fold the comparison based on it.
5823 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5824 if (CFP->getValueAPF().isNaN()) {
5825 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005827 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5828 "Comparison must be either ordered or unordered!");
5829 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005830 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005831 }
5832 }
5833
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005834 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5835 switch (LHSI->getOpcode()) {
5836 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005837 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5838 // block. If in the same block, we're encouraging jump threading. If
5839 // not, we are just pessimizing the code by making an i1 phi.
5840 if (LHSI->getParent() == I.getParent())
5841 if (Instruction *NV = FoldOpIntoPhi(I))
5842 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005843 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005844 case Instruction::SIToFP:
5845 case Instruction::UIToFP:
5846 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5847 return NV;
5848 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005849 case Instruction::Select:
5850 // If either operand of the select is a constant, we can fold the
5851 // comparison into the select arms, which will cause one to be
5852 // constant folded and the select turned into a bitwise or.
5853 Value *Op1 = 0, *Op2 = 0;
5854 if (LHSI->hasOneUse()) {
5855 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5856 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005857 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005858 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005859 Op2 = Builder->CreateFCmp(I.getPredicate(),
5860 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005861 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5862 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005863 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005864 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005865 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5866 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005867 }
5868 }
5869
5870 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005871 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005872 break;
5873 }
5874 }
5875
5876 return Changed ? &I : 0;
5877}
5878
5879Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5880 bool Changed = SimplifyCompare(I);
5881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5882 const Type *Ty = Op0->getType();
5883
5884 // icmp X, X
5885 if (Op0 == Op1)
Chris Lattner41c09932009-09-02 05:12:37 +00005886 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005887 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005888
5889 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005890 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lambf78cd322007-12-18 21:32:20 +00005891
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005892 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5893 // addresses never equal each other! We already know that Op0 != Op1.
5894 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5895 isa<ConstantPointerNull>(Op0)) &&
5896 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5897 isa<ConstantPointerNull>(Op1)))
Owen Anderson35b47072009-08-13 21:58:54 +00005898 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005899 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005900
5901 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00005902 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005903 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005904 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005905 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00005906 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00005907 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005908 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005909 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005910 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005911
5912 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005913 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005914 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005915 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00005916 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005917 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005918 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005919 case ICmpInst::ICMP_SGT:
5920 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005921 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005922 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005923 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005924 return BinaryOperator::CreateAnd(Not, Op0);
5925 }
5926 case ICmpInst::ICMP_UGE:
5927 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5928 // FALL THROUGH
5929 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00005930 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005931 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005932 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005933 case ICmpInst::ICMP_SGE:
5934 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5935 // FALL THROUGH
5936 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005937 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005938 return BinaryOperator::CreateOr(Not, Op0);
5939 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005940 }
5941 }
5942
Dan Gohman7934d592009-04-25 17:12:48 +00005943 unsigned BitWidth = 0;
5944 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00005945 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5946 else if (Ty->isIntOrIntVector())
5947 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00005948
5949 bool isSignBit = false;
5950
Dan Gohman58c09632008-09-16 18:46:06 +00005951 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005952 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00005953 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005954
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005955 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5956 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005957 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005958 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00005959 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005960 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005961
Dan Gohman58c09632008-09-16 18:46:06 +00005962 // If we have an icmp le or icmp ge instruction, turn it into the
5963 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5964 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00005965 switch (I.getPredicate()) {
5966 default: break;
5967 case ICmpInst::ICMP_ULE:
5968 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00005969 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00005970 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005971 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005972 case ICmpInst::ICMP_SLE:
5973 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00005974 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00005975 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005976 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005977 case ICmpInst::ICMP_UGE:
5978 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00005979 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00005980 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005981 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005982 case ICmpInst::ICMP_SGE:
5983 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00005984 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00005985 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005986 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005987 }
5988
Chris Lattnera1308652008-07-11 05:40:05 +00005989 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005990 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005991 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00005992 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5993 }
5994
5995 // See if we can fold the comparison based on range information we can get
5996 // by checking whether bits are known to be zero or one in the input.
5997 if (BitWidth != 0) {
5998 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5999 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6000
6001 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006002 isSignBit ? APInt::getSignBit(BitWidth)
6003 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006004 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006005 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006006 if (SimplifyDemandedBits(I.getOperandUse(1),
6007 APInt::getAllOnesValue(BitWidth),
6008 Op1KnownZero, Op1KnownOne, 0))
6009 return &I;
6010
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006012 // in. Compute the Min, Max and RHS values based on the known bits. For the
6013 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006014 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6015 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6016 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6017 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6018 Op0Min, Op0Max);
6019 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6020 Op1Min, Op1Max);
6021 } else {
6022 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6023 Op0Min, Op0Max);
6024 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6025 Op1Min, Op1Max);
6026 }
6027
Chris Lattnera1308652008-07-11 05:40:05 +00006028 // If Min and Max are known to be the same, then SimplifyDemandedBits
6029 // figured out that the LHS is a constant. Just constant fold this now so
6030 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006031 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006032 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006033 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006034 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006035 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006036 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006037
Chris Lattnera1308652008-07-11 05:40:05 +00006038 // Based on the range information we know about the LHS, see if we can
6039 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006040 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006041 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006042 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006043 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006044 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006045 break;
6046 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006047 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006048 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006049 break;
6050 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006051 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006052 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006053 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006054 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006055 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006056 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006057 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6058 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006059 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006060 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006061
6062 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6063 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006064 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006065 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006066 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006067 break;
6068 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006069 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006070 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006071 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006072 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006073
6074 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006075 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6077 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006079 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006080
6081 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6082 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006083 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006084 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006085 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006086 break;
6087 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006088 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006089 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006090 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006091 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006092 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006093 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006094 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6095 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006096 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006097 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006098 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006099 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006100 case ICmpInst::ICMP_SGT:
6101 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006102 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006103 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006104 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006105
6106 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006107 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006108 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6109 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006110 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006111 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006112 }
6113 break;
6114 case ICmpInst::ICMP_SGE:
6115 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6116 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006117 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006118 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006119 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006120 break;
6121 case ICmpInst::ICMP_SLE:
6122 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6123 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006124 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006125 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006126 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006127 break;
6128 case ICmpInst::ICMP_UGE:
6129 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6130 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006131 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006132 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006133 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006134 break;
6135 case ICmpInst::ICMP_ULE:
6136 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6137 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006138 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006139 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006140 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006141 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006142 }
Dan Gohman7934d592009-04-25 17:12:48 +00006143
6144 // Turn a signed comparison into an unsigned one if both operands
6145 // are known to have the same sign.
6146 if (I.isSignedPredicate() &&
6147 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6148 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006149 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006150 }
6151
6152 // Test if the ICmpInst instruction is used exclusively by a select as
6153 // part of a minimum or maximum operation. If so, refrain from doing
6154 // any other folding. This helps out other analyses which understand
6155 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6156 // and CodeGen. And in this case, at least one of the comparison
6157 // operands has at least one user besides the compare (the select),
6158 // which would often largely negate the benefit of folding anyway.
6159 if (I.hasOneUse())
6160 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6161 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6162 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6163 return 0;
6164
6165 // See if we are doing a comparison between a constant and an instruction that
6166 // can be folded into the comparison.
6167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006168 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6169 // instruction, see if that instruction also has constants so that the
6170 // instruction can be folded into the icmp
6171 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6172 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6173 return Res;
6174 }
6175
6176 // Handle icmp with constant (but not simple integer constant) RHS
6177 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6178 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6179 switch (LHSI->getOpcode()) {
6180 case Instruction::GetElementPtr:
6181 if (RHSC->isNullValue()) {
6182 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6183 bool isAllZeros = true;
6184 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6185 if (!isa<Constant>(LHSI->getOperand(i)) ||
6186 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6187 isAllZeros = false;
6188 break;
6189 }
6190 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006191 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006192 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006193 }
6194 break;
6195
6196 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006197 // Only fold icmp into the PHI if the phi and fcmp are in the same
6198 // block. If in the same block, we're encouraging jump threading. If
6199 // not, we are just pessimizing the code by making an i1 phi.
6200 if (LHSI->getParent() == I.getParent())
6201 if (Instruction *NV = FoldOpIntoPhi(I))
6202 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006203 break;
6204 case Instruction::Select: {
6205 // If either operand of the select is a constant, we can fold the
6206 // comparison into the select arms, which will cause one to be
6207 // constant folded and the select turned into a bitwise or.
6208 Value *Op1 = 0, *Op2 = 0;
6209 if (LHSI->hasOneUse()) {
6210 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6211 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006212 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006213 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006214 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6215 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006216 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6217 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006218 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006219 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006220 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6221 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006222 }
6223 }
6224
6225 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006226 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006227 break;
6228 }
6229 case Instruction::Malloc:
6230 // If we have (malloc != null), and if the malloc has a single use, we
6231 // can assume it is successful and remove the malloc.
6232 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner3183fb62009-08-30 06:13:40 +00006233 Worklist.Add(LHSI);
Owen Anderson35b47072009-08-13 21:58:54 +00006234 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00006235 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006236 }
6237 break;
6238 }
6239 }
6240
6241 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006242 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006243 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6244 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006245 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006246 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6247 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6248 return NI;
6249
6250 // Test to see if the operands of the icmp are casted versions of other
6251 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6252 // now.
6253 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6254 if (isa<PointerType>(Op0->getType()) &&
6255 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6256 // We keep moving the cast from the left operand over to the right
6257 // operand, where it can often be eliminated completely.
6258 Op0 = CI->getOperand(0);
6259
6260 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6261 // so eliminate it as well.
6262 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6263 Op1 = CI2->getOperand(0);
6264
6265 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006266 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006267 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006268 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006269 } else {
6270 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006271 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006272 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006273 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006274 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006275 }
6276 }
6277
6278 if (isa<CastInst>(Op0)) {
6279 // Handle the special case of: icmp (cast bool to X), <cst>
6280 // This comes up when you have code like
6281 // int X = A < B;
6282 // if (X) ...
6283 // For generality, we handle any zero-extension of any operand comparison
6284 // with a constant or another cast from the same type.
6285 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6286 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6287 return R;
6288 }
6289
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006290 // See if it's the same type of instruction on the left and right.
6291 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6292 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006293 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006294 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006295 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006296 default: break;
6297 case Instruction::Add:
6298 case Instruction::Sub:
6299 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006300 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006301 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006302 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006303 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6304 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6305 if (CI->getValue().isSignBit()) {
6306 ICmpInst::Predicate Pred = I.isSignedPredicate()
6307 ? I.getUnsignedPredicate()
6308 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006309 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006310 Op1I->getOperand(0));
6311 }
6312
6313 if (CI->getValue().isMaxSignedValue()) {
6314 ICmpInst::Predicate Pred = I.isSignedPredicate()
6315 ? I.getUnsignedPredicate()
6316 : I.getSignedPredicate();
6317 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006318 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006319 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006320 }
6321 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006322 break;
6323 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006324 if (!I.isEquality())
6325 break;
6326
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006327 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6328 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6329 // Mask = -1 >> count-trailing-zeros(Cst).
6330 if (!CI->isZero() && !CI->isOne()) {
6331 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006332 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006333 APInt::getLowBitsSet(AP.getBitWidth(),
6334 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006335 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006336 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6337 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006338 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006339 }
6340 }
6341 break;
6342 }
6343 }
6344 }
6345 }
6346
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006347 // ~x < ~y --> y < x
6348 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006349 if (match(Op0, m_Not(m_Value(A))) &&
6350 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006351 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006352 }
6353
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006354 if (I.isEquality()) {
6355 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006356
6357 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006358 if (match(Op0, m_Neg(m_Value(A))) &&
6359 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006360 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006361
Dan Gohmancdff2122009-08-12 16:23:25 +00006362 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006363 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6364 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006365 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006366 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006367 }
6368
Dan Gohmancdff2122009-08-12 16:23:25 +00006369 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006370 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006371 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006372 if (match(B, m_ConstantInt(C1)) &&
6373 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006374 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006375 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006376 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6377 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006378 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006379
6380 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006381 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6382 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6383 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6384 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006385 }
6386 }
6387
Dan Gohmancdff2122009-08-12 16:23:25 +00006388 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006389 (A == Op0 || B == Op0)) {
6390 // A == (A^B) -> B == 0
6391 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006392 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006393 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006394 }
Chris Lattner3b874082008-11-16 05:38:51 +00006395
6396 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006397 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006398 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006399 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006400
6401 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006402 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006403 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006404 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006405
6406 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6407 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006408 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6409 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006410 Value *X = 0, *Y = 0, *Z = 0;
6411
6412 if (A == C) {
6413 X = B; Y = D; Z = A;
6414 } else if (A == D) {
6415 X = B; Y = C; Z = A;
6416 } else if (B == C) {
6417 X = A; Y = D; Z = B;
6418 } else if (B == D) {
6419 X = A; Y = C; Z = B;
6420 }
6421
6422 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006423 Op1 = Builder->CreateXor(X, Y, "tmp");
6424 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006425 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006426 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006427 return &I;
6428 }
6429 }
6430 }
6431 return Changed ? &I : 0;
6432}
6433
6434
6435/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6436/// and CmpRHS are both known to be integer constants.
6437Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6438 ConstantInt *DivRHS) {
6439 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6440 const APInt &CmpRHSV = CmpRHS->getValue();
6441
6442 // FIXME: If the operand types don't match the type of the divide
6443 // then don't attempt this transform. The code below doesn't have the
6444 // logic to deal with a signed divide and an unsigned compare (and
6445 // vice versa). This is because (x /s C1) <s C2 produces different
6446 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6447 // (x /u C1) <u C2. Simply casting the operands and result won't
6448 // work. :( The if statement below tests that condition and bails
6449 // if it finds it.
6450 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6451 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6452 return 0;
6453 if (DivRHS->isZero())
6454 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006455 if (DivIsSigned && DivRHS->isAllOnesValue())
6456 return 0; // The overflow computation also screws up here
6457 if (DivRHS->isOne())
6458 return 0; // Not worth bothering, and eliminates some funny cases
6459 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006460
6461 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6462 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6463 // C2 (CI). By solving for X we can turn this into a range check
6464 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006465 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006466
6467 // Determine if the product overflows by seeing if the product is
6468 // not equal to the divide. Make sure we do the same kind of divide
6469 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006470 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6471 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006472
6473 // Get the ICmp opcode
6474 ICmpInst::Predicate Pred = ICI.getPredicate();
6475
6476 // Figure out the interval that is being checked. For example, a comparison
6477 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6478 // Compute this interval based on the constants involved and the signedness of
6479 // the compare/divide. This computes a half-open interval, keeping track of
6480 // whether either value in the interval overflows. After analysis each
6481 // overflow variable is set to 0 if it's corresponding bound variable is valid
6482 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6483 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006484 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006485
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006486 if (!DivIsSigned) { // udiv
6487 // e.g. X/5 op 3 --> [15, 20)
6488 LoBound = Prod;
6489 HiOverflow = LoOverflow = ProdOV;
6490 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006491 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006492 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006493 if (CmpRHSV == 0) { // (X / pos) op 0
6494 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006495 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006496 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006497 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006498 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6499 HiOverflow = LoOverflow = ProdOV;
6500 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006501 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006502 } else { // (X / pos) op neg
6503 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006504 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006505 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6506 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006507 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006508 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006509 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006510 true) ? -1 : 0;
6511 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006512 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006513 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006514 if (CmpRHSV == 0) { // (X / neg) op 0
6515 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006516 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006517 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006518 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6519 HiOverflow = 1; // [INTMIN+1, overflow)
6520 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6521 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006522 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006523 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006524 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006525 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6526 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006527 LoOverflow = AddWithOverflow(LoBound, HiBound,
6528 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006529 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006530 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6531 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006532 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006533 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006534 }
6535
6536 // Dividing by a negative swaps the condition. LT <-> GT
6537 Pred = ICmpInst::getSwappedPredicate(Pred);
6538 }
6539
6540 Value *X = DivI->getOperand(0);
6541 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006542 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006543 case ICmpInst::ICMP_EQ:
6544 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006545 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006546 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006547 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006548 ICmpInst::ICMP_UGE, X, LoBound);
6549 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006550 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006551 ICmpInst::ICMP_ULT, X, HiBound);
6552 else
6553 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6554 case ICmpInst::ICMP_NE:
6555 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006556 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006558 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006559 ICmpInst::ICMP_ULT, X, LoBound);
6560 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006561 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006562 ICmpInst::ICMP_UGE, X, HiBound);
6563 else
6564 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6565 case ICmpInst::ICMP_ULT:
6566 case ICmpInst::ICMP_SLT:
6567 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006568 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006569 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006570 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006571 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006572 case ICmpInst::ICMP_UGT:
6573 case ICmpInst::ICMP_SGT:
6574 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006575 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006576 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006577 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006578 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006579 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006580 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006581 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006582 }
6583}
6584
6585
6586/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6587///
6588Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6589 Instruction *LHSI,
6590 ConstantInt *RHS) {
6591 const APInt &RHSV = RHS->getValue();
6592
6593 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006594 case Instruction::Trunc:
6595 if (ICI.isEquality() && LHSI->hasOneUse()) {
6596 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6597 // of the high bits truncated out of x are known.
6598 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6599 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6600 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6601 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6602 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6603
6604 // If all the high bits are known, we can do this xform.
6605 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6606 // Pull in the high bits from known-ones set.
6607 APInt NewRHS(RHS->getValue());
6608 NewRHS.zext(SrcBits);
6609 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006610 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006611 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006612 }
6613 }
6614 break;
6615
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006616 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6617 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6618 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6619 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006620 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6621 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006622 Value *CompareVal = LHSI->getOperand(0);
6623
6624 // If the sign bit of the XorCST is not set, there is no change to
6625 // the operation, just stop using the Xor.
6626 if (!XorCST->getValue().isNegative()) {
6627 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006628 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006629 return &ICI;
6630 }
6631
6632 // Was the old condition true if the operand is positive?
6633 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6634
6635 // If so, the new one isn't.
6636 isTrueIfPositive ^= true;
6637
6638 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006639 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006640 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006641 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006642 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006643 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006644 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006645
6646 if (LHSI->hasOneUse()) {
6647 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6648 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6649 const APInt &SignBit = XorCST->getValue();
6650 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6651 ? ICI.getUnsignedPredicate()
6652 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006653 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006654 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006655 }
6656
6657 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006658 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006659 const APInt &NotSignBit = XorCST->getValue();
6660 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6661 ? ICI.getUnsignedPredicate()
6662 : ICI.getSignedPredicate();
6663 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006664 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006665 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006666 }
6667 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006668 }
6669 break;
6670 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6671 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6672 LHSI->getOperand(0)->hasOneUse()) {
6673 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6674
6675 // If the LHS is an AND of a truncating cast, we can widen the
6676 // and/compare to be the input width without changing the value
6677 // produced, eliminating a cast.
6678 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6679 // We can do this transformation if either the AND constant does not
6680 // have its sign bit set or if it is an equality comparison.
6681 // Extending a relational comparison when we're checking the sign
6682 // bit would not work.
6683 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006684 (ICI.isEquality() ||
6685 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006686 uint32_t BitWidth =
6687 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6688 APInt NewCST = AndCST->getValue();
6689 NewCST.zext(BitWidth);
6690 APInt NewCI = RHSV;
6691 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006692 Value *NewAnd =
6693 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006694 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006695 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006696 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006697 }
6698 }
6699
6700 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6701 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6702 // happens a LOT in code produced by the C front-end, for bitfield
6703 // access.
6704 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6705 if (Shift && !Shift->isShift())
6706 Shift = 0;
6707
6708 ConstantInt *ShAmt;
6709 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6710 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6711 const Type *AndTy = AndCST->getType(); // Type of the and.
6712
6713 // We can fold this as long as we can't shift unknown bits
6714 // into the mask. This can only happen with signed shift
6715 // rights, as they sign-extend.
6716 if (ShAmt) {
6717 bool CanFold = Shift->isLogicalShift();
6718 if (!CanFold) {
6719 // To test for the bad case of the signed shr, see if any
6720 // of the bits shifted in could be tested after the mask.
6721 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6722 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6723
6724 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6725 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6726 AndCST->getValue()) == 0)
6727 CanFold = true;
6728 }
6729
6730 if (CanFold) {
6731 Constant *NewCst;
6732 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006733 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006734 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006735 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006736
6737 // Check to see if we are shifting out any of the bits being
6738 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006739 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006740 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006741 // If we shifted bits out, the fold is not going to work out.
6742 // As a special case, check to see if this means that the
6743 // result is always true or false now.
6744 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006745 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006746 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006747 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006748 } else {
6749 ICI.setOperand(1, NewCst);
6750 Constant *NewAndCST;
6751 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006752 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006753 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006754 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006755 LHSI->setOperand(1, NewAndCST);
6756 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006757 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006758 return &ICI;
6759 }
6760 }
6761 }
6762
6763 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6764 // preferable because it allows the C<<Y expression to be hoisted out
6765 // of a loop if Y is invariant and X is not.
6766 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006767 ICI.isEquality() && !Shift->isArithmeticShift() &&
6768 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006769 // Compute C << Y.
6770 Value *NS;
6771 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006772 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006773 } else {
6774 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006775 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006776 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006777
6778 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006779 Value *NewAnd =
6780 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006781
6782 ICI.setOperand(0, NewAnd);
6783 return &ICI;
6784 }
6785 }
6786 break;
6787
6788 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6789 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6790 if (!ShAmt) break;
6791
6792 uint32_t TypeBits = RHSV.getBitWidth();
6793
6794 // Check that the shift amount is in range. If not, don't perform
6795 // undefined shifts. When the shift is visited it will be
6796 // simplified.
6797 if (ShAmt->uge(TypeBits))
6798 break;
6799
6800 if (ICI.isEquality()) {
6801 // If we are comparing against bits always shifted out, the
6802 // comparison cannot succeed.
6803 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006804 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006805 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006806 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6807 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006808 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 return ReplaceInstUsesWith(ICI, Cst);
6810 }
6811
6812 if (LHSI->hasOneUse()) {
6813 // Otherwise strength reduce the shift into an and.
6814 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6815 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006816 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006817 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006818
Chris Lattnerc7694852009-08-30 07:44:24 +00006819 Value *And =
6820 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006821 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006822 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823 }
6824 }
6825
6826 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6827 bool TrueIfSigned = false;
6828 if (LHSI->hasOneUse() &&
6829 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6830 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006831 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006832 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00006833 Value *And =
6834 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006835 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006836 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006837 }
6838 break;
6839 }
6840
6841 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6842 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006843 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006844 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006845 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006846
Chris Lattner5ee84f82008-03-21 05:19:58 +00006847 // Check that the shift amount is in range. If not, don't perform
6848 // undefined shifts. When the shift is visited it will be
6849 // simplified.
6850 uint32_t TypeBits = RHSV.getBitWidth();
6851 if (ShAmt->uge(TypeBits))
6852 break;
6853
6854 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006855
Chris Lattner5ee84f82008-03-21 05:19:58 +00006856 // If we are comparing against bits always shifted out, the
6857 // comparison cannot succeed.
6858 APInt Comp = RHSV << ShAmtVal;
6859 if (LHSI->getOpcode() == Instruction::LShr)
6860 Comp = Comp.lshr(ShAmtVal);
6861 else
6862 Comp = Comp.ashr(ShAmtVal);
6863
6864 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6865 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006866 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006867 return ReplaceInstUsesWith(ICI, Cst);
6868 }
6869
6870 // Otherwise, check to see if the bits shifted out are known to be zero.
6871 // If so, we can compare against the unshifted value:
6872 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006873 if (LHSI->hasOneUse() &&
6874 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006875 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006876 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006877 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006878 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879
Evan Chengfb9292a2008-04-23 00:38:06 +00006880 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006881 // Otherwise strength reduce the shift into an and.
6882 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00006883 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006884
Chris Lattnerc7694852009-08-30 07:44:24 +00006885 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6886 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006887 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00006888 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006889 }
6890 break;
6891 }
6892
6893 case Instruction::SDiv:
6894 case Instruction::UDiv:
6895 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6896 // Fold this div into the comparison, producing a range check.
6897 // Determine, based on the divide type, what the range is being
6898 // checked. If there is an overflow on the low or high side, remember
6899 // it, otherwise compute the range [low, hi) bounding the new value.
6900 // See: InsertRangeTest above for the kinds of replacements possible.
6901 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6902 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6903 DivRHS))
6904 return R;
6905 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006906
6907 case Instruction::Add:
6908 // Fold: icmp pred (add, X, C1), C2
6909
6910 if (!ICI.isEquality()) {
6911 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6912 if (!LHSC) break;
6913 const APInt &LHSV = LHSC->getValue();
6914
6915 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6916 .subtract(LHSV);
6917
6918 if (ICI.isSignedPredicate()) {
6919 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006920 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006921 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006922 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006923 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006924 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006925 }
6926 } else {
6927 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006928 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006929 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006930 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006931 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006932 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006933 }
6934 }
6935 }
6936 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006937 }
6938
6939 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6940 if (ICI.isEquality()) {
6941 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6942
6943 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6944 // the second operand is a constant, simplify a bit.
6945 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6946 switch (BO->getOpcode()) {
6947 case Instruction::SRem:
6948 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6949 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6950 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6951 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006952 Value *NewRem =
6953 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6954 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006955 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00006956 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006957 }
6958 }
6959 break;
6960 case Instruction::Add:
6961 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6962 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6963 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00006964 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006965 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006966 } else if (RHSV == 0) {
6967 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6968 // efficiently invertible, or if the add has just this one use.
6969 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6970
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006971 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00006972 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006973 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00006974 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006975 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006976 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006977 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00006978 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006979 }
6980 }
6981 break;
6982 case Instruction::Xor:
6983 // For the xor case, we can xor two constants together, eliminating
6984 // the explicit xor.
6985 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00006986 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006987 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006988
6989 // FALLTHROUGH
6990 case Instruction::Sub:
6991 // Replace (([sub|xor] A, B) != 0) with (A != B)
6992 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00006993 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006994 BO->getOperand(1));
6995 break;
6996
6997 case Instruction::Or:
6998 // If bits are being or'd in that are not present in the constant we
6999 // are comparing against, then the comparison could never succeed!
7000 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007001 Constant *NotCI = ConstantExpr::getNot(RHS);
7002 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007003 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007004 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007005 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007006 }
7007 break;
7008
7009 case Instruction::And:
7010 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7011 // If bits are being compared against that are and'd out, then the
7012 // comparison can never succeed!
7013 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007014 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007015 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007016 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007017
7018 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7019 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007020 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007021 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007022 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007023
7024 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007025 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007026 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007027 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007028 ICmpInst::Predicate pred = isICMP_NE ?
7029 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007030 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007031 }
7032
7033 // ((X & ~7) == 0) --> X < 8
7034 if (RHSV == 0 && isHighOnes(BOC)) {
7035 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007036 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007037 ICmpInst::Predicate pred = isICMP_NE ?
7038 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007039 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007040 }
7041 }
7042 default: break;
7043 }
7044 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7045 // Handle icmp {eq|ne} <intrinsic>, intcst.
7046 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007047 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007048 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007049 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007050 return &ICI;
7051 }
7052 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007053 }
7054 return 0;
7055}
7056
7057/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7058/// We only handle extending casts so far.
7059///
7060Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7061 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7062 Value *LHSCIOp = LHSCI->getOperand(0);
7063 const Type *SrcTy = LHSCIOp->getType();
7064 const Type *DestTy = LHSCI->getType();
7065 Value *RHSCIOp;
7066
7067 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7068 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007069 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7070 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007071 cast<IntegerType>(DestTy)->getBitWidth()) {
7072 Value *RHSOp = 0;
7073 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007074 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007075 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7076 RHSOp = RHSC->getOperand(0);
7077 // If the pointer types don't match, insert a bitcast.
7078 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007079 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007080 }
7081
7082 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007083 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 }
7085
7086 // The code below only handles extension cast instructions, so far.
7087 // Enforce this.
7088 if (LHSCI->getOpcode() != Instruction::ZExt &&
7089 LHSCI->getOpcode() != Instruction::SExt)
7090 return 0;
7091
7092 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7093 bool isSignedCmp = ICI.isSignedPredicate();
7094
7095 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7096 // Not an extension from the same type?
7097 RHSCIOp = CI->getOperand(0);
7098 if (RHSCIOp->getType() != LHSCIOp->getType())
7099 return 0;
7100
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007101 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007102 // and the other is a zext), then we can't handle this.
7103 if (CI->getOpcode() != LHSCI->getOpcode())
7104 return 0;
7105
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007106 // Deal with equality cases early.
7107 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007108 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007109
7110 // A signed comparison of sign extended values simplifies into a
7111 // signed comparison.
7112 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007113 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007114
7115 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007116 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007117 }
7118
7119 // If we aren't dealing with a constant on the RHS, exit early
7120 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7121 if (!CI)
7122 return 0;
7123
7124 // Compute the constant that would happen if we truncated to SrcTy then
7125 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007126 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7127 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007128 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007129
7130 // If the re-extended constant didn't change...
7131 if (Res2 == CI) {
7132 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7133 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007134 // %A = sext i16 %X to i32
7135 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007136 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007137 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138 // because %A may have negative value.
7139 //
Chris Lattner3d816532008-07-11 04:09:09 +00007140 // However, we allow this when the compare is EQ/NE, because they are
7141 // signless.
7142 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007143 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007144 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007145 }
7146
7147 // The re-extended constant changed so the constant cannot be represented
7148 // in the shorter type. Consequently, we cannot emit a simple comparison.
7149
7150 // First, handle some easy cases. We know the result cannot be equal at this
7151 // point so handle the ICI.isEquality() cases
7152 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007153 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007154 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007155 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007156
7157 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7158 // should have been folded away previously and not enter in here.
7159 Value *Result;
7160 if (isSignedCmp) {
7161 // We're performing a signed comparison.
7162 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007163 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007164 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007165 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007166 } else {
7167 // We're performing an unsigned comparison.
7168 if (isSignedExt) {
7169 // We're performing an unsigned comp with a sign extended value.
7170 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007171 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007172 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007173 } else {
7174 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007175 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007176 }
7177 }
7178
7179 // Finally, return the value computed.
7180 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007181 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007182 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007183
7184 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7185 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7186 "ICmp should be folded!");
7187 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007188 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007189 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007190}
7191
7192Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7193 return commonShiftTransforms(I);
7194}
7195
7196Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7197 return commonShiftTransforms(I);
7198}
7199
7200Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007201 if (Instruction *R = commonShiftTransforms(I))
7202 return R;
7203
7204 Value *Op0 = I.getOperand(0);
7205
7206 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7207 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7208 if (CSI->isAllOnesValue())
7209 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007210
Dan Gohman2526aea2009-06-16 19:55:29 +00007211 // See if we can turn a signed shr into an unsigned shr.
7212 if (MaskedValueIsZero(Op0,
7213 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7214 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7215
7216 // Arithmetic shifting an all-sign-bit value is a no-op.
7217 unsigned NumSignBits = ComputeNumSignBits(Op0);
7218 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7219 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007220
Chris Lattnere3c504f2007-12-06 01:59:46 +00007221 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007222}
7223
7224Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7225 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7227
7228 // shl X, 0 == X and shr X, 0 == X
7229 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007230 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7231 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007232 return ReplaceInstUsesWith(I, Op0);
7233
7234 if (isa<UndefValue>(Op0)) {
7235 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7236 return ReplaceInstUsesWith(I, Op0);
7237 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007238 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007239 }
7240 if (isa<UndefValue>(Op1)) {
7241 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7242 return ReplaceInstUsesWith(I, Op0);
7243 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007244 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007245 }
7246
Dan Gohman2bc21562009-05-21 02:28:33 +00007247 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007248 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007249 return &I;
7250
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007251 // Try to fold constant and into select arguments.
7252 if (isa<Constant>(Op0))
7253 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7254 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7255 return R;
7256
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007257 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7258 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7259 return Res;
7260 return 0;
7261}
7262
7263Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7264 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007265 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007266
7267 // See if we can simplify any instructions used by the instruction whose sole
7268 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007269 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007270
Dan Gohman9e1657f2009-06-14 23:30:43 +00007271 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7272 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007273 //
7274 if (Op1->uge(TypeBits)) {
7275 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007276 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007278 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007279 return &I;
7280 }
7281 }
7282
7283 // ((X*C1) << C2) == (X * (C1 << C2))
7284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7285 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7286 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007287 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007288 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007289
7290 // Try to fold constant and into select arguments.
7291 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7292 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7293 return R;
7294 if (isa<PHINode>(Op0))
7295 if (Instruction *NV = FoldOpIntoPhi(I))
7296 return NV;
7297
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007298 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7299 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7300 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7301 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7302 // place. Don't try to do this transformation in this case. Also, we
7303 // require that the input operand is a shift-by-constant so that we have
7304 // confidence that the shifts will get folded together. We could do this
7305 // xform in more cases, but it is unlikely to be profitable.
7306 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7307 isa<ConstantInt>(TrOp->getOperand(1))) {
7308 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007309 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007310 // (shift2 (shift1 & 0x00FF), c2)
7311 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007312
7313 // For logical shifts, the truncation has the effect of making the high
7314 // part of the register be zeros. Emulate this by inserting an AND to
7315 // clear the top bits as needed. This 'and' will usually be zapped by
7316 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007317 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7318 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007319 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7320
7321 // The mask we constructed says what the trunc would do if occurring
7322 // between the shifts. We want to know the effect *after* the second
7323 // shift. We know that it is a logical shift by a constant, so adjust the
7324 // mask as appropriate.
7325 if (I.getOpcode() == Instruction::Shl)
7326 MaskV <<= Op1->getZExtValue();
7327 else {
7328 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7329 MaskV = MaskV.lshr(Op1->getZExtValue());
7330 }
7331
Chris Lattnerc7694852009-08-30 07:44:24 +00007332 // shift1 & 0x00FF
7333 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7334 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007335
7336 // Return the value truncated to the interesting size.
7337 return new TruncInst(And, I.getType());
7338 }
7339 }
7340
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007341 if (Op0->hasOneUse()) {
7342 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7343 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7344 Value *V1, *V2;
7345 ConstantInt *CC;
7346 switch (Op0BO->getOpcode()) {
7347 default: break;
7348 case Instruction::Add:
7349 case Instruction::And:
7350 case Instruction::Or:
7351 case Instruction::Xor: {
7352 // These operators commute.
7353 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7354 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007355 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007356 m_Specific(Op1)))) {
7357 Value *YS = // (Y << C)
7358 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7359 // (X + (Y << C))
7360 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7361 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007362 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007363 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007364 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7365 }
7366
7367 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7368 Value *Op0BOOp1 = Op0BO->getOperand(1);
7369 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7370 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007371 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007372 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007373 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007374 Value *YS = // (Y << C)
7375 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7376 Op0BO->getName());
7377 // X & (CC << C)
7378 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7379 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007380 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007381 }
7382 }
7383
7384 // FALL THROUGH.
7385 case Instruction::Sub: {
7386 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7387 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007388 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007389 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007390 Value *YS = // (Y << C)
7391 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7392 // (X + (Y << C))
7393 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7394 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007395 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007396 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007397 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7398 }
7399
7400 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7401 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7402 match(Op0BO->getOperand(0),
7403 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007404 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007405 cast<BinaryOperator>(Op0BO->getOperand(0))
7406 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007407 Value *YS = // (Y << C)
7408 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7409 // X & (CC << C)
7410 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7411 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007412
Gabor Greifa645dd32008-05-16 19:29:10 +00007413 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007414 }
7415
7416 break;
7417 }
7418 }
7419
7420
7421 // If the operand is an bitwise operator with a constant RHS, and the
7422 // shift is the only use, we can pull it out of the shift.
7423 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7424 bool isValid = true; // Valid only for And, Or, Xor
7425 bool highBitSet = false; // Transform if high bit of constant set?
7426
7427 switch (Op0BO->getOpcode()) {
7428 default: isValid = false; break; // Do not perform transform!
7429 case Instruction::Add:
7430 isValid = isLeftShift;
7431 break;
7432 case Instruction::Or:
7433 case Instruction::Xor:
7434 highBitSet = false;
7435 break;
7436 case Instruction::And:
7437 highBitSet = true;
7438 break;
7439 }
7440
7441 // If this is a signed shift right, and the high bit is modified
7442 // by the logical operation, do not perform the transformation.
7443 // The highBitSet boolean indicates the value of the high bit of
7444 // the constant which would cause it to be modified for this
7445 // operation.
7446 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007447 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007448 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007449
7450 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007451 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007452
Chris Lattnerad7516a2009-08-30 18:50:58 +00007453 Value *NewShift =
7454 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007455 NewShift->takeName(Op0BO);
7456
Gabor Greifa645dd32008-05-16 19:29:10 +00007457 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007458 NewRHS);
7459 }
7460 }
7461 }
7462 }
7463
7464 // Find out if this is a shift of a shift by a constant.
7465 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7466 if (ShiftOp && !ShiftOp->isShift())
7467 ShiftOp = 0;
7468
7469 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7470 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7471 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7472 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7473 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7474 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7475 Value *X = ShiftOp->getOperand(0);
7476
7477 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007478
7479 const IntegerType *Ty = cast<IntegerType>(I.getType());
7480
7481 // Check for (X << c1) << c2 and (X >> c1) >> c2
7482 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007483 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7484 // saturates.
7485 if (AmtSum >= TypeBits) {
7486 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007487 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007488 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7489 }
7490
Gabor Greifa645dd32008-05-16 19:29:10 +00007491 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007492 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007493 }
7494
7495 if (ShiftOp->getOpcode() == Instruction::LShr &&
7496 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007497 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007499
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007500 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007501 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007502 }
7503
7504 if (ShiftOp->getOpcode() == Instruction::AShr &&
7505 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007506 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007507 if (AmtSum >= TypeBits)
7508 AmtSum = TypeBits-1;
7509
Chris Lattnerad7516a2009-08-30 18:50:58 +00007510 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007511
7512 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007513 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007514 }
7515
7516 // Okay, if we get here, one shift must be left, and the other shift must be
7517 // right. See if the amounts are equal.
7518 if (ShiftAmt1 == ShiftAmt2) {
7519 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7520 if (I.getOpcode() == Instruction::Shl) {
7521 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007522 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007523 }
7524 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7525 if (I.getOpcode() == Instruction::LShr) {
7526 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007527 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007528 }
7529 // We can simplify ((X << C) >>s C) into a trunc + sext.
7530 // NOTE: we could do this for any C, but that would make 'unusual' integer
7531 // types. For now, just stick to ones well-supported by the code
7532 // generators.
7533 const Type *SExtType = 0;
7534 switch (Ty->getBitWidth() - ShiftAmt1) {
7535 case 1 :
7536 case 8 :
7537 case 16 :
7538 case 32 :
7539 case 64 :
7540 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007541 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542 break;
7543 default: break;
7544 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007545 if (SExtType)
7546 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007547 // Otherwise, we can't handle it yet.
7548 } else if (ShiftAmt1 < ShiftAmt2) {
7549 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7550
7551 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7552 if (I.getOpcode() == Instruction::Shl) {
7553 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7554 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007555 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007556
7557 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007558 return BinaryOperator::CreateAnd(Shift,
7559 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007560 }
7561
7562 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7563 if (I.getOpcode() == Instruction::LShr) {
7564 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007565 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007566
7567 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007568 return BinaryOperator::CreateAnd(Shift,
7569 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007570 }
7571
7572 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7573 } else {
7574 assert(ShiftAmt2 < ShiftAmt1);
7575 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7576
7577 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7578 if (I.getOpcode() == Instruction::Shl) {
7579 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7580 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007581 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7582 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007583
7584 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007585 return BinaryOperator::CreateAnd(Shift,
7586 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007587 }
7588
7589 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7590 if (I.getOpcode() == Instruction::LShr) {
7591 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007592 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007593
7594 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007595 return BinaryOperator::CreateAnd(Shift,
7596 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007597 }
7598
7599 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7600 }
7601 }
7602 return 0;
7603}
7604
7605
7606/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7607/// expression. If so, decompose it, returning some value X, such that Val is
7608/// X*Scale+Offset.
7609///
7610static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007611 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007612 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7613 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007614 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7615 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007616 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007617 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007618 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7619 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7620 if (I->getOpcode() == Instruction::Shl) {
7621 // This is a value scaled by '1 << the shift amt'.
7622 Scale = 1U << RHS->getZExtValue();
7623 Offset = 0;
7624 return I->getOperand(0);
7625 } else if (I->getOpcode() == Instruction::Mul) {
7626 // This value is scaled by 'RHS'.
7627 Scale = RHS->getZExtValue();
7628 Offset = 0;
7629 return I->getOperand(0);
7630 } else if (I->getOpcode() == Instruction::Add) {
7631 // We have X+C. Check to see if we really have (X*C2)+C1,
7632 // where C1 is divisible by C2.
7633 unsigned SubScale;
7634 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007635 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7636 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007637 Offset += RHS->getZExtValue();
7638 Scale = SubScale;
7639 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007640 }
7641 }
7642 }
7643
7644 // Otherwise, we can't look past this.
7645 Scale = 1;
7646 Offset = 0;
7647 return Val;
7648}
7649
7650
7651/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7652/// try to eliminate the cast by moving the type information into the alloc.
7653Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7654 AllocationInst &AI) {
7655 const PointerType *PTy = cast<PointerType>(CI.getType());
7656
Chris Lattnerad7516a2009-08-30 18:50:58 +00007657 BuilderTy AllocaBuilder(*Builder);
7658 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7659
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007660 // Remove any uses of AI that are dead.
7661 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7662
7663 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7664 Instruction *User = cast<Instruction>(*UI++);
7665 if (isInstructionTriviallyDead(User)) {
7666 while (UI != E && *UI == User)
7667 ++UI; // If this instruction uses AI more than once, don't break UI.
7668
7669 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007670 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007671 EraseInstFromFunction(*User);
7672 }
7673 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007674
7675 // This requires TargetData to get the alloca alignment and size information.
7676 if (!TD) return 0;
7677
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007678 // Get the type really allocated and the type casted to.
7679 const Type *AllocElTy = AI.getAllocatedType();
7680 const Type *CastElTy = PTy->getElementType();
7681 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7682
7683 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7684 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7685 if (CastElTyAlign < AllocElTyAlign) return 0;
7686
7687 // If the allocation has multiple uses, only promote it if we are strictly
7688 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007689 // same, we open the door to infinite loops of various kinds. (A reference
7690 // from a dbg.declare doesn't count as a use for this purpose.)
7691 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7692 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007693
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007694 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7695 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7697
7698 // See if we can satisfy the modulus by pulling a scale out of the array
7699 // size argument.
7700 unsigned ArraySizeScale;
7701 int ArrayOffset;
7702 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007703 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7704 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007705
7706 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7707 // do the xform.
7708 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7709 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7710
7711 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7712 Value *Amt = 0;
7713 if (Scale == 1) {
7714 Amt = NumElements;
7715 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007716 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007717 // Insert before the alloca, not before the cast.
7718 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719 }
7720
7721 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007722 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007723 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007724 }
7725
7726 AllocationInst *New;
7727 if (isa<MallocInst>(AI))
Chris Lattnerad7516a2009-08-30 18:50:58 +00007728 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007729 else
Chris Lattnerad7516a2009-08-30 18:50:58 +00007730 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7731 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007732 New->takeName(&AI);
7733
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007734 // If the allocation has one real use plus a dbg.declare, just remove the
7735 // declare.
7736 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7737 EraseInstFromFunction(*DI);
7738 }
7739 // If the allocation has multiple real uses, insert a cast and change all
7740 // things that used it to use the new cast. This will also hack on CI, but it
7741 // will die soon.
7742 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007743 // New is the allocation instruction, pointer typed. AI is the original
7744 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007745 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007746 AI.replaceAllUsesWith(NewCast);
7747 }
7748 return ReplaceInstUsesWith(CI, New);
7749}
7750
7751/// CanEvaluateInDifferentType - Return true if we can take the specified value
7752/// and return it as type Ty without inserting any new casts and without
7753/// changing the computed value. This is used by code that tries to decide
7754/// whether promoting or shrinking integer operations to wider or smaller types
7755/// will allow us to eliminate a truncate or extend.
7756///
7757/// This is a truncation operation if Ty is smaller than V->getType(), or an
7758/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007759///
7760/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7761/// should return true if trunc(V) can be computed by computing V in the smaller
7762/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7763/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7764/// efficiently truncated.
7765///
7766/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7767/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7768/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007769bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007770 unsigned CastOpc,
7771 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007772 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007773 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007774 return true;
7775
7776 Instruction *I = dyn_cast<Instruction>(V);
7777 if (!I) return false;
7778
Dan Gohman8fd520a2009-06-15 22:12:54 +00007779 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007780
Chris Lattneref70bb82007-08-02 06:11:14 +00007781 // If this is an extension or truncate, we can often eliminate it.
7782 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7783 // If this is a cast from the destination type, we can trivially eliminate
7784 // it, and this will remove a cast overall.
7785 if (I->getOperand(0)->getType() == Ty) {
7786 // If the first operand is itself a cast, and is eliminable, do not count
7787 // this as an eliminable cast. We would prefer to eliminate those two
7788 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007789 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007790 ++NumCastsRemoved;
7791 return true;
7792 }
7793 }
7794
7795 // We can't extend or shrink something that has multiple uses: doing so would
7796 // require duplicating the instruction in general, which isn't profitable.
7797 if (!I->hasOneUse()) return false;
7798
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007799 unsigned Opc = I->getOpcode();
7800 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007801 case Instruction::Add:
7802 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007803 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007804 case Instruction::And:
7805 case Instruction::Or:
7806 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007807 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007808 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007809 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007810 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007811 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007812
Eli Friedman08c45bc2009-07-13 22:46:01 +00007813 case Instruction::UDiv:
7814 case Instruction::URem: {
7815 // UDiv and URem can be truncated if all the truncated bits are zero.
7816 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7817 uint32_t BitWidth = Ty->getScalarSizeInBits();
7818 if (BitWidth < OrigBitWidth) {
7819 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7820 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7821 MaskedValueIsZero(I->getOperand(1), Mask)) {
7822 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7823 NumCastsRemoved) &&
7824 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7825 NumCastsRemoved);
7826 }
7827 }
7828 break;
7829 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007830 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007831 // If we are truncating the result of this SHL, and if it's a shift of a
7832 // constant amount, we can always perform a SHL in a smaller type.
7833 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007834 uint32_t BitWidth = Ty->getScalarSizeInBits();
7835 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007836 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007837 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007838 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007839 }
7840 break;
7841 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007842 // If this is a truncate of a logical shr, we can truncate it to a smaller
7843 // lshr iff we know that the bits we would otherwise be shifting in are
7844 // already zeros.
7845 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007846 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7847 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007848 if (BitWidth < OrigBitWidth &&
7849 MaskedValueIsZero(I->getOperand(0),
7850 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7851 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007852 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007853 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007854 }
7855 }
7856 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007857 case Instruction::ZExt:
7858 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007859 case Instruction::Trunc:
7860 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007861 // can safely replace it. Note that replacing it does not reduce the number
7862 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007863 if (Opc == CastOpc)
7864 return true;
7865
7866 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007867 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007868 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007869 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007870 case Instruction::Select: {
7871 SelectInst *SI = cast<SelectInst>(I);
7872 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007873 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007874 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007875 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007876 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007877 case Instruction::PHI: {
7878 // We can change a phi if we can change all operands.
7879 PHINode *PN = cast<PHINode>(I);
7880 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7881 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007882 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007883 return false;
7884 return true;
7885 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007886 default:
7887 // TODO: Can handle more cases here.
7888 break;
7889 }
7890
7891 return false;
7892}
7893
7894/// EvaluateInDifferentType - Given an expression that
7895/// CanEvaluateInDifferentType returns true for, actually insert the code to
7896/// evaluate the expression.
7897Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7898 bool isSigned) {
7899 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00007900 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007901 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902
7903 // Otherwise, it must be an instruction.
7904 Instruction *I = cast<Instruction>(V);
7905 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007906 unsigned Opc = I->getOpcode();
7907 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007908 case Instruction::Add:
7909 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007910 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 case Instruction::And:
7912 case Instruction::Or:
7913 case Instruction::Xor:
7914 case Instruction::AShr:
7915 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00007916 case Instruction::Shl:
7917 case Instruction::UDiv:
7918 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007919 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7920 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007921 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007922 break;
7923 }
7924 case Instruction::Trunc:
7925 case Instruction::ZExt:
7926 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007927 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007928 // just return the source. There's no need to insert it because it is not
7929 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007930 if (I->getOperand(0)->getType() == Ty)
7931 return I->getOperand(0);
7932
Chris Lattner4200c2062008-06-18 04:00:49 +00007933 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007934 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007935 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007936 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007937 case Instruction::Select: {
7938 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7939 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7940 Res = SelectInst::Create(I->getOperand(0), True, False);
7941 break;
7942 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007943 case Instruction::PHI: {
7944 PHINode *OPN = cast<PHINode>(I);
7945 PHINode *NPN = PHINode::Create(Ty);
7946 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7947 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7948 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7949 }
7950 Res = NPN;
7951 break;
7952 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007953 default:
7954 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00007955 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007956 break;
7957 }
7958
Chris Lattner4200c2062008-06-18 04:00:49 +00007959 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007960 return InsertNewInstBefore(Res, *I);
7961}
7962
7963/// @brief Implement the transforms common to all CastInst visitors.
7964Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7965 Value *Src = CI.getOperand(0);
7966
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007967 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7968 // eliminate it now.
7969 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7970 if (Instruction::CastOps opc =
7971 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7972 // The first cast (CSrc) is eliminable so we need to fix up or replace
7973 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007974 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007975 }
7976 }
7977
7978 // If we are casting a select then fold the cast into the select
7979 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7980 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7981 return NV;
7982
7983 // If we are casting a PHI then fold the cast into the PHI
7984 if (isa<PHINode>(Src))
7985 if (Instruction *NV = FoldOpIntoPhi(CI))
7986 return NV;
7987
7988 return 0;
7989}
7990
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007991/// FindElementAtOffset - Given a type and a constant offset, determine whether
7992/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00007993/// the specified offset. If so, fill them into NewIndices and return the
7994/// resultant element type, otherwise return null.
7995static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7996 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00007997 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00007998 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00007999 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008000 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008001
8002 // Start with the index over the outer type. Note that the type size
8003 // might be zero (even if the offset isn't zero) if the indexed type
8004 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008005 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008006 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008007 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008008 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008009 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008010
Chris Lattnerce48c462009-01-11 20:15:20 +00008011 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008012 if (Offset < 0) {
8013 --FirstIdx;
8014 Offset += TySize;
8015 assert(Offset >= 0);
8016 }
8017 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8018 }
8019
Owen Andersoneacb44d2009-07-24 23:12:02 +00008020 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008021
8022 // Index into the types. If we fail, set OrigBase to null.
8023 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008024 // Indexing into tail padding between struct/array elements.
8025 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008026 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008027
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008028 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8029 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008030 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8031 "Offset must stay within the indexed type");
8032
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008033 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008034 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008035
8036 Offset -= SL->getElementOffset(Elt);
8037 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008038 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008039 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008040 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008041 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008042 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008043 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008044 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008045 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008046 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008047 }
8048 }
8049
Chris Lattner54dddc72009-01-24 01:00:13 +00008050 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008051}
8052
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008053/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8054Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8055 Value *Src = CI.getOperand(0);
8056
8057 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8058 // If casting the result of a getelementptr instruction with no offset, turn
8059 // this into a cast of the original pointer!
8060 if (GEP->hasAllZeroIndices()) {
8061 // Changing the cast operand is usually not a good idea but it is safe
8062 // here because the pointer operand is being replaced with another
8063 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008064 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008065 CI.setOperand(0, GEP->getOperand(0));
8066 return &CI;
8067 }
8068
8069 // If the GEP has a single use, and the base pointer is a bitcast, and the
8070 // GEP computes a constant offset, see if we can convert these three
8071 // instructions into fewer. This typically happens with unions and other
8072 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008073 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008074 if (GEP->hasAllConstantIndices()) {
8075 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008076 ConstantInt *OffsetV =
8077 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008078 int64_t Offset = OffsetV->getSExtValue();
8079
8080 // Get the base pointer input of the bitcast, and the type it points to.
8081 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8082 const Type *GEPIdxTy =
8083 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008084 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008085 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008086 // If we were able to index down into an element, create the GEP
8087 // and bitcast the result. This eliminates one bitcast, potentially
8088 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008089 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8090 Builder->CreateInBoundsGEP(OrigBase,
8091 NewIndices.begin(), NewIndices.end()) :
8092 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008093 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008094
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008095 if (isa<BitCastInst>(CI))
8096 return new BitCastInst(NGEP, CI.getType());
8097 assert(isa<PtrToIntInst>(CI));
8098 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008099 }
8100 }
8101 }
8102 }
8103
8104 return commonCastTransforms(CI);
8105}
8106
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008107/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8108/// type like i42. We don't want to introduce operations on random non-legal
8109/// integer types where they don't already exist in the code. In the future,
8110/// we should consider making this based off target-data, so that 32-bit targets
8111/// won't get i64 operations etc.
8112static bool isSafeIntegerType(const Type *Ty) {
8113 switch (Ty->getPrimitiveSizeInBits()) {
8114 case 8:
8115 case 16:
8116 case 32:
8117 case 64:
8118 return true;
8119 default:
8120 return false;
8121 }
8122}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008123
Eli Friedman827e37a2009-07-13 20:58:59 +00008124/// commonIntCastTransforms - This function implements the common transforms
8125/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008126Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8127 if (Instruction *Result = commonCastTransforms(CI))
8128 return Result;
8129
8130 Value *Src = CI.getOperand(0);
8131 const Type *SrcTy = Src->getType();
8132 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008133 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8134 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008135
8136 // See if we can simplify any instructions used by the LHS whose sole
8137 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008138 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008139 return &CI;
8140
8141 // If the source isn't an instruction or has more than one use then we
8142 // can't do anything more.
8143 Instruction *SrcI = dyn_cast<Instruction>(Src);
8144 if (!SrcI || !Src->hasOneUse())
8145 return 0;
8146
8147 // Attempt to propagate the cast into the instruction for int->int casts.
8148 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008149 // Only do this if the dest type is a simple type, don't convert the
8150 // expression tree to something weird like i93 unless the source is also
8151 // strange.
8152 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008153 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8154 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008155 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008156 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008157 // eliminates the cast, so it is always a win. If this is a zero-extension,
8158 // we need to do an AND to maintain the clear top-part of the computation,
8159 // so we require that the input have eliminated at least one cast. If this
8160 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008161 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008162 bool DoXForm = false;
8163 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008164 switch (CI.getOpcode()) {
8165 default:
8166 // All the others use floating point so we shouldn't actually
8167 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008168 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008169 case Instruction::Trunc:
8170 DoXForm = true;
8171 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008172 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008173 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008174 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008175 // If it's unnecessary to issue an AND to clear the high bits, it's
8176 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008177 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008178 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8179 if (MaskedValueIsZero(TryRes, Mask))
8180 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008181
8182 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008183 if (TryI->use_empty())
8184 EraseInstFromFunction(*TryI);
8185 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008186 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008187 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008188 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008189 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008190 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008191 // If we do not have to emit the truncate + sext pair, then it's always
8192 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008193 //
8194 // It's not safe to eliminate the trunc + sext pair if one of the
8195 // eliminated cast is a truncate. e.g.
8196 // t2 = trunc i32 t1 to i16
8197 // t3 = sext i16 t2 to i32
8198 // !=
8199 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008200 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008201 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8202 if (NumSignBits > (DestBitSize - SrcBitSize))
8203 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008204
8205 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008206 if (TryI->use_empty())
8207 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008208 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008209 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008210 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008211 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008212
8213 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008214 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8215 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008216 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8217 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008218 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008219 // Just replace this cast with the result.
8220 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008221
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008222 assert(Res->getType() == DestTy);
8223 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008224 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008225 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008226 // Just replace this cast with the result.
8227 return ReplaceInstUsesWith(CI, Res);
8228 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008229 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008230
8231 // If the high bits are already zero, just replace this cast with the
8232 // result.
8233 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8234 if (MaskedValueIsZero(Res, Mask))
8235 return ReplaceInstUsesWith(CI, Res);
8236
8237 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008238 Constant *C = ConstantInt::get(*Context,
8239 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008240 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008241 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008242 case Instruction::SExt: {
8243 // If the high bits are already filled with sign bit, just replace this
8244 // cast with the result.
8245 unsigned NumSignBits = ComputeNumSignBits(Res);
8246 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008247 return ReplaceInstUsesWith(CI, Res);
8248
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008249 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008250 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008252 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008253 }
8254 }
8255
8256 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8257 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8258
8259 switch (SrcI->getOpcode()) {
8260 case Instruction::Add:
8261 case Instruction::Mul:
8262 case Instruction::And:
8263 case Instruction::Or:
8264 case Instruction::Xor:
8265 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008266 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8267 // Don't insert two casts unless at least one can be eliminated.
8268 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008269 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008270 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8271 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008272 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008273 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8274 }
8275 }
8276
8277 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8278 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8279 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008280 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008282 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008283 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008284 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008285 }
8286 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008287
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008288 case Instruction::Shl: {
8289 // Canonicalize trunc inside shl, if we can.
8290 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8291 if (CI && DestBitSize < SrcBitSize &&
8292 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008293 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8294 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008295 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296 }
8297 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008298 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008299 }
8300 return 0;
8301}
8302
8303Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8304 if (Instruction *Result = commonIntCastTransforms(CI))
8305 return Result;
8306
8307 Value *Src = CI.getOperand(0);
8308 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008309 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8310 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008311
8312 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008313 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008314 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008315 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008316 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008317 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008318 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008319
Chris Lattner32177f82009-03-24 18:15:30 +00008320 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8321 ConstantInt *ShAmtV = 0;
8322 Value *ShiftOp = 0;
8323 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008324 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008325 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8326
8327 // Get a mask for the bits shifting in.
8328 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8329 if (MaskedValueIsZero(ShiftOp, Mask)) {
8330 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008331 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008332
8333 // Okay, we can shrink this. Truncate the input, then return a new
8334 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008335 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008336 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008337 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008338 }
8339 }
8340
8341 return 0;
8342}
8343
Evan Chenge3779cf2008-03-24 00:21:34 +00008344/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8345/// in order to eliminate the icmp.
8346Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8347 bool DoXform) {
8348 // If we are just checking for a icmp eq of a single bit and zext'ing it
8349 // to an integer, then shift the bit to the appropriate place and then
8350 // cast to integer to avoid the comparison.
8351 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8352 const APInt &Op1CV = Op1C->getValue();
8353
8354 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8355 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8356 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8357 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8358 if (!DoXform) return ICI;
8359
8360 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008361 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008362 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008363 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008364 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008365 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008366
8367 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008368 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008369 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008370 }
8371
8372 return ReplaceInstUsesWith(CI, In);
8373 }
8374
8375
8376
8377 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8378 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8379 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8380 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8381 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8382 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8383 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8384 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8385 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8386 // This only works for EQ and NE
8387 ICI->isEquality()) {
8388 // If Op1C some other power of two, convert:
8389 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8390 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8391 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8392 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8393
8394 APInt KnownZeroMask(~KnownZero);
8395 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8396 if (!DoXform) return ICI;
8397
8398 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8399 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8400 // (X&4) == 2 --> false
8401 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008402 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008403 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008404 return ReplaceInstUsesWith(CI, Res);
8405 }
8406
8407 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8408 Value *In = ICI->getOperand(0);
8409 if (ShiftAmt) {
8410 // Perform a logical shr by shiftamt.
8411 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008412 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8413 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008414 }
8415
8416 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008417 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008418 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008419 }
8420
8421 if (CI.getType() == In->getType())
8422 return ReplaceInstUsesWith(CI, In);
8423 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008424 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008425 }
8426 }
8427 }
8428
8429 return 0;
8430}
8431
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008432Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8433 // If one of the common conversion will work ..
8434 if (Instruction *Result = commonIntCastTransforms(CI))
8435 return Result;
8436
8437 Value *Src = CI.getOperand(0);
8438
Chris Lattner215d56e2009-02-17 20:47:23 +00008439 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8440 // types and if the sizes are just right we can convert this into a logical
8441 // 'and' which will be much cheaper than the pair of casts.
8442 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8443 // Get the sizes of the types involved. We know that the intermediate type
8444 // will be smaller than A or C, but don't know the relation between A and C.
8445 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008446 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8447 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8448 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008449 // If we're actually extending zero bits, then if
8450 // SrcSize < DstSize: zext(a & mask)
8451 // SrcSize == DstSize: a & mask
8452 // SrcSize > DstSize: trunc(a) & mask
8453 if (SrcSize < DstSize) {
8454 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008455 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008456 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008457 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008458 }
8459
8460 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008461 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008462 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008463 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008464 }
8465 if (SrcSize > DstSize) {
8466 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008467 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008468 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008469 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008470 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008471 }
8472 }
8473
Evan Chenge3779cf2008-03-24 00:21:34 +00008474 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8475 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008476
Evan Chenge3779cf2008-03-24 00:21:34 +00008477 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8478 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8479 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8480 // of the (zext icmp) will be transformed.
8481 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8482 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8483 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8484 (transformZExtICmp(LHS, CI, false) ||
8485 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008486 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8487 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008488 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008489 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008490 }
8491
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008492 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008493 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8494 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8495 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8496 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008497 if (TI0->getType() == CI.getType())
8498 return
8499 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008500 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008501 }
8502
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008503 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8504 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8505 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8506 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8507 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8508 And->getOperand(1) == C)
8509 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8510 Value *TI0 = TI->getOperand(0);
8511 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008512 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008513 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008514 return BinaryOperator::CreateXor(NewAnd, ZC);
8515 }
8516 }
8517
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008518 return 0;
8519}
8520
8521Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8522 if (Instruction *I = commonIntCastTransforms(CI))
8523 return I;
8524
8525 Value *Src = CI.getOperand(0);
8526
Dan Gohman35b76162008-10-30 20:40:10 +00008527 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008528 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008529 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008530 Constant::getAllOnesValue(CI.getType()),
8531 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008532
8533 // See if the value being truncated is already sign extended. If so, just
8534 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008535 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008536 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008537 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8538 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8539 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008540 unsigned NumSignBits = ComputeNumSignBits(Op);
8541
8542 if (OpBits == DestBits) {
8543 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8544 // bits, it is already ready.
8545 if (NumSignBits > DestBits-MidBits)
8546 return ReplaceInstUsesWith(CI, Op);
8547 } else if (OpBits < DestBits) {
8548 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8549 // bits, just sext from i32.
8550 if (NumSignBits > OpBits-MidBits)
8551 return new SExtInst(Op, CI.getType(), "tmp");
8552 } else {
8553 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8554 // bits, just truncate to i32.
8555 if (NumSignBits > OpBits-MidBits)
8556 return new TruncInst(Op, CI.getType(), "tmp");
8557 }
8558 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008559
8560 // If the input is a shl/ashr pair of a same constant, then this is a sign
8561 // extension from a smaller value. If we could trust arbitrary bitwidth
8562 // integers, we could turn this into a truncate to the smaller bit and then
8563 // use a sext for the whole extension. Since we don't, look deeper and check
8564 // for a truncate. If the source and dest are the same type, eliminate the
8565 // trunc and extend and just do shifts. For example, turn:
8566 // %a = trunc i32 %i to i8
8567 // %b = shl i8 %a, 6
8568 // %c = ashr i8 %b, 6
8569 // %d = sext i8 %c to i32
8570 // into:
8571 // %a = shl i32 %i, 30
8572 // %d = ashr i32 %a, 30
8573 Value *A = 0;
8574 ConstantInt *BA = 0, *CA = 0;
8575 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008576 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008577 BA == CA && isa<TruncInst>(A)) {
8578 Value *I = cast<TruncInst>(A)->getOperand(0);
8579 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008580 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8581 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008582 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008583 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008584 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008585 return BinaryOperator::CreateAShr(I, ShAmtV);
8586 }
8587 }
8588
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008589 return 0;
8590}
8591
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008592/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8593/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008594static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008595 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008596 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008597 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008598 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8599 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008600 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008601 return 0;
8602}
8603
8604/// LookThroughFPExtensions - If this is an fp extension instruction, look
8605/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008606static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008607 if (Instruction *I = dyn_cast<Instruction>(V))
8608 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008609 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008610
8611 // If this value is a constant, return the constant in the smallest FP type
8612 // that can accurately represent it. This allows us to turn
8613 // (float)((double)X+2.0) into x+2.0f.
8614 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008615 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008616 return V; // No constant folding of this.
8617 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008618 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008619 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008620 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008621 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008622 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008623 return V;
8624 // Don't try to shrink to various long double types.
8625 }
8626
8627 return V;
8628}
8629
8630Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8631 if (Instruction *I = commonCastTransforms(CI))
8632 return I;
8633
Dan Gohman7ce405e2009-06-04 22:49:04 +00008634 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008635 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008636 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008637 // many builtins (sqrt, etc).
8638 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8639 if (OpI && OpI->hasOneUse()) {
8640 switch (OpI->getOpcode()) {
8641 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008642 case Instruction::FAdd:
8643 case Instruction::FSub:
8644 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008645 case Instruction::FDiv:
8646 case Instruction::FRem:
8647 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008648 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8649 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008650 if (LHSTrunc->getType() != SrcTy &&
8651 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008652 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008653 // If the source types were both smaller than the destination type of
8654 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008655 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8656 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008657 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8658 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008659 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008660 }
8661 }
8662 break;
8663 }
8664 }
8665 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008666}
8667
8668Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8669 return commonCastTransforms(CI);
8670}
8671
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008672Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008673 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8674 if (OpI == 0)
8675 return commonCastTransforms(FI);
8676
8677 // fptoui(uitofp(X)) --> X
8678 // fptoui(sitofp(X)) --> X
8679 // This is safe if the intermediate type has enough bits in its mantissa to
8680 // accurately represent all values of X. For example, do not do this with
8681 // i64->float->i64. This is also safe for sitofp case, because any negative
8682 // 'X' value would cause an undefined result for the fptoui.
8683 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8684 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008685 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008686 OpI->getType()->getFPMantissaWidth())
8687 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008688
8689 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008690}
8691
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008692Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008693 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8694 if (OpI == 0)
8695 return commonCastTransforms(FI);
8696
8697 // fptosi(sitofp(X)) --> X
8698 // fptosi(uitofp(X)) --> X
8699 // This is safe if the intermediate type has enough bits in its mantissa to
8700 // accurately represent all values of X. For example, do not do this with
8701 // i64->float->i64. This is also safe for sitofp case, because any negative
8702 // 'X' value would cause an undefined result for the fptoui.
8703 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8704 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008705 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008706 OpI->getType()->getFPMantissaWidth())
8707 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008708
8709 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008710}
8711
8712Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8713 return commonCastTransforms(CI);
8714}
8715
8716Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8717 return commonCastTransforms(CI);
8718}
8719
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008720Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8721 // If the destination integer type is smaller than the intptr_t type for
8722 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8723 // trunc to be exposed to other transforms. Don't do this for extending
8724 // ptrtoint's, because we don't know if the target sign or zero extends its
8725 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008726 if (TD &&
8727 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008728 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8729 TD->getIntPtrType(CI.getContext()),
8730 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008731 return new TruncInst(P, CI.getType());
8732 }
8733
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008734 return commonPointerCastTransforms(CI);
8735}
8736
Chris Lattner7c1626482008-01-08 07:23:51 +00008737Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008738 // If the source integer type is larger than the intptr_t type for
8739 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8740 // allows the trunc to be exposed to other transforms. Don't do this for
8741 // extending inttoptr's, because we don't know if the target sign or zero
8742 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008743 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008744 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008745 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8746 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008747 return new IntToPtrInst(P, CI.getType());
8748 }
8749
Chris Lattner7c1626482008-01-08 07:23:51 +00008750 if (Instruction *I = commonCastTransforms(CI))
8751 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008752
Chris Lattner7c1626482008-01-08 07:23:51 +00008753 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008754}
8755
8756Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8757 // If the operands are integer typed then apply the integer transforms,
8758 // otherwise just apply the common ones.
8759 Value *Src = CI.getOperand(0);
8760 const Type *SrcTy = Src->getType();
8761 const Type *DestTy = CI.getType();
8762
Eli Friedman5013d3f2009-07-13 20:53:00 +00008763 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008764 if (Instruction *I = commonPointerCastTransforms(CI))
8765 return I;
8766 } else {
8767 if (Instruction *Result = commonCastTransforms(CI))
8768 return Result;
8769 }
8770
8771
8772 // Get rid of casts from one type to the same type. These are useless and can
8773 // be replaced by the operand.
8774 if (DestTy == Src->getType())
8775 return ReplaceInstUsesWith(CI, Src);
8776
8777 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8778 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8779 const Type *DstElTy = DstPTy->getElementType();
8780 const Type *SrcElTy = SrcPTy->getElementType();
8781
Nate Begemandf5b3612008-03-31 00:22:16 +00008782 // If the address spaces don't match, don't eliminate the bitcast, which is
8783 // required for changing types.
8784 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8785 return 0;
8786
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008787 // If we are casting a malloc or alloca to a pointer to a type of the same
8788 // size, rewrite the allocation instruction to allocate the "right" type.
8789 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8790 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8791 return V;
8792
8793 // If the source and destination are pointers, and this cast is equivalent
8794 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8795 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008796 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008797 unsigned NumZeros = 0;
8798 while (SrcElTy != DstElTy &&
8799 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8800 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8801 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8802 ++NumZeros;
8803 }
8804
8805 // If we found a path from the src to dest, create the getelementptr now.
8806 if (SrcElTy == DstElTy) {
8807 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008808 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8809 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008810 }
8811 }
8812
Eli Friedman1d31dee2009-07-18 23:06:53 +00008813 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8814 if (DestVTy->getNumElements() == 1) {
8815 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008816 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008817 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00008818 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008819 }
8820 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8821 }
8822 }
8823
8824 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8825 if (SrcVTy->getNumElements() == 1) {
8826 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008827 Value *Elem =
8828 Builder->CreateExtractElement(Src,
8829 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008830 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8831 }
8832 }
8833 }
8834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008835 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8836 if (SVI->hasOneUse()) {
8837 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8838 // a bitconvert to a vector with the same # elts.
8839 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008840 cast<VectorType>(DestTy)->getNumElements() ==
8841 SVI->getType()->getNumElements() &&
8842 SVI->getType()->getNumElements() ==
8843 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008844 CastInst *Tmp;
8845 // If either of the operands is a cast from CI.getType(), then
8846 // evaluating the shuffle in the casted destination's type will allow
8847 // us to eliminate at least one cast.
8848 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8849 Tmp->getOperand(0)->getType() == DestTy) ||
8850 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8851 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008852 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8853 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008854 // Return a new shuffle vector. Use the same element ID's, as we
8855 // know the vector types match #elts.
8856 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8857 }
8858 }
8859 }
8860 }
8861 return 0;
8862}
8863
8864/// GetSelectFoldableOperands - We want to turn code that looks like this:
8865/// %C = or %A, %B
8866/// %D = select %cond, %C, %A
8867/// into:
8868/// %C = select %cond, %B, 0
8869/// %D = or %A, %C
8870///
8871/// Assuming that the specified instruction is an operand to the select, return
8872/// a bitmask indicating which operands of this instruction are foldable if they
8873/// equal the other incoming value of the select.
8874///
8875static unsigned GetSelectFoldableOperands(Instruction *I) {
8876 switch (I->getOpcode()) {
8877 case Instruction::Add:
8878 case Instruction::Mul:
8879 case Instruction::And:
8880 case Instruction::Or:
8881 case Instruction::Xor:
8882 return 3; // Can fold through either operand.
8883 case Instruction::Sub: // Can only fold on the amount subtracted.
8884 case Instruction::Shl: // Can only fold on the shift amount.
8885 case Instruction::LShr:
8886 case Instruction::AShr:
8887 return 1;
8888 default:
8889 return 0; // Cannot fold
8890 }
8891}
8892
8893/// GetSelectFoldableConstant - For the same transformation as the previous
8894/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00008895static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00008896 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008897 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008898 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008899 case Instruction::Add:
8900 case Instruction::Sub:
8901 case Instruction::Or:
8902 case Instruction::Xor:
8903 case Instruction::Shl:
8904 case Instruction::LShr:
8905 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00008906 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008907 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00008908 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008909 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00008910 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008911 }
8912}
8913
8914/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8915/// have the same opcode and only one use each. Try to simplify this.
8916Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8917 Instruction *FI) {
8918 if (TI->getNumOperands() == 1) {
8919 // If this is a non-volatile load or a cast from the same type,
8920 // merge.
8921 if (TI->isCast()) {
8922 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8923 return 0;
8924 } else {
8925 return 0; // unknown unary op.
8926 }
8927
8928 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008929 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00008930 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008931 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008932 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008933 TI->getType());
8934 }
8935
8936 // Only handle binary operators here.
8937 if (!isa<BinaryOperator>(TI))
8938 return 0;
8939
8940 // Figure out if the operations have any operands in common.
8941 Value *MatchOp, *OtherOpT, *OtherOpF;
8942 bool MatchIsOpZero;
8943 if (TI->getOperand(0) == FI->getOperand(0)) {
8944 MatchOp = TI->getOperand(0);
8945 OtherOpT = TI->getOperand(1);
8946 OtherOpF = FI->getOperand(1);
8947 MatchIsOpZero = true;
8948 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8949 MatchOp = TI->getOperand(1);
8950 OtherOpT = TI->getOperand(0);
8951 OtherOpF = FI->getOperand(0);
8952 MatchIsOpZero = false;
8953 } else if (!TI->isCommutative()) {
8954 return 0;
8955 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8956 MatchOp = TI->getOperand(0);
8957 OtherOpT = TI->getOperand(1);
8958 OtherOpF = FI->getOperand(0);
8959 MatchIsOpZero = true;
8960 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8961 MatchOp = TI->getOperand(1);
8962 OtherOpT = TI->getOperand(0);
8963 OtherOpF = FI->getOperand(1);
8964 MatchIsOpZero = true;
8965 } else {
8966 return 0;
8967 }
8968
8969 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008970 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8971 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008972 InsertNewInstBefore(NewSI, SI);
8973
8974 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8975 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008976 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008977 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008978 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008979 }
Edwin Törökbd448e32009-07-14 16:55:14 +00008980 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008981 return 0;
8982}
8983
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00008984static bool isSelect01(Constant *C1, Constant *C2) {
8985 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8986 if (!C1I)
8987 return false;
8988 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8989 if (!C2I)
8990 return false;
8991 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8992}
8993
8994/// FoldSelectIntoOp - Try fold the select into one of the operands to
8995/// facilitate further optimization.
8996Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8997 Value *FalseVal) {
8998 // See the comment above GetSelectFoldableOperands for a description of the
8999 // transformation we are doing here.
9000 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9001 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9002 !isa<Constant>(FalseVal)) {
9003 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9004 unsigned OpToFold = 0;
9005 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9006 OpToFold = 1;
9007 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9008 OpToFold = 2;
9009 }
9010
9011 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009012 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009013 Value *OOp = TVI->getOperand(2-OpToFold);
9014 // Avoid creating select between 2 constants unless it's selecting
9015 // between 0 and 1.
9016 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9017 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9018 InsertNewInstBefore(NewSel, SI);
9019 NewSel->takeName(TVI);
9020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9021 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009022 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009023 }
9024 }
9025 }
9026 }
9027 }
9028
9029 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9030 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9031 !isa<Constant>(TrueVal)) {
9032 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9033 unsigned OpToFold = 0;
9034 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9035 OpToFold = 1;
9036 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9037 OpToFold = 2;
9038 }
9039
9040 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009041 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009042 Value *OOp = FVI->getOperand(2-OpToFold);
9043 // Avoid creating select between 2 constants unless it's selecting
9044 // between 0 and 1.
9045 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9046 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9047 InsertNewInstBefore(NewSel, SI);
9048 NewSel->takeName(FVI);
9049 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9050 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009051 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009052 }
9053 }
9054 }
9055 }
9056 }
9057
9058 return 0;
9059}
9060
Dan Gohman58c09632008-09-16 18:46:06 +00009061/// visitSelectInstWithICmp - Visit a SelectInst that has an
9062/// ICmpInst as its first operand.
9063///
9064Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9065 ICmpInst *ICI) {
9066 bool Changed = false;
9067 ICmpInst::Predicate Pred = ICI->getPredicate();
9068 Value *CmpLHS = ICI->getOperand(0);
9069 Value *CmpRHS = ICI->getOperand(1);
9070 Value *TrueVal = SI.getTrueValue();
9071 Value *FalseVal = SI.getFalseValue();
9072
9073 // Check cases where the comparison is with a constant that
9074 // can be adjusted to fit the min/max idiom. We may edit ICI in
9075 // place here, so make sure the select is the only user.
9076 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009077 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009078 switch (Pred) {
9079 default: break;
9080 case ICmpInst::ICMP_ULT:
9081 case ICmpInst::ICMP_SLT: {
9082 // X < MIN ? T : F --> F
9083 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9084 return ReplaceInstUsesWith(SI, FalseVal);
9085 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009086 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009087 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9088 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9089 Pred = ICmpInst::getSwappedPredicate(Pred);
9090 CmpRHS = AdjustedRHS;
9091 std::swap(FalseVal, TrueVal);
9092 ICI->setPredicate(Pred);
9093 ICI->setOperand(1, CmpRHS);
9094 SI.setOperand(1, TrueVal);
9095 SI.setOperand(2, FalseVal);
9096 Changed = true;
9097 }
9098 break;
9099 }
9100 case ICmpInst::ICMP_UGT:
9101 case ICmpInst::ICMP_SGT: {
9102 // X > MAX ? T : F --> F
9103 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9104 return ReplaceInstUsesWith(SI, FalseVal);
9105 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009106 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009107 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9108 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9109 Pred = ICmpInst::getSwappedPredicate(Pred);
9110 CmpRHS = AdjustedRHS;
9111 std::swap(FalseVal, TrueVal);
9112 ICI->setPredicate(Pred);
9113 ICI->setOperand(1, CmpRHS);
9114 SI.setOperand(1, TrueVal);
9115 SI.setOperand(2, FalseVal);
9116 Changed = true;
9117 }
9118 break;
9119 }
9120 }
9121
Dan Gohman35b76162008-10-30 20:40:10 +00009122 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9123 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009124 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009125 if (match(TrueVal, m_ConstantInt<-1>()) &&
9126 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009127 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009128 else if (match(TrueVal, m_ConstantInt<0>()) &&
9129 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009130 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9131
Dan Gohman35b76162008-10-30 20:40:10 +00009132 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9133 // If we are just checking for a icmp eq of a single bit and zext'ing it
9134 // to an integer, then shift the bit to the appropriate place and then
9135 // cast to integer to avoid the comparison.
9136 const APInt &Op1CV = CI->getValue();
9137
9138 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9139 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9140 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009141 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009142 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009143 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009144 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009145 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009146 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009147 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009148 if (In->getType() != SI.getType())
9149 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009150 true/*SExt*/, "tmp", ICI);
9151
9152 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009153 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009154 In->getName()+".not"), *ICI);
9155
9156 return ReplaceInstUsesWith(SI, In);
9157 }
9158 }
9159 }
9160
Dan Gohman58c09632008-09-16 18:46:06 +00009161 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9162 // Transform (X == Y) ? X : Y -> Y
9163 if (Pred == ICmpInst::ICMP_EQ)
9164 return ReplaceInstUsesWith(SI, FalseVal);
9165 // Transform (X != Y) ? X : Y -> X
9166 if (Pred == ICmpInst::ICMP_NE)
9167 return ReplaceInstUsesWith(SI, TrueVal);
9168 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9169
9170 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9171 // Transform (X == Y) ? Y : X -> X
9172 if (Pred == ICmpInst::ICMP_EQ)
9173 return ReplaceInstUsesWith(SI, FalseVal);
9174 // Transform (X != Y) ? Y : X -> Y
9175 if (Pred == ICmpInst::ICMP_NE)
9176 return ReplaceInstUsesWith(SI, TrueVal);
9177 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9178 }
9179
9180 /// NOTE: if we wanted to, this is where to detect integer ABS
9181
9182 return Changed ? &SI : 0;
9183}
9184
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009185Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9186 Value *CondVal = SI.getCondition();
9187 Value *TrueVal = SI.getTrueValue();
9188 Value *FalseVal = SI.getFalseValue();
9189
9190 // select true, X, Y -> X
9191 // select false, X, Y -> Y
9192 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9193 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9194
9195 // select C, X, X -> X
9196 if (TrueVal == FalseVal)
9197 return ReplaceInstUsesWith(SI, TrueVal);
9198
9199 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9200 return ReplaceInstUsesWith(SI, FalseVal);
9201 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9202 return ReplaceInstUsesWith(SI, TrueVal);
9203 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9204 if (isa<Constant>(TrueVal))
9205 return ReplaceInstUsesWith(SI, TrueVal);
9206 else
9207 return ReplaceInstUsesWith(SI, FalseVal);
9208 }
9209
Owen Anderson35b47072009-08-13 21:58:54 +00009210 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009211 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9212 if (C->getZExtValue()) {
9213 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009214 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009215 } else {
9216 // Change: A = select B, false, C --> A = and !B, C
9217 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009218 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009219 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009220 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009221 }
9222 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9223 if (C->getZExtValue() == false) {
9224 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009225 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009226 } else {
9227 // Change: A = select B, C, true --> A = or !B, C
9228 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009229 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009230 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009231 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009232 }
9233 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009234
9235 // select a, b, a -> a&b
9236 // select a, a, b -> a|b
9237 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009238 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009239 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009240 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009241 }
9242
9243 // Selecting between two integer constants?
9244 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9245 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9246 // select C, 1, 0 -> zext C to int
9247 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009248 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009249 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9250 // select C, 0, 1 -> zext !C to int
9251 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009252 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009253 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009254 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009255 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009256
9257 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009258 // If one of the constants is zero (we know they can't both be) and we
9259 // have an icmp instruction with zero, and we have an 'and' with the
9260 // non-constant value, eliminate this whole mess. This corresponds to
9261 // cases like this: ((X & 27) ? 27 : 0)
9262 if (TrueValC->isZero() || FalseValC->isZero())
9263 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9264 cast<Constant>(IC->getOperand(1))->isNullValue())
9265 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9266 if (ICA->getOpcode() == Instruction::And &&
9267 isa<ConstantInt>(ICA->getOperand(1)) &&
9268 (ICA->getOperand(1) == TrueValC ||
9269 ICA->getOperand(1) == FalseValC) &&
9270 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9271 // Okay, now we know that everything is set up, we just don't
9272 // know whether we have a icmp_ne or icmp_eq and whether the
9273 // true or false val is the zero.
9274 bool ShouldNotVal = !TrueValC->isZero();
9275 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9276 Value *V = ICA;
9277 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009278 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009279 Instruction::Xor, V, ICA->getOperand(1)), SI);
9280 return ReplaceInstUsesWith(SI, V);
9281 }
9282 }
9283 }
9284
9285 // See if we are selecting two values based on a comparison of the two values.
9286 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9287 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9288 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009289 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9290 // This is not safe in general for floating point:
9291 // consider X== -0, Y== +0.
9292 // It becomes safe if either operand is a nonzero constant.
9293 ConstantFP *CFPt, *CFPf;
9294 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9295 !CFPt->getValueAPF().isZero()) ||
9296 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9297 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009298 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009299 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009300 // Transform (X != Y) ? X : Y -> X
9301 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9302 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009303 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009304
9305 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9306 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009307 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9308 // This is not safe in general for floating point:
9309 // consider X== -0, Y== +0.
9310 // It becomes safe if either operand is a nonzero constant.
9311 ConstantFP *CFPt, *CFPf;
9312 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9313 !CFPt->getValueAPF().isZero()) ||
9314 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9315 !CFPf->getValueAPF().isZero()))
9316 return ReplaceInstUsesWith(SI, FalseVal);
9317 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009318 // Transform (X != Y) ? Y : X -> Y
9319 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9320 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009321 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009322 }
Dan Gohman58c09632008-09-16 18:46:06 +00009323 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009324 }
9325
9326 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009327 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9328 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9329 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009330
9331 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9332 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9333 if (TI->hasOneUse() && FI->hasOneUse()) {
9334 Instruction *AddOp = 0, *SubOp = 0;
9335
9336 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9337 if (TI->getOpcode() == FI->getOpcode())
9338 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9339 return IV;
9340
9341 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9342 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009343 if ((TI->getOpcode() == Instruction::Sub &&
9344 FI->getOpcode() == Instruction::Add) ||
9345 (TI->getOpcode() == Instruction::FSub &&
9346 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009347 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009348 } else if ((FI->getOpcode() == Instruction::Sub &&
9349 TI->getOpcode() == Instruction::Add) ||
9350 (FI->getOpcode() == Instruction::FSub &&
9351 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009352 AddOp = TI; SubOp = FI;
9353 }
9354
9355 if (AddOp) {
9356 Value *OtherAddOp = 0;
9357 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9358 OtherAddOp = AddOp->getOperand(1);
9359 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9360 OtherAddOp = AddOp->getOperand(0);
9361 }
9362
9363 if (OtherAddOp) {
9364 // So at this point we know we have (Y -> OtherAddOp):
9365 // select C, (add X, Y), (sub X, Z)
9366 Value *NegVal; // Compute -Z
9367 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009368 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009369 } else {
9370 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009371 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009372 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009373 }
9374
9375 Value *NewTrueOp = OtherAddOp;
9376 Value *NewFalseOp = NegVal;
9377 if (AddOp != TI)
9378 std::swap(NewTrueOp, NewFalseOp);
9379 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009380 SelectInst::Create(CondVal, NewTrueOp,
9381 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009382
9383 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009384 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009385 }
9386 }
9387 }
9388
9389 // See if we can fold the select into one of our operands.
9390 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009391 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9392 if (FoldI)
9393 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009394 }
9395
9396 if (BinaryOperator::isNot(CondVal)) {
9397 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9398 SI.setOperand(1, FalseVal);
9399 SI.setOperand(2, TrueVal);
9400 return &SI;
9401 }
9402
9403 return 0;
9404}
9405
Dan Gohman2d648bb2008-04-10 18:43:06 +00009406/// EnforceKnownAlignment - If the specified pointer points to an object that
9407/// we control, modify the object's alignment to PrefAlign. This isn't
9408/// often possible though. If alignment is important, a more reliable approach
9409/// is to simply align all global variables and allocation instructions to
9410/// their preferred alignment from the beginning.
9411///
9412static unsigned EnforceKnownAlignment(Value *V,
9413 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009414
Dan Gohman2d648bb2008-04-10 18:43:06 +00009415 User *U = dyn_cast<User>(V);
9416 if (!U) return Align;
9417
Dan Gohman9545fb02009-07-17 20:47:02 +00009418 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009419 default: break;
9420 case Instruction::BitCast:
9421 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9422 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009423 // If all indexes are zero, it is just the alignment of the base pointer.
9424 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009425 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009426 if (!isa<Constant>(*i) ||
9427 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009428 AllZeroOperands = false;
9429 break;
9430 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009431
9432 if (AllZeroOperands) {
9433 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009434 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009435 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009436 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009437 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009438 }
9439
9440 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9441 // If there is a large requested alignment and we can, bump up the alignment
9442 // of the global.
9443 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009444 if (GV->getAlignment() >= PrefAlign)
9445 Align = GV->getAlignment();
9446 else {
9447 GV->setAlignment(PrefAlign);
9448 Align = PrefAlign;
9449 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009450 }
9451 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9452 // If there is a requested alignment and if this is an alloca, round up. We
9453 // don't do this for malloc, because some systems can't respect the request.
9454 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009455 if (AI->getAlignment() >= PrefAlign)
9456 Align = AI->getAlignment();
9457 else {
9458 AI->setAlignment(PrefAlign);
9459 Align = PrefAlign;
9460 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009461 }
9462 }
9463
9464 return Align;
9465}
9466
9467/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9468/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9469/// and it is more than the alignment of the ultimate object, see if we can
9470/// increase the alignment of the ultimate object, making this check succeed.
9471unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9472 unsigned PrefAlign) {
9473 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9474 sizeof(PrefAlign) * CHAR_BIT;
9475 APInt Mask = APInt::getAllOnesValue(BitWidth);
9476 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9477 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9478 unsigned TrailZ = KnownZero.countTrailingOnes();
9479 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9480
9481 if (PrefAlign > Align)
9482 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9483
9484 // We don't need to make any adjustment.
9485 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009486}
9487
Chris Lattner00ae5132008-01-13 23:50:23 +00009488Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009489 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009490 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009491 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009492 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009493
9494 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009495 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009496 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009497 return MI;
9498 }
9499
9500 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9501 // load/store.
9502 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9503 if (MemOpLength == 0) return 0;
9504
Chris Lattnerc669fb62008-01-14 00:28:35 +00009505 // Source and destination pointer types are always "i8*" for intrinsic. See
9506 // if the size is something we can handle with a single primitive load/store.
9507 // A single load+store correctly handles overlapping memory in the memmove
9508 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009509 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009510 if (Size == 0) return MI; // Delete this mem transfer.
9511
9512 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009513 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009514
Chris Lattnerc669fb62008-01-14 00:28:35 +00009515 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009516 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009517 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009518
9519 // Memcpy forces the use of i8* for the source and destination. That means
9520 // that if you're using memcpy to move one double around, you'll get a cast
9521 // from double* to i8*. We'd much rather use a double load+store rather than
9522 // an i64 load+store, here because this improves the odds that the source or
9523 // dest address will be promotable. See if we can find a better type than the
9524 // integer datatype.
9525 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9526 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009527 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009528 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9529 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009530 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009531 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9532 if (STy->getNumElements() == 1)
9533 SrcETy = STy->getElementType(0);
9534 else
9535 break;
9536 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9537 if (ATy->getNumElements() == 1)
9538 SrcETy = ATy->getElementType();
9539 else
9540 break;
9541 } else
9542 break;
9543 }
9544
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009545 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009546 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009547 }
9548 }
9549
9550
Chris Lattner00ae5132008-01-13 23:50:23 +00009551 // If the memcpy/memmove provides better alignment info than we can
9552 // infer, use it.
9553 SrcAlign = std::max(SrcAlign, CopyAlign);
9554 DstAlign = std::max(DstAlign, CopyAlign);
9555
Chris Lattner78628292009-08-30 19:47:22 +00009556 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9557 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009558 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9559 InsertNewInstBefore(L, *MI);
9560 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9561
9562 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009563 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009564 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009565}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009566
Chris Lattner5af8a912008-04-30 06:39:11 +00009567Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9568 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009569 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009570 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009571 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009572 return MI;
9573 }
9574
9575 // Extract the length and alignment and fill if they are constant.
9576 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9577 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009578 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009579 return 0;
9580 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009581 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009582
9583 // If the length is zero, this is a no-op
9584 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9585
9586 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9587 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009588 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009589
9590 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009591 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009592
9593 // Alignment 0 is identity for alignment 1 for memset, but not store.
9594 if (Alignment == 0) Alignment = 1;
9595
9596 // Extract the fill value and store.
9597 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009598 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009599 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009600
9601 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009602 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009603 return MI;
9604 }
9605
9606 return 0;
9607}
9608
9609
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009610/// visitCallInst - CallInst simplification. This mostly only handles folding
9611/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9612/// the heavy lifting.
9613///
9614Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009615 // If the caller function is nounwind, mark the call as nounwind, even if the
9616 // callee isn't.
9617 if (CI.getParent()->getParent()->doesNotThrow() &&
9618 !CI.doesNotThrow()) {
9619 CI.setDoesNotThrow();
9620 return &CI;
9621 }
9622
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009623 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9624 if (!II) return visitCallSite(&CI);
9625
9626 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9627 // visitCallSite.
9628 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9629 bool Changed = false;
9630
9631 // memmove/cpy/set of zero bytes is a noop.
9632 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9633 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9634
9635 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9636 if (CI->getZExtValue() == 1) {
9637 // Replace the instruction with just byte operations. We would
9638 // transform other cases to loads/stores, but we don't know if
9639 // alignment is sufficient.
9640 }
9641 }
9642
9643 // If we have a memmove and the source operation is a constant global,
9644 // then the source and dest pointers can't alias, so we can change this
9645 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009646 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009647 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9648 if (GVSrc->isConstant()) {
9649 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009650 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9651 const Type *Tys[1];
9652 Tys[0] = CI.getOperand(3)->getType();
9653 CI.setOperand(0,
9654 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009655 Changed = true;
9656 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009657
9658 // memmove(x,x,size) -> noop.
9659 if (MMI->getSource() == MMI->getDest())
9660 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009661 }
9662
9663 // If we can determine a pointer alignment that is bigger than currently
9664 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009665 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009666 if (Instruction *I = SimplifyMemTransfer(MI))
9667 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009668 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9669 if (Instruction *I = SimplifyMemSet(MSI))
9670 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009671 }
9672
9673 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009674 }
9675
9676 switch (II->getIntrinsicID()) {
9677 default: break;
9678 case Intrinsic::bswap:
9679 // bswap(bswap(x)) -> x
9680 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9681 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9682 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9683 break;
9684 case Intrinsic::ppc_altivec_lvx:
9685 case Intrinsic::ppc_altivec_lvxl:
9686 case Intrinsic::x86_sse_loadu_ps:
9687 case Intrinsic::x86_sse2_loadu_pd:
9688 case Intrinsic::x86_sse2_loadu_dq:
9689 // Turn PPC lvx -> load if the pointer is known aligned.
9690 // Turn X86 loadups -> load if the pointer is known aligned.
9691 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009692 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9693 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009694 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009695 }
Chris Lattner989ba312008-06-18 04:33:20 +00009696 break;
9697 case Intrinsic::ppc_altivec_stvx:
9698 case Intrinsic::ppc_altivec_stvxl:
9699 // Turn stvx -> store if the pointer is known aligned.
9700 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9701 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009702 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009703 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009704 return new StoreInst(II->getOperand(1), Ptr);
9705 }
9706 break;
9707 case Intrinsic::x86_sse_storeu_ps:
9708 case Intrinsic::x86_sse2_storeu_pd:
9709 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009710 // Turn X86 storeu -> store if the pointer is known aligned.
9711 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9712 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009713 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009714 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009715 return new StoreInst(II->getOperand(2), Ptr);
9716 }
9717 break;
9718
9719 case Intrinsic::x86_sse_cvttss2si: {
9720 // These intrinsics only demands the 0th element of its input vector. If
9721 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009722 unsigned VWidth =
9723 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9724 APInt DemandedElts(VWidth, 1);
9725 APInt UndefElts(VWidth, 0);
9726 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009727 UndefElts)) {
9728 II->setOperand(1, V);
9729 return II;
9730 }
9731 break;
9732 }
9733
9734 case Intrinsic::ppc_altivec_vperm:
9735 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9736 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9737 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009738
Chris Lattner989ba312008-06-18 04:33:20 +00009739 // Check that all of the elements are integer constants or undefs.
9740 bool AllEltsOk = true;
9741 for (unsigned i = 0; i != 16; ++i) {
9742 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9743 !isa<UndefValue>(Mask->getOperand(i))) {
9744 AllEltsOk = false;
9745 break;
9746 }
9747 }
9748
9749 if (AllEltsOk) {
9750 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00009751 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9752 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009753 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009754
Chris Lattner989ba312008-06-18 04:33:20 +00009755 // Only extract each element once.
9756 Value *ExtractedElts[32];
9757 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9758
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009759 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009760 if (isa<UndefValue>(Mask->getOperand(i)))
9761 continue;
9762 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9763 Idx &= 31; // Match the hardware behavior.
9764
9765 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009766 ExtractedElts[Idx] =
9767 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9768 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9769 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009771
Chris Lattner989ba312008-06-18 04:33:20 +00009772 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009773 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9774 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9775 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009776 }
Chris Lattner989ba312008-06-18 04:33:20 +00009777 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009778 }
Chris Lattner989ba312008-06-18 04:33:20 +00009779 }
9780 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009781
Chris Lattner989ba312008-06-18 04:33:20 +00009782 case Intrinsic::stackrestore: {
9783 // If the save is right next to the restore, remove the restore. This can
9784 // happen when variable allocas are DCE'd.
9785 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9786 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9787 BasicBlock::iterator BI = SS;
9788 if (&*++BI == II)
9789 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009790 }
Chris Lattner989ba312008-06-18 04:33:20 +00009791 }
9792
9793 // Scan down this block to see if there is another stack restore in the
9794 // same block without an intervening call/alloca.
9795 BasicBlock::iterator BI = II;
9796 TerminatorInst *TI = II->getParent()->getTerminator();
9797 bool CannotRemove = false;
9798 for (++BI; &*BI != TI; ++BI) {
9799 if (isa<AllocaInst>(BI)) {
9800 CannotRemove = true;
9801 break;
9802 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009803 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9804 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9805 // If there is a stackrestore below this one, remove this one.
9806 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9807 return EraseInstFromFunction(CI);
9808 // Otherwise, ignore the intrinsic.
9809 } else {
9810 // If we found a non-intrinsic call, we can't remove the stack
9811 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009812 CannotRemove = true;
9813 break;
9814 }
Chris Lattner989ba312008-06-18 04:33:20 +00009815 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009816 }
Chris Lattner989ba312008-06-18 04:33:20 +00009817
9818 // If the stack restore is in a return/unwind block and if there are no
9819 // allocas or calls between the restore and the return, nuke the restore.
9820 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9821 return EraseInstFromFunction(CI);
9822 break;
9823 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009824 }
9825
9826 return visitCallSite(II);
9827}
9828
9829// InvokeInst simplification
9830//
9831Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9832 return visitCallSite(&II);
9833}
9834
Dale Johannesen96021832008-04-25 21:16:07 +00009835/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9836/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009837static bool isSafeToEliminateVarargsCast(const CallSite CS,
9838 const CastInst * const CI,
9839 const TargetData * const TD,
9840 const int ix) {
9841 if (!CI->isLosslessCast())
9842 return false;
9843
9844 // The size of ByVal arguments is derived from the type, so we
9845 // can't change to a type with a different size. If the size were
9846 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009847 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009848 return true;
9849
9850 const Type* SrcTy =
9851 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9852 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9853 if (!SrcTy->isSized() || !DstTy->isSized())
9854 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00009855 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009856 return false;
9857 return true;
9858}
9859
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009860// visitCallSite - Improvements for call and invoke instructions.
9861//
9862Instruction *InstCombiner::visitCallSite(CallSite CS) {
9863 bool Changed = false;
9864
9865 // If the callee is a constexpr cast of a function, attempt to move the cast
9866 // to the arguments of the call/invoke.
9867 if (transformConstExprCastCall(CS)) return 0;
9868
9869 Value *Callee = CS.getCalledValue();
9870
9871 if (Function *CalleeF = dyn_cast<Function>(Callee))
9872 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9873 Instruction *OldCall = CS.getInstruction();
9874 // If the call and callee calling conventions don't match, this call must
9875 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009876 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +00009877 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Anderson24be4c12009-07-03 00:17:18 +00009878 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009879 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00009880 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009881 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9882 return EraseInstFromFunction(*OldCall);
9883 return 0;
9884 }
9885
9886 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9887 // This instruction is not reachable, just remove it. We insert a store to
9888 // undef so that we know that this code is not reachable, despite the fact
9889 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009890 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +00009891 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009892 CS.getInstruction());
9893
9894 if (!CS.getInstruction()->use_empty())
9895 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +00009896 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009897
9898 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9899 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009900 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +00009901 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009902 }
9903 return EraseInstFromFunction(*CS.getInstruction());
9904 }
9905
Duncan Sands74833f22007-09-17 10:26:40 +00009906 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9907 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9908 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9909 return transformCallThroughTrampoline(CS);
9910
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009911 const PointerType *PTy = cast<PointerType>(Callee->getType());
9912 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9913 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009914 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009915 // See if we can optimize any arguments passed through the varargs area of
9916 // the call.
9917 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009918 E = CS.arg_end(); I != E; ++I, ++ix) {
9919 CastInst *CI = dyn_cast<CastInst>(*I);
9920 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9921 *I = CI->getOperand(0);
9922 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009923 }
Dale Johannesen35615462008-04-23 18:34:37 +00009924 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009925 }
9926
Duncan Sands2937e352007-12-19 21:13:37 +00009927 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009928 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009929 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009930 Changed = true;
9931 }
9932
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009933 return Changed ? CS.getInstruction() : 0;
9934}
9935
9936// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9937// attempt to move the cast to the arguments of the call/invoke.
9938//
9939bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9940 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9941 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9942 if (CE->getOpcode() != Instruction::BitCast ||
9943 !isa<Function>(CE->getOperand(0)))
9944 return false;
9945 Function *Callee = cast<Function>(CE->getOperand(0));
9946 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00009947 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009948
9949 // Okay, this is a cast from a function to a different type. Unless doing so
9950 // would cause a type conversion of one of our arguments, change this call to
9951 // be a direct call with arguments casted to the appropriate types.
9952 //
9953 const FunctionType *FT = Callee->getFunctionType();
9954 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00009955 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009956
Duncan Sands7901ce12008-06-01 07:38:42 +00009957 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00009958 return false; // TODO: Handle multiple return values.
9959
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009960 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00009961 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009962 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00009963 // Conversion is ok if changing from one pointer type to another or from
9964 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +00009965 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00009966 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +00009967 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +00009968 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009969 return false; // Cannot transform this return value.
9970
Duncan Sands5c489582008-01-06 10:12:28 +00009971 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009972 // void -> non-void is handled specially
Owen Anderson35b47072009-08-13 21:58:54 +00009973 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009974 return false; // Cannot transform this return value.
9975
Chris Lattner1c8733e2008-03-12 17:45:29 +00009976 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00009977 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00009978 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009979 return false; // Attribute not compatible with transformed value.
9980 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009981
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009982 // If the callsite is an invoke instruction, and the return value is used by
9983 // a PHI node in a successor, we cannot change the return type of the call
9984 // because there is no place to put the cast instruction (without breaking
9985 // the critical edge). Bail out in this case.
9986 if (!Caller->use_empty())
9987 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9988 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9989 UI != E; ++UI)
9990 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9991 if (PN->getParent() == II->getNormalDest() ||
9992 PN->getParent() == II->getUnwindDest())
9993 return false;
9994 }
9995
9996 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9997 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9998
9999 CallSite::arg_iterator AI = CS.arg_begin();
10000 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10001 const Type *ParamTy = FT->getParamType(i);
10002 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010003
10004 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010005 return false; // Cannot transform this parameter value.
10006
Devang Patelf2a4a922008-09-26 22:53:05 +000010007 if (CallerPAL.getParamAttributes(i + 1)
10008 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010009 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010010
Duncan Sands7901ce12008-06-01 07:38:42 +000010011 // Converting from one pointer type to another or between a pointer and an
10012 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010013 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010014 (TD && ((isa<PointerType>(ParamTy) ||
10015 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10016 (isa<PointerType>(ActTy) ||
10017 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010018 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010019 }
10020
10021 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10022 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010023 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010024
Chris Lattner1c8733e2008-03-12 17:45:29 +000010025 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10026 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010027 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010028 // won't be dropping them. Check that these extra arguments have attributes
10029 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010030 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10031 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010032 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010033 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010034 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010035 return false;
10036 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010037
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010038 // Okay, we decided that this is a safe thing to do: go ahead and start
10039 // inserting cast instructions as necessary...
10040 std::vector<Value*> Args;
10041 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010042 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010043 attrVec.reserve(NumCommonArgs);
10044
10045 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010046 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010047
10048 // If the return value is not being used, the type may not be compatible
10049 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010050 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010051
10052 // Add the new return attributes.
10053 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010054 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010055
10056 AI = CS.arg_begin();
10057 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10058 const Type *ParamTy = FT->getParamType(i);
10059 if ((*AI)->getType() == ParamTy) {
10060 Args.push_back(*AI);
10061 } else {
10062 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10063 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010064 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010065 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010066
10067 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010068 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010069 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010070 }
10071
10072 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010073 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010075 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010076
Chris Lattnerad7516a2009-08-30 18:50:58 +000010077 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010078 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010079 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010080 errs() << "WARNING: While resolving call to function '"
10081 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010083 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010084 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10085 const Type *PTy = getPromotedType((*AI)->getType());
10086 if (PTy != (*AI)->getType()) {
10087 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010088 Instruction::CastOps opcode =
10089 CastInst::getCastOpcode(*AI, false, PTy, false);
10090 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010091 } else {
10092 Args.push_back(*AI);
10093 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010094
Duncan Sands4ced1f82008-01-13 08:02:44 +000010095 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010096 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010097 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010098 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010099 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010100 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101
Devang Patelf2a4a922008-09-26 22:53:05 +000010102 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10103 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10104
Owen Anderson35b47072009-08-13 21:58:54 +000010105 if (NewRetTy == Type::getVoidTy(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010106 Caller->setName(""); // Void type should not have a name.
10107
Eric Christopher3e7381f2009-07-25 02:45:27 +000010108 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10109 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010110
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010111 Instruction *NC;
10112 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010113 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010114 Args.begin(), Args.end(),
10115 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010116 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010117 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010118 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010119 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10120 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010121 CallInst *CI = cast<CallInst>(Caller);
10122 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010123 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010124 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010125 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010126 }
10127
10128 // Insert a cast of the return type as necessary.
10129 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010130 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson35b47072009-08-13 21:58:54 +000010131 if (NV->getType() != Type::getVoidTy(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010132 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010133 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010134 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010135
10136 // If this is an invoke instruction, we should insert it after the first
10137 // non-phi, instruction in the normal successor block.
10138 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010139 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140 InsertNewInstBefore(NC, *I);
10141 } else {
10142 // Otherwise, it's a call, just insert cast right after the call instr
10143 InsertNewInstBefore(NC, *Caller);
10144 }
Chris Lattner4796b622009-08-30 06:22:51 +000010145 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010147 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010148 }
10149 }
10150
Chris Lattner26b7f942009-08-31 05:17:58 +000010151
10152 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010153 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010154
10155 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156 return true;
10157}
10158
Duncan Sands74833f22007-09-17 10:26:40 +000010159// transformCallThroughTrampoline - Turn a call to a function created by the
10160// init_trampoline intrinsic into a direct call to the underlying function.
10161//
10162Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10163 Value *Callee = CS.getCalledValue();
10164 const PointerType *PTy = cast<PointerType>(Callee->getType());
10165 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010166 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010167
10168 // If the call already has the 'nest' attribute somewhere then give up -
10169 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010170 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010171 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010172
10173 IntrinsicInst *Tramp =
10174 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10175
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010176 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010177 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10178 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10179
Devang Pateld222f862008-09-25 21:00:45 +000010180 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010181 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010182 unsigned NestIdx = 1;
10183 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010184 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010185
10186 // Look for a parameter marked with the 'nest' attribute.
10187 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10188 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010189 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010190 // Record the parameter type and any other attributes.
10191 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010192 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010193 break;
10194 }
10195
10196 if (NestTy) {
10197 Instruction *Caller = CS.getInstruction();
10198 std::vector<Value*> NewArgs;
10199 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10200
Devang Pateld222f862008-09-25 21:00:45 +000010201 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010202 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010203
Duncan Sands74833f22007-09-17 10:26:40 +000010204 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010205 // mean appending it. Likewise for attributes.
10206
Devang Patelf2a4a922008-09-26 22:53:05 +000010207 // Add any result attributes.
10208 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010209 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010210
Duncan Sands74833f22007-09-17 10:26:40 +000010211 {
10212 unsigned Idx = 1;
10213 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10214 do {
10215 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010216 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010217 Value *NestVal = Tramp->getOperand(3);
10218 if (NestVal->getType() != NestTy)
10219 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10220 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010221 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010222 }
10223
10224 if (I == E)
10225 break;
10226
Duncan Sands48b81112008-01-14 19:52:09 +000010227 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010228 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010229 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010230 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010231 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010232
10233 ++Idx, ++I;
10234 } while (1);
10235 }
10236
Devang Patelf2a4a922008-09-26 22:53:05 +000010237 // Add any function attributes.
10238 if (Attributes Attr = Attrs.getFnAttributes())
10239 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10240
Duncan Sands74833f22007-09-17 10:26:40 +000010241 // The trampoline may have been bitcast to a bogus type (FTy).
10242 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010243 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010244
Duncan Sands74833f22007-09-17 10:26:40 +000010245 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010246 NewTypes.reserve(FTy->getNumParams()+1);
10247
Duncan Sands74833f22007-09-17 10:26:40 +000010248 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010249 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010250 {
10251 unsigned Idx = 1;
10252 FunctionType::param_iterator I = FTy->param_begin(),
10253 E = FTy->param_end();
10254
10255 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010256 if (Idx == NestIdx)
10257 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010258 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010259
10260 if (I == E)
10261 break;
10262
Duncan Sands48b81112008-01-14 19:52:09 +000010263 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010264 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010265
10266 ++Idx, ++I;
10267 } while (1);
10268 }
10269
10270 // Replace the trampoline call with a direct call. Let the generic
10271 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010272 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010273 FTy->isVarArg());
10274 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010275 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010276 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010277 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010278 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10279 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010280
10281 Instruction *NewCaller;
10282 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010283 NewCaller = InvokeInst::Create(NewCallee,
10284 II->getNormalDest(), II->getUnwindDest(),
10285 NewArgs.begin(), NewArgs.end(),
10286 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010287 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010288 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010289 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010290 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10291 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010292 if (cast<CallInst>(Caller)->isTailCall())
10293 cast<CallInst>(NewCaller)->setTailCall();
10294 cast<CallInst>(NewCaller)->
10295 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010296 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010297 }
Owen Anderson35b47072009-08-13 21:58:54 +000010298 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sands74833f22007-09-17 10:26:40 +000010299 Caller->replaceAllUsesWith(NewCaller);
10300 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010301 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010302 return 0;
10303 }
10304 }
10305
10306 // Replace the trampoline call with a direct call. Since there is no 'nest'
10307 // parameter, there is no need to adjust the argument list. Let the generic
10308 // code sort out any function type mismatches.
10309 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010310 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010311 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010312 CS.setCalledFunction(NewCallee);
10313 return CS.getInstruction();
10314}
10315
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010316/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10317/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10318/// and a single binop.
10319Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10320 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010321 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010322 unsigned Opc = FirstInst->getOpcode();
10323 Value *LHSVal = FirstInst->getOperand(0);
10324 Value *RHSVal = FirstInst->getOperand(1);
10325
10326 const Type *LHSType = LHSVal->getType();
10327 const Type *RHSType = RHSVal->getType();
10328
10329 // Scan to see if all operands are the same opcode, all have one use, and all
10330 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010331 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010332 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10333 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10334 // Verify type of the LHS matches so we don't fold cmp's of different
10335 // types or GEP's with different index types.
10336 I->getOperand(0)->getType() != LHSType ||
10337 I->getOperand(1)->getType() != RHSType)
10338 return 0;
10339
10340 // If they are CmpInst instructions, check their predicates
10341 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10342 if (cast<CmpInst>(I)->getPredicate() !=
10343 cast<CmpInst>(FirstInst)->getPredicate())
10344 return 0;
10345
10346 // Keep track of which operand needs a phi node.
10347 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10348 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10349 }
10350
Chris Lattner30078012008-12-01 03:42:51 +000010351 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010352
10353 Value *InLHS = FirstInst->getOperand(0);
10354 Value *InRHS = FirstInst->getOperand(1);
10355 PHINode *NewLHS = 0, *NewRHS = 0;
10356 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010357 NewLHS = PHINode::Create(LHSType,
10358 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010359 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10360 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10361 InsertNewInstBefore(NewLHS, PN);
10362 LHSVal = NewLHS;
10363 }
10364
10365 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010366 NewRHS = PHINode::Create(RHSType,
10367 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010368 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10369 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10370 InsertNewInstBefore(NewRHS, PN);
10371 RHSVal = NewRHS;
10372 }
10373
10374 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010375 if (NewLHS || NewRHS) {
10376 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10377 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10378 if (NewLHS) {
10379 Value *NewInLHS = InInst->getOperand(0);
10380 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10381 }
10382 if (NewRHS) {
10383 Value *NewInRHS = InInst->getOperand(1);
10384 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10385 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010386 }
10387 }
10388
10389 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010390 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010391 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010392 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010393 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010394}
10395
Chris Lattner9e1916e2008-12-01 02:34:36 +000010396Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10397 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10398
10399 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10400 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010401 // This is true if all GEP bases are allocas and if all indices into them are
10402 // constants.
10403 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010404
10405 // We don't want to replace this phi if the replacement would require
10406 // more than one phi.
10407 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010408
10409 // Scan to see if all operands are the same opcode, all have one use, and all
10410 // kill their operands (i.e. the operands have one use).
10411 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10412 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10413 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10414 GEP->getNumOperands() != FirstInst->getNumOperands())
10415 return 0;
10416
Chris Lattneradf354b2009-02-21 00:46:50 +000010417 // Keep track of whether or not all GEPs are of alloca pointers.
10418 if (AllBasePointersAreAllocas &&
10419 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10420 !GEP->hasAllConstantIndices()))
10421 AllBasePointersAreAllocas = false;
10422
Chris Lattner9e1916e2008-12-01 02:34:36 +000010423 // Compare the operand lists.
10424 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10425 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10426 continue;
10427
10428 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10429 // if one of the PHIs has a constant for the index. The index may be
10430 // substantially cheaper to compute for the constants, so making it a
10431 // variable index could pessimize the path. This also handles the case
10432 // for struct indices, which must always be constant.
10433 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10434 isa<ConstantInt>(GEP->getOperand(op)))
10435 return 0;
10436
10437 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10438 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010439
10440 // If we already needed a PHI for an earlier operand, and another operand
10441 // also requires a PHI, we'd be introducing more PHIs than we're
10442 // eliminating, which increases register pressure on entry to the PHI's
10443 // block.
10444 if (NeededPhi)
10445 return 0;
10446
Chris Lattner9e1916e2008-12-01 02:34:36 +000010447 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010448 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010449 }
10450 }
10451
Chris Lattneradf354b2009-02-21 00:46:50 +000010452 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010453 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010454 // offset calculation, but all the predecessors will have to materialize the
10455 // stack address into a register anyway. We'd actually rather *clone* the
10456 // load up into the predecessors so that we have a load of a gep of an alloca,
10457 // which can usually all be folded into the load.
10458 if (AllBasePointersAreAllocas)
10459 return 0;
10460
Chris Lattner9e1916e2008-12-01 02:34:36 +000010461 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10462 // that is variable.
10463 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10464
10465 bool HasAnyPHIs = false;
10466 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10467 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10468 Value *FirstOp = FirstInst->getOperand(i);
10469 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10470 FirstOp->getName()+".pn");
10471 InsertNewInstBefore(NewPN, PN);
10472
10473 NewPN->reserveOperandSpace(e);
10474 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10475 OperandPhis[i] = NewPN;
10476 FixedOperands[i] = NewPN;
10477 HasAnyPHIs = true;
10478 }
10479
10480
10481 // Add all operands to the new PHIs.
10482 if (HasAnyPHIs) {
10483 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10484 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10485 BasicBlock *InBB = PN.getIncomingBlock(i);
10486
10487 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10488 if (PHINode *OpPhi = OperandPhis[op])
10489 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10490 }
10491 }
10492
10493 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010494 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10495 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10496 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010497 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10498 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010499}
10500
10501
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010502/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10503/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010504/// obvious the value of the load is not changed from the point of the load to
10505/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010506///
10507/// Finally, it is safe, but not profitable, to sink a load targetting a
10508/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10509/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010510static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010511 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10512
10513 for (++BBI; BBI != E; ++BBI)
10514 if (BBI->mayWriteToMemory())
10515 return false;
10516
10517 // Check for non-address taken alloca. If not address-taken already, it isn't
10518 // profitable to do this xform.
10519 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10520 bool isAddressTaken = false;
10521 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10522 UI != E; ++UI) {
10523 if (isa<LoadInst>(UI)) continue;
10524 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10525 // If storing TO the alloca, then the address isn't taken.
10526 if (SI->getOperand(1) == AI) continue;
10527 }
10528 isAddressTaken = true;
10529 break;
10530 }
10531
Chris Lattneradf354b2009-02-21 00:46:50 +000010532 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010533 return false;
10534 }
10535
Chris Lattneradf354b2009-02-21 00:46:50 +000010536 // If this load is a load from a GEP with a constant offset from an alloca,
10537 // then we don't want to sink it. In its present form, it will be
10538 // load [constant stack offset]. Sinking it will cause us to have to
10539 // materialize the stack addresses in each predecessor in a register only to
10540 // do a shared load from register in the successor.
10541 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10542 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10543 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10544 return false;
10545
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010546 return true;
10547}
10548
10549
10550// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10551// operator and they all are only used by the PHI, PHI together their
10552// inputs, and do the operation once, to the result of the PHI.
10553Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10554 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10555
10556 // Scan the instruction, looking for input operations that can be folded away.
10557 // If all input operands to the phi are the same instruction (e.g. a cast from
10558 // the same type or "+42") we can pull the operation through the PHI, reducing
10559 // code size and simplifying code.
10560 Constant *ConstantOp = 0;
10561 const Type *CastSrcTy = 0;
10562 bool isVolatile = false;
10563 if (isa<CastInst>(FirstInst)) {
10564 CastSrcTy = FirstInst->getOperand(0)->getType();
10565 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10566 // Can fold binop, compare or shift here if the RHS is a constant,
10567 // otherwise call FoldPHIArgBinOpIntoPHI.
10568 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10569 if (ConstantOp == 0)
10570 return FoldPHIArgBinOpIntoPHI(PN);
10571 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10572 isVolatile = LI->isVolatile();
10573 // We can't sink the load if the loaded value could be modified between the
10574 // load and the PHI.
10575 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010576 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010577 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010578
10579 // If the PHI is of volatile loads and the load block has multiple
10580 // successors, sinking it would remove a load of the volatile value from
10581 // the path through the other successor.
10582 if (isVolatile &&
10583 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10584 return 0;
10585
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010586 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010587 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010588 } else {
10589 return 0; // Cannot fold this operation.
10590 }
10591
10592 // Check to see if all arguments are the same operation.
10593 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10594 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10595 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10596 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10597 return 0;
10598 if (CastSrcTy) {
10599 if (I->getOperand(0)->getType() != CastSrcTy)
10600 return 0; // Cast operation must match.
10601 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10602 // We can't sink the load if the loaded value could be modified between
10603 // the load and the PHI.
10604 if (LI->isVolatile() != isVolatile ||
10605 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010606 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010607 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010608
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010609 // If the PHI is of volatile loads and the load block has multiple
10610 // successors, sinking it would remove a load of the volatile value from
10611 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010612 if (isVolatile &&
10613 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10614 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010615
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010616 } else if (I->getOperand(1) != ConstantOp) {
10617 return 0;
10618 }
10619 }
10620
10621 // Okay, they are all the same operation. Create a new PHI node of the
10622 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010623 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10624 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010625 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10626
10627 Value *InVal = FirstInst->getOperand(0);
10628 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10629
10630 // Add all operands to the new PHI.
10631 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10632 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10633 if (NewInVal != InVal)
10634 InVal = 0;
10635 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10636 }
10637
10638 Value *PhiVal;
10639 if (InVal) {
10640 // The new PHI unions all of the same values together. This is really
10641 // common, so we handle it intelligently here for compile-time speed.
10642 PhiVal = InVal;
10643 delete NewPN;
10644 } else {
10645 InsertNewInstBefore(NewPN, PN);
10646 PhiVal = NewPN;
10647 }
10648
10649 // Insert and return the new operation.
10650 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010651 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010652 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010653 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010654 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohmane6803b82009-08-25 23:17:54 +000010655 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010656 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010657 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10658
10659 // If this was a volatile load that we are merging, make sure to loop through
10660 // and mark all the input loads as non-volatile. If we don't do this, we will
10661 // insert a new volatile load and the old ones will not be deletable.
10662 if (isVolatile)
10663 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10664 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10665
10666 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010667}
10668
10669/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10670/// that is dead.
10671static bool DeadPHICycle(PHINode *PN,
10672 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10673 if (PN->use_empty()) return true;
10674 if (!PN->hasOneUse()) return false;
10675
10676 // Remember this node, and if we find the cycle, return.
10677 if (!PotentiallyDeadPHIs.insert(PN))
10678 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010679
10680 // Don't scan crazily complex things.
10681 if (PotentiallyDeadPHIs.size() == 16)
10682 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010683
10684 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10685 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10686
10687 return false;
10688}
10689
Chris Lattner27b695d2007-11-06 21:52:06 +000010690/// PHIsEqualValue - Return true if this phi node is always equal to
10691/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10692/// z = some value; x = phi (y, z); y = phi (x, z)
10693static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10694 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10695 // See if we already saw this PHI node.
10696 if (!ValueEqualPHIs.insert(PN))
10697 return true;
10698
10699 // Don't scan crazily complex things.
10700 if (ValueEqualPHIs.size() == 16)
10701 return false;
10702
10703 // Scan the operands to see if they are either phi nodes or are equal to
10704 // the value.
10705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10706 Value *Op = PN->getIncomingValue(i);
10707 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10708 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10709 return false;
10710 } else if (Op != NonPhiInVal)
10711 return false;
10712 }
10713
10714 return true;
10715}
10716
10717
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010718// PHINode simplification
10719//
10720Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10721 // If LCSSA is around, don't mess with Phi nodes
10722 if (MustPreserveLCSSA) return 0;
10723
10724 if (Value *V = PN.hasConstantValue())
10725 return ReplaceInstUsesWith(PN, V);
10726
10727 // If all PHI operands are the same operation, pull them through the PHI,
10728 // reducing code size.
10729 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010730 isa<Instruction>(PN.getIncomingValue(1)) &&
10731 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10732 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10733 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10734 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010735 PN.getIncomingValue(0)->hasOneUse())
10736 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10737 return Result;
10738
10739 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10740 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10741 // PHI)... break the cycle.
10742 if (PN.hasOneUse()) {
10743 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10744 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10745 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10746 PotentiallyDeadPHIs.insert(&PN);
10747 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010748 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010749 }
10750
10751 // If this phi has a single use, and if that use just computes a value for
10752 // the next iteration of a loop, delete the phi. This occurs with unused
10753 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10754 // common case here is good because the only other things that catch this
10755 // are induction variable analysis (sometimes) and ADCE, which is only run
10756 // late.
10757 if (PHIUser->hasOneUse() &&
10758 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10759 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010760 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010761 }
10762 }
10763
Chris Lattner27b695d2007-11-06 21:52:06 +000010764 // We sometimes end up with phi cycles that non-obviously end up being the
10765 // same value, for example:
10766 // z = some value; x = phi (y, z); y = phi (x, z)
10767 // where the phi nodes don't necessarily need to be in the same block. Do a
10768 // quick check to see if the PHI node only contains a single non-phi value, if
10769 // so, scan to see if the phi cycle is actually equal to that value.
10770 {
10771 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10772 // Scan for the first non-phi operand.
10773 while (InValNo != NumOperandVals &&
10774 isa<PHINode>(PN.getIncomingValue(InValNo)))
10775 ++InValNo;
10776
10777 if (InValNo != NumOperandVals) {
10778 Value *NonPhiInVal = PN.getOperand(InValNo);
10779
10780 // Scan the rest of the operands to see if there are any conflicts, if so
10781 // there is no need to recursively scan other phis.
10782 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10783 Value *OpVal = PN.getIncomingValue(InValNo);
10784 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10785 break;
10786 }
10787
10788 // If we scanned over all operands, then we have one unique value plus
10789 // phi values. Scan PHI nodes to see if they all merge in each other or
10790 // the value.
10791 if (InValNo == NumOperandVals) {
10792 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10793 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10794 return ReplaceInstUsesWith(PN, NonPhiInVal);
10795 }
10796 }
10797 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010798 return 0;
10799}
10800
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010801Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10802 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerf3a23592009-08-30 20:36:46 +000010803 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010804 if (GEP.getNumOperands() == 1)
10805 return ReplaceInstUsesWith(GEP, PtrOp);
10806
10807 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010808 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010809
10810 bool HasZeroPointerIndex = false;
10811 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10812 HasZeroPointerIndex = C->isNullValue();
10813
10814 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10815 return ReplaceInstUsesWith(GEP, PtrOp);
10816
10817 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010818 if (TD) {
10819 bool MadeChange = false;
10820 unsigned PtrSize = TD->getPointerSizeInBits();
10821
10822 gep_type_iterator GTI = gep_type_begin(GEP);
10823 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10824 I != E; ++I, ++GTI) {
10825 if (!isa<SequentialType>(*GTI)) continue;
10826
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010827 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010828 // to what we need. If narrower, sign-extend it to what we need. This
10829 // explicit cast can make subsequent optimizations more obvious.
10830 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010831 if (OpBits == PtrSize)
10832 continue;
10833
Chris Lattnerd6164c22009-08-30 20:01:10 +000010834 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010835 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010836 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010837 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010838 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010839
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010840 // Combine Indices - If the source pointer to this getelementptr instruction
10841 // is a getelementptr instruction, combine the indices of the two
10842 // getelementptr instructions into a single instruction.
10843 //
Dan Gohman17f46f72009-07-28 01:40:03 +000010844 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010845 // Note that if our source is a gep chain itself that we wait for that
10846 // chain to be resolved before we perform this transformation. This
10847 // avoids us creating a TON of code in some cases.
10848 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010849 if (GetElementPtrInst *SrcGEP =
10850 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10851 if (SrcGEP->getNumOperands() == 2)
10852 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010853
10854 SmallVector<Value*, 8> Indices;
10855
10856 // Find out whether the last index in the source GEP is a sequential idx.
10857 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000010858 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10859 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010860 EndsWithSequential = !isa<StructType>(*I);
10861
10862 // Can we combine the two pointer arithmetics offsets?
10863 if (EndsWithSequential) {
10864 // Replace: gep (gep %P, long B), long A, ...
10865 // With: T = long A+B; gep %P, T, ...
10866 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010867 Value *Sum;
10868 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10869 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000010870 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010871 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000010872 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010873 Sum = SO1;
10874 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000010875 // If they aren't the same type, then the input hasn't been processed
10876 // by the loop above yet (which canonicalizes sequential index types to
10877 // intptr_t). Just avoid transforming this until the input has been
10878 // normalized.
10879 if (SO1->getType() != GO1->getType())
10880 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000010881 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010882 }
10883
Chris Lattner1c641fc2009-08-30 05:30:55 +000010884 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010885 if (Src->getNumOperands() == 2) {
10886 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010887 GEP.setOperand(1, Sum);
10888 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010889 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000010890 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010891 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000010892 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010893 } else if (isa<Constant>(*GEP.idx_begin()) &&
10894 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010895 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010896 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000010897 Indices.append(Src->op_begin()+1, Src->op_end());
10898 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010899 }
10900
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010901 if (!Indices.empty())
10902 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10903 Src->isInBounds()) ?
10904 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10905 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010906 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010907 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010908 }
10909
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010910 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10911 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010912 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000010913
Chris Lattner83288fa2009-08-30 20:38:21 +000010914 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10915 // want to change the gep until the bitcasts are eliminated.
10916 if (getBitCastOperand(X)) {
10917 Worklist.AddValue(PtrOp);
10918 return 0;
10919 }
10920
Chris Lattnerf3a23592009-08-30 20:36:46 +000010921 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10922 // into : GEP [10 x i8]* X, i32 0, ...
10923 //
10924 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10925 // into : GEP i8* X, ...
10926 //
10927 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010928 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010929 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10930 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000010931 if (const ArrayType *CATy =
10932 dyn_cast<ArrayType>(CPTy->getElementType())) {
10933 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10934 if (CATy->getElementType() == XTy->getElementType()) {
10935 // -> GEP i8* X, ...
10936 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010937 return cast<GEPOperator>(&GEP)->isInBounds() ?
10938 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
10939 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010940 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10941 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000010942 }
10943
10944 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000010945 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010946 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000010947 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010948 // At this point, we know that the cast source type is a pointer
10949 // to an array of the same type as the destination pointer
10950 // array. Because the array type is never stepped over (there
10951 // is a leading zero) we can fold the cast into this GEP.
10952 GEP.setOperand(0, X);
10953 return &GEP;
10954 }
Duncan Sandscf866e62009-03-02 09:18:21 +000010955 }
10956 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010957 } else if (GEP.getNumOperands() == 2) {
10958 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010959 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10960 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010961 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10962 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000010963 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000010964 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10965 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010966 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000010967 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000010968 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010969 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
10970 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000010971 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010972 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000010973 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010974 }
10975
10976 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010977 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010978 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010979 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010980
Owen Anderson35b47072009-08-13 21:58:54 +000010981 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010982 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000010983 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010984
10985 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10986 // allow either a mul, shift, or constant here.
10987 Value *NewIdx = 0;
10988 ConstantInt *Scale = 0;
10989 if (ArrayEltSize == 1) {
10990 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000010991 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010992 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000010993 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010994 Scale = CI;
10995 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10996 if (Inst->getOpcode() == Instruction::Shl &&
10997 isa<ConstantInt>(Inst->getOperand(1))) {
10998 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10999 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011000 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011001 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011002 NewIdx = Inst->getOperand(0);
11003 } else if (Inst->getOpcode() == Instruction::Mul &&
11004 isa<ConstantInt>(Inst->getOperand(1))) {
11005 Scale = cast<ConstantInt>(Inst->getOperand(1));
11006 NewIdx = Inst->getOperand(0);
11007 }
11008 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011009
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011010 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011011 // out, perform the transformation. Note, we don't know whether Scale is
11012 // signed or not. We'll use unsigned version of division/modulo
11013 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011014 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011015 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011016 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011017 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011018 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011019 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11020 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011021 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011022 }
11023
11024 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011025 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011026 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011027 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011028 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11029 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11030 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011031 // The NewGEP must be pointer typed, so must the old one -> BitCast
11032 return new BitCastInst(NewGEP, GEP.getType());
11033 }
11034 }
11035 }
11036 }
Chris Lattner111ea772009-01-09 04:53:57 +000011037
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011038 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011039 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011040 /// Y = gep X, <...constant indices...>
11041 /// into a gep of the original struct. This is important for SROA and alias
11042 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011043 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011044 if (TD &&
11045 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011046 // Determine how much the GEP moves the pointer. We are guaranteed to get
11047 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011048 ConstantInt *OffsetV =
11049 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011050 int64_t Offset = OffsetV->getSExtValue();
11051
11052 // If this GEP instruction doesn't move the pointer, just replace the GEP
11053 // with a bitcast of the real input to the dest type.
11054 if (Offset == 0) {
11055 // If the bitcast is of an allocation, and the allocation will be
11056 // converted to match the type of the cast, don't touch this.
11057 if (isa<AllocationInst>(BCI->getOperand(0))) {
11058 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11059 if (Instruction *I = visitBitCast(*BCI)) {
11060 if (I != BCI) {
11061 I->takeName(BCI);
11062 BCI->getParent()->getInstList().insert(BCI, I);
11063 ReplaceInstUsesWith(*BCI, I);
11064 }
11065 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011066 }
Chris Lattner111ea772009-01-09 04:53:57 +000011067 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011068 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011069 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011070
11071 // Otherwise, if the offset is non-zero, we need to find out if there is a
11072 // field at Offset in 'A's type. If so, we can pull the cast through the
11073 // GEP.
11074 SmallVector<Value*, 8> NewIndices;
11075 const Type *InTy =
11076 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011077 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011078 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11079 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11080 NewIndices.end()) :
11081 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11082 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011083
11084 if (NGEP->getType() == GEP.getType())
11085 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011086 NGEP->takeName(&GEP);
11087 return new BitCastInst(NGEP, GEP.getType());
11088 }
Chris Lattner111ea772009-01-09 04:53:57 +000011089 }
11090 }
11091
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011092 return 0;
11093}
11094
11095Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11096 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011097 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011098 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11099 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011100 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011101 AllocationInst *New = 0;
11102
11103 // Create and insert the replacement instruction...
11104 if (isa<MallocInst>(AI))
Chris Lattnerad7516a2009-08-30 18:50:58 +000011105 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011106 else {
11107 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerad7516a2009-08-30 18:50:58 +000011108 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011109 }
Chris Lattnerad7516a2009-08-30 18:50:58 +000011110 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011111
11112 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011113 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011114 //
11115 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011116 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011117
11118 // Now that I is pointing to the first non-allocation-inst in the block,
11119 // insert our getelementptr instruction...
11120 //
Owen Anderson35b47072009-08-13 21:58:54 +000011121 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011122 Value *Idx[2];
11123 Idx[0] = NullIdx;
11124 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011125 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11126 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011127
11128 // Now make everything use the getelementptr instead of the original
11129 // allocation.
11130 return ReplaceInstUsesWith(AI, V);
11131 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011132 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011133 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011134 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011135
Dan Gohmana80e2712009-07-21 23:21:54 +000011136 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011137 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011138 // Note that we only do this for alloca's, because malloc should allocate
11139 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011140 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011141 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011142
11143 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11144 if (AI.getAlignment() == 0)
11145 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11146 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011147
11148 return 0;
11149}
11150
11151Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11152 Value *Op = FI.getOperand(0);
11153
11154 // free undef -> unreachable.
11155 if (isa<UndefValue>(Op)) {
11156 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011157 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +000011158 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011159 return EraseInstFromFunction(FI);
11160 }
11161
11162 // If we have 'free null' delete the instruction. This can happen in stl code
11163 // when lots of inlining happens.
11164 if (isa<ConstantPointerNull>(Op))
11165 return EraseInstFromFunction(FI);
11166
11167 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11168 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11169 FI.setOperand(0, CI->getOperand(0));
11170 return &FI;
11171 }
11172
11173 // Change free (gep X, 0,0,0,0) into free(X)
11174 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11175 if (GEPI->hasAllZeroIndices()) {
Chris Lattner3183fb62009-08-30 06:13:40 +000011176 Worklist.Add(GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011177 FI.setOperand(0, GEPI->getOperand(0));
11178 return &FI;
11179 }
11180 }
11181
11182 // Change free(malloc) into nothing, if the malloc has a single use.
11183 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11184 if (MI->hasOneUse()) {
11185 EraseInstFromFunction(FI);
11186 return EraseInstFromFunction(*MI);
11187 }
11188
11189 return 0;
11190}
11191
11192
11193/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011194static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011195 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011196 User *CI = cast<User>(LI.getOperand(0));
11197 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011198 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011199
Nick Lewycky291c5942009-05-08 06:47:37 +000011200 if (TD) {
11201 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11202 // Instead of loading constant c string, use corresponding integer value
11203 // directly if string length is small enough.
11204 std::string Str;
11205 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11206 unsigned len = Str.length();
11207 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11208 unsigned numBits = Ty->getPrimitiveSizeInBits();
11209 // Replace LI with immediate integer store.
11210 if ((numBits >> 3) == len + 1) {
11211 APInt StrVal(numBits, 0);
11212 APInt SingleChar(numBits, 0);
11213 if (TD->isLittleEndian()) {
11214 for (signed i = len-1; i >= 0; i--) {
11215 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11216 StrVal = (StrVal << 8) | SingleChar;
11217 }
11218 } else {
11219 for (unsigned i = 0; i < len; i++) {
11220 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11221 StrVal = (StrVal << 8) | SingleChar;
11222 }
11223 // Append NULL at the end.
11224 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011225 StrVal = (StrVal << 8) | SingleChar;
11226 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011227 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011228 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011229 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011230 }
11231 }
11232 }
11233
Mon P Wangbd05ed82009-02-07 22:19:29 +000011234 const PointerType *DestTy = cast<PointerType>(CI->getType());
11235 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011236 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011237
11238 // If the address spaces don't match, don't eliminate the cast.
11239 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11240 return 0;
11241
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011242 const Type *SrcPTy = SrcTy->getElementType();
11243
11244 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11245 isa<VectorType>(DestPTy)) {
11246 // If the source is an array, the code below will not succeed. Check to
11247 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11248 // constants.
11249 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11250 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11251 if (ASrcTy->getNumElements() != 0) {
11252 Value *Idxs[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011253 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Anderson02b48c32009-07-29 18:55:55 +000011254 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011255 SrcTy = cast<PointerType>(CastOp->getType());
11256 SrcPTy = SrcTy->getElementType();
11257 }
11258
Dan Gohmana80e2712009-07-21 23:21:54 +000011259 if (IC.getTargetData() &&
11260 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011261 isa<VectorType>(SrcPTy)) &&
11262 // Do not allow turning this into a load of an integer, which is then
11263 // casted to a pointer, this pessimizes pointer analysis a lot.
11264 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011265 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11266 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011267
11268 // Okay, we are casting from one integer or pointer type to another of
11269 // the same size. Instead of casting the pointer before the load, cast
11270 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011271 Value *NewLoad =
11272 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011273 // Now cast the result of the load.
11274 return new BitCastInst(NewLoad, LI.getType());
11275 }
11276 }
11277 }
11278 return 0;
11279}
11280
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011281Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11282 Value *Op = LI.getOperand(0);
11283
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011284 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011285 if (TD) {
11286 unsigned KnownAlign =
11287 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11288 if (KnownAlign >
11289 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11290 LI.getAlignment()))
11291 LI.setAlignment(KnownAlign);
11292 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011293
Chris Lattnerf3a23592009-08-30 20:36:46 +000011294 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011295 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011296 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011297 return Res;
11298
11299 // None of the following transforms are legal for volatile loads.
11300 if (LI.isVolatile()) return 0;
11301
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011302 // Do really simple store-to-load forwarding and load CSE, to catch cases
11303 // where there are several consequtive memory accesses to the same location,
11304 // separated by a few arithmetic operations.
11305 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011306 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11307 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011308
Christopher Lamb2c175392007-12-29 07:56:53 +000011309 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11310 const Value *GEPI0 = GEPI->getOperand(0);
11311 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011312 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011313 // Insert a new store to null instruction before the load to indicate
11314 // that this code is not reachable. We do this instead of inserting
11315 // an unreachable instruction directly because we cannot modify the
11316 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011317 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011318 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011319 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011320 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011321 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011322
11323 if (Constant *C = dyn_cast<Constant>(Op)) {
11324 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011325 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011326 if (isa<UndefValue>(C) ||
11327 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011328 // Insert a new store to null instruction before the load to indicate that
11329 // this code is not reachable. We do this instead of inserting an
11330 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011331 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011332 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011333 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011334 }
11335
11336 // Instcombine load (constant global) into the value loaded.
11337 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011338 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011339 return ReplaceInstUsesWith(LI, GV->getInitializer());
11340
11341 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011342 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011343 if (CE->getOpcode() == Instruction::GetElementPtr) {
11344 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011345 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011346 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011347 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011348 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011349 return ReplaceInstUsesWith(LI, V);
11350 if (CE->getOperand(0)->isNullValue()) {
11351 // Insert a new store to null instruction before the load to indicate
11352 // that this code is not reachable. We do this instead of inserting
11353 // an unreachable instruction directly because we cannot modify the
11354 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011355 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011356 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011357 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011358 }
11359
11360 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011361 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011362 return Res;
11363 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011364 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011365 }
Chris Lattner0270a112007-08-11 18:48:48 +000011366
11367 // If this load comes from anywhere in a constant global, and if the global
11368 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011369 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011370 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011371 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011372 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011373 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011374 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011375 }
11376 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011377
11378 if (Op->hasOneUse()) {
11379 // Change select and PHI nodes to select values instead of addresses: this
11380 // helps alias analysis out a lot, allows many others simplifications, and
11381 // exposes redundancy in the code.
11382 //
11383 // Note that we cannot do the transformation unless we know that the
11384 // introduced loads cannot trap! Something like this is valid as long as
11385 // the condition is always false: load (select bool %C, int* null, int* %G),
11386 // but it would not be valid if we transformed it to load from null
11387 // unconditionally.
11388 //
11389 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11390 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11391 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11392 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011393 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11394 SI->getOperand(1)->getName()+".val");
11395 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11396 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011397 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011398 }
11399
11400 // load (select (cond, null, P)) -> load P
11401 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11402 if (C->isNullValue()) {
11403 LI.setOperand(0, SI->getOperand(2));
11404 return &LI;
11405 }
11406
11407 // load (select (cond, P, null)) -> load P
11408 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11409 if (C->isNullValue()) {
11410 LI.setOperand(0, SI->getOperand(1));
11411 return &LI;
11412 }
11413 }
11414 }
11415 return 0;
11416}
11417
11418/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011419/// when possible. This makes it generally easy to do alias analysis and/or
11420/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011421static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11422 User *CI = cast<User>(SI.getOperand(1));
11423 Value *CastOp = CI->getOperand(0);
11424
11425 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011426 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11427 if (SrcTy == 0) return 0;
11428
11429 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011430
Chris Lattnera032c0e2009-01-16 20:08:59 +000011431 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11432 return 0;
11433
Chris Lattner54dddc72009-01-24 01:00:13 +000011434 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11435 /// to its first element. This allows us to handle things like:
11436 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11437 /// on 32-bit hosts.
11438 SmallVector<Value*, 4> NewGEPIndices;
11439
Chris Lattnera032c0e2009-01-16 20:08:59 +000011440 // If the source is an array, the code below will not succeed. Check to
11441 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11442 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011443 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11444 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011445 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011446 NewGEPIndices.push_back(Zero);
11447
11448 while (1) {
11449 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011450 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011451 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011452 NewGEPIndices.push_back(Zero);
11453 SrcPTy = STy->getElementType(0);
11454 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11455 NewGEPIndices.push_back(Zero);
11456 SrcPTy = ATy->getElementType();
11457 } else {
11458 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011460 }
11461
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011462 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011463 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011464
11465 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11466 return 0;
11467
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011468 // If the pointers point into different address spaces or if they point to
11469 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011470 if (!IC.getTargetData() ||
11471 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011472 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011473 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11474 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011475 return 0;
11476
11477 // Okay, we are casting from one integer or pointer type to another of
11478 // the same size. Instead of casting the pointer before
11479 // the store, cast the value to be stored.
11480 Value *NewCast;
11481 Value *SIOp0 = SI.getOperand(0);
11482 Instruction::CastOps opcode = Instruction::BitCast;
11483 const Type* CastSrcTy = SIOp0->getType();
11484 const Type* CastDstTy = SrcPTy;
11485 if (isa<PointerType>(CastDstTy)) {
11486 if (CastSrcTy->isInteger())
11487 opcode = Instruction::IntToPtr;
11488 } else if (isa<IntegerType>(CastDstTy)) {
11489 if (isa<PointerType>(SIOp0->getType()))
11490 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011491 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011492
11493 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11494 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011495 if (!NewGEPIndices.empty())
11496 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11497 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000011498
Chris Lattnerad7516a2009-08-30 18:50:58 +000011499 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11500 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000011501 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011502}
11503
Chris Lattner6fd8c802008-11-27 08:56:30 +000011504/// equivalentAddressValues - Test if A and B will obviously have the same
11505/// value. This includes recognizing that %t0 and %t1 will have the same
11506/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011507/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011508/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011509/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011510/// %t2 = load i32* %t1
11511///
11512static bool equivalentAddressValues(Value *A, Value *B) {
11513 // Test if the values are trivially equivalent.
11514 if (A == B) return true;
11515
11516 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011517 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11518 // its only used to compare two uses within the same basic block, which
11519 // means that they'll always either have the same value or one of them
11520 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000011521 if (isa<BinaryOperator>(A) ||
11522 isa<CastInst>(A) ||
11523 isa<PHINode>(A) ||
11524 isa<GetElementPtrInst>(A))
11525 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011526 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000011527 return true;
11528
11529 // Otherwise they may not be equivalent.
11530 return false;
11531}
11532
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011533// If this instruction has two uses, one of which is a llvm.dbg.declare,
11534// return the llvm.dbg.declare.
11535DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11536 if (!V->hasNUses(2))
11537 return 0;
11538 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11539 UI != E; ++UI) {
11540 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11541 return DI;
11542 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11543 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11544 return DI;
11545 }
11546 }
11547 return 0;
11548}
11549
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011550Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11551 Value *Val = SI.getOperand(0);
11552 Value *Ptr = SI.getOperand(1);
11553
11554 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11555 EraseInstFromFunction(SI);
11556 ++NumCombined;
11557 return 0;
11558 }
11559
11560 // If the RHS is an alloca with a single use, zapify the store, making the
11561 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011562 // If the RHS is an alloca with a two uses, the other one being a
11563 // llvm.dbg.declare, zapify the store and the declare, making the
11564 // alloca dead. We must do this to prevent declare's from affecting
11565 // codegen.
11566 if (!SI.isVolatile()) {
11567 if (Ptr->hasOneUse()) {
11568 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011569 EraseInstFromFunction(SI);
11570 ++NumCombined;
11571 return 0;
11572 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011573 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11574 if (isa<AllocaInst>(GEP->getOperand(0))) {
11575 if (GEP->getOperand(0)->hasOneUse()) {
11576 EraseInstFromFunction(SI);
11577 ++NumCombined;
11578 return 0;
11579 }
11580 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11581 EraseInstFromFunction(*DI);
11582 EraseInstFromFunction(SI);
11583 ++NumCombined;
11584 return 0;
11585 }
11586 }
11587 }
11588 }
11589 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11590 EraseInstFromFunction(*DI);
11591 EraseInstFromFunction(SI);
11592 ++NumCombined;
11593 return 0;
11594 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011595 }
11596
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011597 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011598 if (TD) {
11599 unsigned KnownAlign =
11600 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11601 if (KnownAlign >
11602 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11603 SI.getAlignment()))
11604 SI.setAlignment(KnownAlign);
11605 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011606
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011607 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011608 // stores to the same location, separated by a few arithmetic operations. This
11609 // situation often occurs with bitfield accesses.
11610 BasicBlock::iterator BBI = &SI;
11611 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11612 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011613 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011614 // Don't count debug info directives, lest they affect codegen,
11615 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11616 // It is necessary for correctness to skip those that feed into a
11617 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011618 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011619 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011620 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011621 continue;
11622 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011623
11624 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11625 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011626 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11627 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011628 ++NumDeadStore;
11629 ++BBI;
11630 EraseInstFromFunction(*PrevSI);
11631 continue;
11632 }
11633 break;
11634 }
11635
11636 // If this is a load, we have to stop. However, if the loaded value is from
11637 // the pointer we're loading and is producing the pointer we're storing,
11638 // then *this* store is dead (X = load P; store X -> P).
11639 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011640 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11641 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011642 EraseInstFromFunction(SI);
11643 ++NumCombined;
11644 return 0;
11645 }
11646 // Otherwise, this is a load from some other location. Stores before it
11647 // may not be dead.
11648 break;
11649 }
11650
11651 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011652 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011653 break;
11654 }
11655
11656
11657 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11658
11659 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000011660 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011661 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011662 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011663 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000011664 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011665 ++NumCombined;
11666 }
11667 return 0; // Do not modify these!
11668 }
11669
11670 // store undef, Ptr -> noop
11671 if (isa<UndefValue>(Val)) {
11672 EraseInstFromFunction(SI);
11673 ++NumCombined;
11674 return 0;
11675 }
11676
11677 // If the pointer destination is a cast, see if we can fold the cast into the
11678 // source instead.
11679 if (isa<CastInst>(Ptr))
11680 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11681 return Res;
11682 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11683 if (CE->isCast())
11684 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11685 return Res;
11686
11687
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011688 // If this store is the last instruction in the basic block (possibly
11689 // excepting debug info instructions and the pointer bitcasts that feed
11690 // into them), and if the block ends with an unconditional branch, try
11691 // to move it to the successor block.
11692 BBI = &SI;
11693 do {
11694 ++BBI;
11695 } while (isa<DbgInfoIntrinsic>(BBI) ||
11696 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011697 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11698 if (BI->isUnconditional())
11699 if (SimplifyStoreAtEndOfBlock(SI))
11700 return 0; // xform done!
11701
11702 return 0;
11703}
11704
11705/// SimplifyStoreAtEndOfBlock - Turn things like:
11706/// if () { *P = v1; } else { *P = v2 }
11707/// into a phi node with a store in the successor.
11708///
11709/// Simplify things like:
11710/// *P = v1; if () { *P = v2; }
11711/// into a phi node with a store in the successor.
11712///
11713bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11714 BasicBlock *StoreBB = SI.getParent();
11715
11716 // Check to see if the successor block has exactly two incoming edges. If
11717 // so, see if the other predecessor contains a store to the same location.
11718 // if so, insert a PHI node (if needed) and move the stores down.
11719 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11720
11721 // Determine whether Dest has exactly two predecessors and, if so, compute
11722 // the other predecessor.
11723 pred_iterator PI = pred_begin(DestBB);
11724 BasicBlock *OtherBB = 0;
11725 if (*PI != StoreBB)
11726 OtherBB = *PI;
11727 ++PI;
11728 if (PI == pred_end(DestBB))
11729 return false;
11730
11731 if (*PI != StoreBB) {
11732 if (OtherBB)
11733 return false;
11734 OtherBB = *PI;
11735 }
11736 if (++PI != pred_end(DestBB))
11737 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011738
11739 // Bail out if all the relevant blocks aren't distinct (this can happen,
11740 // for example, if SI is in an infinite loop)
11741 if (StoreBB == DestBB || OtherBB == DestBB)
11742 return false;
11743
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011744 // Verify that the other block ends in a branch and is not otherwise empty.
11745 BasicBlock::iterator BBI = OtherBB->getTerminator();
11746 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11747 if (!OtherBr || BBI == OtherBB->begin())
11748 return false;
11749
11750 // If the other block ends in an unconditional branch, check for the 'if then
11751 // else' case. there is an instruction before the branch.
11752 StoreInst *OtherStore = 0;
11753 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011754 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011755 // Skip over debugging info.
11756 while (isa<DbgInfoIntrinsic>(BBI) ||
11757 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11758 if (BBI==OtherBB->begin())
11759 return false;
11760 --BBI;
11761 }
11762 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011763 OtherStore = dyn_cast<StoreInst>(BBI);
11764 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11765 return false;
11766 } else {
11767 // Otherwise, the other block ended with a conditional branch. If one of the
11768 // destinations is StoreBB, then we have the if/then case.
11769 if (OtherBr->getSuccessor(0) != StoreBB &&
11770 OtherBr->getSuccessor(1) != StoreBB)
11771 return false;
11772
11773 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11774 // if/then triangle. See if there is a store to the same ptr as SI that
11775 // lives in OtherBB.
11776 for (;; --BBI) {
11777 // Check to see if we find the matching store.
11778 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11779 if (OtherStore->getOperand(1) != SI.getOperand(1))
11780 return false;
11781 break;
11782 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011783 // If we find something that may be using or overwriting the stored
11784 // value, or if we run out of instructions, we can't do the xform.
11785 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011786 BBI == OtherBB->begin())
11787 return false;
11788 }
11789
11790 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011791 // make sure nothing reads or overwrites the stored value in
11792 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011793 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11794 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011795 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011796 return false;
11797 }
11798 }
11799
11800 // Insert a PHI node now if we need it.
11801 Value *MergedVal = OtherStore->getOperand(0);
11802 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011803 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011804 PN->reserveOperandSpace(2);
11805 PN->addIncoming(SI.getOperand(0), SI.getParent());
11806 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11807 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11808 }
11809
11810 // Advance to a place where it is safe to insert the new store and
11811 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011812 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011813 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11814 OtherStore->isVolatile()), *BBI);
11815
11816 // Nuke the old stores.
11817 EraseInstFromFunction(SI);
11818 EraseInstFromFunction(*OtherStore);
11819 ++NumCombined;
11820 return true;
11821}
11822
11823
11824Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11825 // Change br (not X), label True, label False to: br X, label False, True
11826 Value *X = 0;
11827 BasicBlock *TrueDest;
11828 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000011829 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011830 !isa<Constant>(X)) {
11831 // Swap Destinations and condition...
11832 BI.setCondition(X);
11833 BI.setSuccessor(0, FalseDest);
11834 BI.setSuccessor(1, TrueDest);
11835 return &BI;
11836 }
11837
11838 // Cannonicalize fcmp_one -> fcmp_oeq
11839 FCmpInst::Predicate FPred; Value *Y;
11840 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011841 TrueDest, FalseDest)) &&
11842 BI.getCondition()->hasOneUse())
11843 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11844 FPred == FCmpInst::FCMP_OGE) {
11845 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11846 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11847
11848 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011849 BI.setSuccessor(0, FalseDest);
11850 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011851 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011852 return &BI;
11853 }
11854
11855 // Cannonicalize icmp_ne -> icmp_eq
11856 ICmpInst::Predicate IPred;
11857 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011858 TrueDest, FalseDest)) &&
11859 BI.getCondition()->hasOneUse())
11860 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11861 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11862 IPred == ICmpInst::ICMP_SGE) {
11863 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11864 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11865 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011866 BI.setSuccessor(0, FalseDest);
11867 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011868 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011869 return &BI;
11870 }
11871
11872 return 0;
11873}
11874
11875Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11876 Value *Cond = SI.getCondition();
11877 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11878 if (I->getOpcode() == Instruction::Add)
11879 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11880 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11881 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000011882 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000011883 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011884 AddRHS));
11885 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000011886 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011887 return &SI;
11888 }
11889 }
11890 return 0;
11891}
11892
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011893Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011894 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011895
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011896 if (!EV.hasIndices())
11897 return ReplaceInstUsesWith(EV, Agg);
11898
11899 if (Constant *C = dyn_cast<Constant>(Agg)) {
11900 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011901 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011902
11903 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000011904 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011905
11906 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11907 // Extract the element indexed by the first index out of the constant
11908 Value *V = C->getOperand(*EV.idx_begin());
11909 if (EV.getNumIndices() > 1)
11910 // Extract the remaining indices out of the constant indexed by the
11911 // first index
11912 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11913 else
11914 return ReplaceInstUsesWith(EV, V);
11915 }
11916 return 0; // Can't handle other constants
11917 }
11918 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11919 // We're extracting from an insertvalue instruction, compare the indices
11920 const unsigned *exti, *exte, *insi, *inse;
11921 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11922 exte = EV.idx_end(), inse = IV->idx_end();
11923 exti != exte && insi != inse;
11924 ++exti, ++insi) {
11925 if (*insi != *exti)
11926 // The insert and extract both reference distinctly different elements.
11927 // This means the extract is not influenced by the insert, and we can
11928 // replace the aggregate operand of the extract with the aggregate
11929 // operand of the insert. i.e., replace
11930 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11931 // %E = extractvalue { i32, { i32 } } %I, 0
11932 // with
11933 // %E = extractvalue { i32, { i32 } } %A, 0
11934 return ExtractValueInst::Create(IV->getAggregateOperand(),
11935 EV.idx_begin(), EV.idx_end());
11936 }
11937 if (exti == exte && insi == inse)
11938 // Both iterators are at the end: Index lists are identical. Replace
11939 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11940 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11941 // with "i32 42"
11942 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11943 if (exti == exte) {
11944 // The extract list is a prefix of the insert list. i.e. replace
11945 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11946 // %E = extractvalue { i32, { i32 } } %I, 1
11947 // with
11948 // %X = extractvalue { i32, { i32 } } %A, 1
11949 // %E = insertvalue { i32 } %X, i32 42, 0
11950 // by switching the order of the insert and extract (though the
11951 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000011952 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11953 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011954 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11955 insi, inse);
11956 }
11957 if (insi == inse)
11958 // The insert list is a prefix of the extract list
11959 // We can simply remove the common indices from the extract and make it
11960 // operate on the inserted value instead of the insertvalue result.
11961 // i.e., replace
11962 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11963 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11964 // with
11965 // %E extractvalue { i32 } { i32 42 }, 0
11966 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11967 exti, exte);
11968 }
11969 // Can't simplify extracts from other values. Note that nested extracts are
11970 // already simplified implicitely by the above (extract ( extract (insert) )
11971 // will be translated into extract ( insert ( extract ) ) first and then just
11972 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011973 return 0;
11974}
11975
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011976/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11977/// is to leave as a vector operation.
11978static bool CheapToScalarize(Value *V, bool isConstant) {
11979 if (isa<ConstantAggregateZero>(V))
11980 return true;
11981 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11982 if (isConstant) return true;
11983 // If all elts are the same, we can extract.
11984 Constant *Op0 = C->getOperand(0);
11985 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11986 if (C->getOperand(i) != Op0)
11987 return false;
11988 return true;
11989 }
11990 Instruction *I = dyn_cast<Instruction>(V);
11991 if (!I) return false;
11992
11993 // Insert element gets simplified to the inserted element or is deleted if
11994 // this is constant idx extract element and its a constant idx insertelt.
11995 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11996 isa<ConstantInt>(I->getOperand(2)))
11997 return true;
11998 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11999 return true;
12000 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12001 if (BO->hasOneUse() &&
12002 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12003 CheapToScalarize(BO->getOperand(1), isConstant)))
12004 return true;
12005 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12006 if (CI->hasOneUse() &&
12007 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12008 CheapToScalarize(CI->getOperand(1), isConstant)))
12009 return true;
12010
12011 return false;
12012}
12013
12014/// Read and decode a shufflevector mask.
12015///
12016/// It turns undef elements into values that are larger than the number of
12017/// elements in the input.
12018static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12019 unsigned NElts = SVI->getType()->getNumElements();
12020 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12021 return std::vector<unsigned>(NElts, 0);
12022 if (isa<UndefValue>(SVI->getOperand(2)))
12023 return std::vector<unsigned>(NElts, 2*NElts);
12024
12025 std::vector<unsigned> Result;
12026 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012027 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12028 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012029 Result.push_back(NElts*2); // undef -> 8
12030 else
Gabor Greif17396002008-06-12 21:37:33 +000012031 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012032 return Result;
12033}
12034
12035/// FindScalarElement - Given a vector and an element number, see if the scalar
12036/// value is already around as a register, for example if it were inserted then
12037/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012038static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012039 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012040 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12041 const VectorType *PTy = cast<VectorType>(V->getType());
12042 unsigned Width = PTy->getNumElements();
12043 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012044 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012045
12046 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012047 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012048 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012049 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012050 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12051 return CP->getOperand(EltNo);
12052 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12053 // If this is an insert to a variable element, we don't know what it is.
12054 if (!isa<ConstantInt>(III->getOperand(2)))
12055 return 0;
12056 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12057
12058 // If this is an insert to the element we are looking for, return the
12059 // inserted value.
12060 if (EltNo == IIElt)
12061 return III->getOperand(1);
12062
12063 // Otherwise, the insertelement doesn't modify the value, recurse on its
12064 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012065 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012066 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012067 unsigned LHSWidth =
12068 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012069 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012070 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012071 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012072 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012073 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012074 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012075 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012076 }
12077
12078 // Otherwise, we don't know.
12079 return 0;
12080}
12081
12082Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012083 // If vector val is undef, replace extract with scalar undef.
12084 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012085 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012086
12087 // If vector val is constant 0, replace extract with scalar 0.
12088 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012089 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012090
12091 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012092 // If vector val is constant with all elements the same, replace EI with
12093 // that element. When the elements are not identical, we cannot replace yet
12094 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012095 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012096 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012097 if (C->getOperand(i) != op0) {
12098 op0 = 0;
12099 break;
12100 }
12101 if (op0)
12102 return ReplaceInstUsesWith(EI, op0);
12103 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012104
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012105 // If extracting a specified index from the vector, see if we can recursively
12106 // find a previously computed scalar that was inserted into the vector.
12107 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12108 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012109 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012110
12111 // If this is extracting an invalid index, turn this into undef, to avoid
12112 // crashing the code below.
12113 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012114 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012115
12116 // This instruction only demands the single element from the input vector.
12117 // If the input vector has a single use, simplify it based on this use
12118 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012119 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012120 APInt UndefElts(VectorWidth, 0);
12121 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012122 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012123 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012124 EI.setOperand(0, V);
12125 return &EI;
12126 }
12127 }
12128
Owen Anderson24be4c12009-07-03 00:17:18 +000012129 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012130 return ReplaceInstUsesWith(EI, Elt);
12131
12132 // If the this extractelement is directly using a bitcast from a vector of
12133 // the same number of elements, see if we can find the source element from
12134 // it. In this case, we will end up needing to bitcast the scalars.
12135 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12136 if (const VectorType *VT =
12137 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12138 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012139 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12140 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012141 return new BitCastInst(Elt, EI.getType());
12142 }
12143 }
12144
12145 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012146 // Push extractelement into predecessor operation if legal and
12147 // profitable to do so
12148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12149 if (I->hasOneUse() &&
12150 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12151 Value *newEI0 =
12152 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12153 EI.getName()+".lhs");
12154 Value *newEI1 =
12155 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12156 EI.getName()+".rhs");
12157 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012158 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012159 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012160 // Extracting the inserted element?
12161 if (IE->getOperand(2) == EI.getOperand(1))
12162 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12163 // If the inserted and extracted elements are constants, they must not
12164 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012165 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012166 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012167 EI.setOperand(0, IE->getOperand(0));
12168 return &EI;
12169 }
12170 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12171 // If this is extracting an element from a shufflevector, figure out where
12172 // it came from and extract from the appropriate input element instead.
12173 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12174 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12175 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012176 unsigned LHSWidth =
12177 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12178
12179 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012180 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012181 else if (SrcIdx < LHSWidth*2) {
12182 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012183 Src = SVI->getOperand(1);
12184 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012185 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012186 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012187 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012188 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12189 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012190 }
12191 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012192 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012193 }
12194 return 0;
12195}
12196
12197/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12198/// elements from either LHS or RHS, return the shuffle mask and true.
12199/// Otherwise, return false.
12200static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012201 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012202 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012203 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12204 "Invalid CollectSingleShuffleElements");
12205 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12206
12207 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012208 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012209 return true;
12210 } else if (V == LHS) {
12211 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012212 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012213 return true;
12214 } else if (V == RHS) {
12215 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012216 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012217 return true;
12218 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12219 // If this is an insert of an extract from some other vector, include it.
12220 Value *VecOp = IEI->getOperand(0);
12221 Value *ScalarOp = IEI->getOperand(1);
12222 Value *IdxOp = IEI->getOperand(2);
12223
12224 if (!isa<ConstantInt>(IdxOp))
12225 return false;
12226 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12227
12228 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12229 // Okay, we can handle this if the vector we are insertinting into is
12230 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012231 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012232 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012233 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012234 return true;
12235 }
12236 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12237 if (isa<ConstantInt>(EI->getOperand(1)) &&
12238 EI->getOperand(0)->getType() == V->getType()) {
12239 unsigned ExtractedIdx =
12240 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12241
12242 // This must be extracting from either LHS or RHS.
12243 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12244 // Okay, we can handle this if the vector we are insertinting into is
12245 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012246 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012247 // If so, update the mask to reflect the inserted value.
12248 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012249 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012250 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012251 } else {
12252 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012253 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012254 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012255
12256 }
12257 return true;
12258 }
12259 }
12260 }
12261 }
12262 }
12263 // TODO: Handle shufflevector here!
12264
12265 return false;
12266}
12267
12268/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12269/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12270/// that computes V and the LHS value of the shuffle.
12271static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012272 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012273 assert(isa<VectorType>(V->getType()) &&
12274 (RHS == 0 || V->getType() == RHS->getType()) &&
12275 "Invalid shuffle!");
12276 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12277
12278 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012279 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012280 return V;
12281 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012282 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012283 return V;
12284 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12285 // If this is an insert of an extract from some other vector, include it.
12286 Value *VecOp = IEI->getOperand(0);
12287 Value *ScalarOp = IEI->getOperand(1);
12288 Value *IdxOp = IEI->getOperand(2);
12289
12290 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12291 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12292 EI->getOperand(0)->getType() == V->getType()) {
12293 unsigned ExtractedIdx =
12294 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12295 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12296
12297 // Either the extracted from or inserted into vector must be RHSVec,
12298 // otherwise we'd end up with a shuffle of three inputs.
12299 if (EI->getOperand(0) == RHS || RHS == 0) {
12300 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012301 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012302 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012303 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012304 return V;
12305 }
12306
12307 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012308 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12309 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012310 // Everything but the extracted element is replaced with the RHS.
12311 for (unsigned i = 0; i != NumElts; ++i) {
12312 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012313 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012314 }
12315 return V;
12316 }
12317
12318 // If this insertelement is a chain that comes from exactly these two
12319 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012320 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12321 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012322 return EI->getOperand(0);
12323
12324 }
12325 }
12326 }
12327 // TODO: Handle shufflevector here!
12328
12329 // Otherwise, can't do anything fancy. Return an identity vector.
12330 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012331 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012332 return V;
12333}
12334
12335Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12336 Value *VecOp = IE.getOperand(0);
12337 Value *ScalarOp = IE.getOperand(1);
12338 Value *IdxOp = IE.getOperand(2);
12339
12340 // Inserting an undef or into an undefined place, remove this.
12341 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12342 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012343
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012344 // If the inserted element was extracted from some other vector, and if the
12345 // indexes are constant, try to turn this into a shufflevector operation.
12346 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12347 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12348 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012349 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012350 unsigned ExtractedIdx =
12351 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12352 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12353
12354 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12355 return ReplaceInstUsesWith(IE, VecOp);
12356
12357 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012358 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012359
12360 // If we are extracting a value from a vector, then inserting it right
12361 // back into the same place, just use the input vector.
12362 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12363 return ReplaceInstUsesWith(IE, VecOp);
12364
12365 // We could theoretically do this for ANY input. However, doing so could
12366 // turn chains of insertelement instructions into a chain of shufflevector
12367 // instructions, and right now we do not merge shufflevectors. As such,
12368 // only do this in a situation where it is clear that there is benefit.
12369 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12370 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12371 // the values of VecOp, except then one read from EIOp0.
12372 // Build a new shuffle mask.
12373 std::vector<Constant*> Mask;
12374 if (isa<UndefValue>(VecOp))
Owen Anderson35b47072009-08-13 21:58:54 +000012375 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012376 else {
12377 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson35b47072009-08-13 21:58:54 +000012378 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012379 NumVectorElts));
12380 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012381 Mask[InsertedIdx] =
Owen Anderson35b47072009-08-13 21:58:54 +000012382 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012383 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012384 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012385 }
12386
12387 // If this insertelement isn't used by some other insertelement, turn it
12388 // (and any insertelements it points to), into one big shuffle.
12389 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12390 std::vector<Constant*> Mask;
12391 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012392 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012393 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012394 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012395 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012396 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012397 }
12398 }
12399 }
12400
Eli Friedmanbefee262009-06-06 20:08:03 +000012401 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12402 APInt UndefElts(VWidth, 0);
12403 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12404 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12405 return &IE;
12406
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012407 return 0;
12408}
12409
12410
12411Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12412 Value *LHS = SVI.getOperand(0);
12413 Value *RHS = SVI.getOperand(1);
12414 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12415
12416 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012417
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012418 // Undefined shuffle mask -> undefined value.
12419 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012420 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012421
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012422 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012423
12424 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12425 return 0;
12426
Evan Cheng63295ab2009-02-03 10:05:09 +000012427 APInt UndefElts(VWidth, 0);
12428 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12429 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012430 LHS = SVI.getOperand(0);
12431 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012432 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012433 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012434
12435 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12436 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12437 if (LHS == RHS || isa<UndefValue>(LHS)) {
12438 if (isa<UndefValue>(LHS) && LHS == RHS) {
12439 // shuffle(undef,undef,mask) -> undef.
12440 return ReplaceInstUsesWith(SVI, LHS);
12441 }
12442
12443 // Remap any references to RHS to use LHS.
12444 std::vector<Constant*> Elts;
12445 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12446 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012447 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012448 else {
12449 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012450 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012451 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012452 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012453 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012454 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012455 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012456 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012457 }
12458 }
12459 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012460 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012461 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012462 LHS = SVI.getOperand(0);
12463 RHS = SVI.getOperand(1);
12464 MadeChange = true;
12465 }
12466
12467 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12468 bool isLHSID = true, isRHSID = true;
12469
12470 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12471 if (Mask[i] >= e*2) continue; // Ignore undef values.
12472 // Is this an identity shuffle of the LHS value?
12473 isLHSID &= (Mask[i] == i);
12474
12475 // Is this an identity shuffle of the RHS value?
12476 isRHSID &= (Mask[i]-e == i);
12477 }
12478
12479 // Eliminate identity shuffles.
12480 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12481 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12482
12483 // If the LHS is a shufflevector itself, see if we can combine it with this
12484 // one without producing an unusual shuffle. Here we are really conservative:
12485 // we are absolutely afraid of producing a shuffle mask not in the input
12486 // program, because the code gen may not be smart enough to turn a merged
12487 // shuffle into two specific shuffles: it may produce worse code. As such,
12488 // we only merge two shuffles if the result is one of the two input shuffle
12489 // masks. In this case, merging the shuffles just removes one instruction,
12490 // which we know is safe. This is good for things like turning:
12491 // (splat(splat)) -> splat.
12492 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12493 if (isa<UndefValue>(RHS)) {
12494 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12495
12496 std::vector<unsigned> NewMask;
12497 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12498 if (Mask[i] >= 2*e)
12499 NewMask.push_back(2*e);
12500 else
12501 NewMask.push_back(LHSMask[Mask[i]]);
12502
12503 // If the result mask is equal to the src shuffle or this shuffle mask, do
12504 // the replacement.
12505 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012506 unsigned LHSInNElts =
12507 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012508 std::vector<Constant*> Elts;
12509 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012510 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000012511 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012512 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000012513 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012514 }
12515 }
12516 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12517 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012518 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012519 }
12520 }
12521 }
12522
12523 return MadeChange ? &SVI : 0;
12524}
12525
12526
12527
12528
12529/// TryToSinkInstruction - Try to move the specified instruction from its
12530/// current block into the beginning of DestBlock, which can only happen if it's
12531/// safe to move the instruction past all of the instructions between it and the
12532/// end of its block.
12533static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12534 assert(I->hasOneUse() && "Invariants didn't hold!");
12535
12536 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012537 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012538 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012539
12540 // Do not sink alloca instructions out of the entry block.
12541 if (isa<AllocaInst>(I) && I->getParent() ==
12542 &DestBlock->getParent()->getEntryBlock())
12543 return false;
12544
12545 // We can only sink load instructions if there is nothing between the load and
12546 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012547 if (I->mayReadFromMemory()) {
12548 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012549 Scan != E; ++Scan)
12550 if (Scan->mayWriteToMemory())
12551 return false;
12552 }
12553
Dan Gohman514277c2008-05-23 21:05:58 +000012554 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012555
Dale Johannesen24339f12009-03-03 01:09:07 +000012556 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012557 I->moveBefore(InsertPos);
12558 ++NumSunkInst;
12559 return true;
12560}
12561
12562
12563/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12564/// all reachable code to the worklist.
12565///
12566/// This has a couple of tricks to make the code faster and more powerful. In
12567/// particular, we constant fold and DCE instructions as we go, to avoid adding
12568/// them to the worklist (this significantly speeds up instcombine on code where
12569/// many instructions are dead or constant). Additionally, if we find a branch
12570/// whose condition is a known constant, we only visit the reachable successors.
12571///
12572static void AddReachableCodeToWorklist(BasicBlock *BB,
12573 SmallPtrSet<BasicBlock*, 64> &Visited,
12574 InstCombiner &IC,
12575 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012576 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012577 Worklist.push_back(BB);
12578
12579 while (!Worklist.empty()) {
12580 BB = Worklist.back();
12581 Worklist.pop_back();
12582
12583 // We have now visited this block! If we've already been here, ignore it.
12584 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012585
12586 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012587 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12588 Instruction *Inst = BBI++;
12589
12590 // DCE instruction if trivially dead.
12591 if (isInstructionTriviallyDead(Inst)) {
12592 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000012593 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012594 Inst->eraseFromParent();
12595 continue;
12596 }
12597
12598 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012599 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012600 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12601 << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012602 Inst->replaceAllUsesWith(C);
12603 ++NumConstProp;
12604 Inst->eraseFromParent();
12605 continue;
12606 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012607
Devang Patel794140c2008-11-19 18:56:50 +000012608 // If there are two consecutive llvm.dbg.stoppoint calls then
12609 // it is likely that the optimizer deleted code in between these
12610 // two intrinsics.
12611 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12612 if (DBI_Next) {
12613 if (DBI_Prev
12614 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12615 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012616 IC.Worklist.Remove(DBI_Prev);
Devang Patel794140c2008-11-19 18:56:50 +000012617 DBI_Prev->eraseFromParent();
12618 }
12619 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012620 } else {
12621 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012622 }
12623
Chris Lattner3183fb62009-08-30 06:13:40 +000012624 IC.Worklist.Add(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012625 }
12626
12627 // Recursively visit successors. If this is a branch or switch on a
12628 // constant, only visit the reachable successor.
12629 TerminatorInst *TI = BB->getTerminator();
12630 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12631 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12632 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012633 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012634 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012635 continue;
12636 }
12637 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12638 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12639 // See if this is an explicit destination.
12640 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12641 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012642 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012643 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012644 continue;
12645 }
12646
12647 // Otherwise it is the default destination.
12648 Worklist.push_back(SI->getSuccessor(0));
12649 continue;
12650 }
12651 }
12652
12653 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12654 Worklist.push_back(TI->getSuccessor(i));
12655 }
12656}
12657
12658bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000012659 MadeIRChange = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012660 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012661
Daniel Dunbar005975c2009-07-25 00:23:56 +000012662 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12663 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012664
12665 {
12666 // Do a depth-first traversal of the function, populate the worklist with
12667 // the reachable instructions. Ignore blocks that are not reachable. Keep
12668 // track of which blocks we visit.
12669 SmallPtrSet<BasicBlock*, 64> Visited;
12670 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12671
12672 // Do a quick scan over the function. If we find any blocks that are
12673 // unreachable, remove any instructions inside of them. This prevents
12674 // the instcombine code from having to deal with some bad special cases.
12675 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12676 if (!Visited.count(BB)) {
12677 Instruction *Term = BB->getTerminator();
12678 while (Term != BB->begin()) { // Remove instrs bottom-up
12679 BasicBlock::iterator I = Term; --I;
12680
Chris Lattner8a6411c2009-08-23 04:37:46 +000012681 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000012682 // A debug intrinsic shouldn't force another iteration if we weren't
12683 // going to do one without it.
12684 if (!isa<DbgInfoIntrinsic>(I)) {
12685 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012686 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000012687 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012688 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000012689 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012690 I->eraseFromParent();
12691 }
12692 }
12693 }
12694
Chris Lattner5119c702009-08-30 05:55:36 +000012695 while (!Worklist.isEmpty()) {
12696 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012697 if (I == 0) continue; // skip null values.
12698
12699 // Check to see if we can DCE the instruction.
12700 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012701 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000012702 EraseInstFromFunction(*I);
12703 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012704 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012705 continue;
12706 }
12707
12708 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000012709 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012710 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012711
12712 // Add operands to the worklist.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012713 ReplaceInstUsesWith(*I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012714 ++NumConstProp;
Chris Lattner3183fb62009-08-30 06:13:40 +000012715 EraseInstFromFunction(*I);
Chris Lattner21d79e22009-08-31 06:57:37 +000012716 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012717 continue;
12718 }
12719
Eli Friedman5c619182009-07-15 22:13:34 +000012720 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000012721 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012722 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12723 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000012724 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12725 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012726 if (NewC != CE) {
12727 i->set(NewC);
Chris Lattner21d79e22009-08-31 06:57:37 +000012728 MadeIRChange = true;
Chris Lattnerf6d58862009-01-31 07:04:22 +000012729 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012730 }
12731
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012732 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012733 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012734 BasicBlock *BB = I->getParent();
12735 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12736 if (UserParent != BB) {
12737 bool UserIsSuccessor = false;
12738 // See if the user is one of our successors.
12739 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12740 if (*SI == UserParent) {
12741 UserIsSuccessor = true;
12742 break;
12743 }
12744
12745 // If the user is one of our immediate successors, and if that successor
12746 // only has us as a predecessors (we'd have to split the critical edge
12747 // otherwise), we can keep going.
12748 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12749 next(pred_begin(UserParent)) == pred_end(UserParent))
12750 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000012751 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012752 }
12753 }
12754
Chris Lattnerc7694852009-08-30 07:44:24 +000012755 // Now that we have an instruction, try combining it to simplify it.
12756 Builder->SetInsertPoint(I->getParent(), I);
12757
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012758#ifndef NDEBUG
12759 std::string OrigI;
12760#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000012761 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattnerc7694852009-08-30 07:44:24 +000012762
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012763 if (Instruction *Result = visit(*I)) {
12764 ++NumCombined;
12765 // Should we replace the old instruction with a new one?
12766 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012767 DEBUG(errs() << "IC: Old = " << *I << '\n'
12768 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012769
12770 // Everything uses the new instruction now.
12771 I->replaceAllUsesWith(Result);
12772
12773 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000012774 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000012775 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012776
12777 // Move the name to the new instruction first.
12778 Result->takeName(I);
12779
12780 // Insert the new instruction into the basic block...
12781 BasicBlock *InstParent = I->getParent();
12782 BasicBlock::iterator InsertPos = I;
12783
12784 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12785 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12786 ++InsertPos;
12787
12788 InstParent->getInstList().insert(InsertPos, Result);
12789
Chris Lattner3183fb62009-08-30 06:13:40 +000012790 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012791 } else {
12792#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000012793 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12794 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012795#endif
12796
12797 // If the instruction was modified, it's possible that it is now dead.
12798 // if so, remove it.
12799 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012800 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012801 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000012802 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000012803 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012804 }
12805 }
Chris Lattner21d79e22009-08-31 06:57:37 +000012806 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012807 }
12808 }
12809
Chris Lattner5119c702009-08-30 05:55:36 +000012810 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000012811 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012812}
12813
12814
12815bool InstCombiner::runOnFunction(Function &F) {
12816 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000012817 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012818
Chris Lattnerc7694852009-08-30 07:44:24 +000012819
12820 /// Builder - This is an IRBuilder that automatically inserts new
12821 /// instructions into the worklist when they are created.
12822 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12823 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12824 InstCombineIRInserter(Worklist));
12825 Builder = &TheBuilder;
12826
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012827 bool EverMadeChange = false;
12828
12829 // Iterate while there is work to do.
12830 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012831 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012832 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000012833
12834 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012835 return EverMadeChange;
12836}
12837
12838FunctionPass *llvm::createInstructionCombiningPass() {
12839 return new InstCombiner();
12840}