blob: 9147a9954aa4d2e81b456cc7974f2b5cb9672567 [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"
Victor Hernandez48c3c542009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
55#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057#include "llvm/Support/MathExtras.h"
58#include "llvm/Support/PatternMatch.h"
Chris Lattneree5839b2009-10-15 04:13:44 +000059#include "llvm/Support/TargetFolder.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061#include "llvm/ADT/DenseMap.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/Statistic.h"
65#include "llvm/ADT/STLExtras.h"
66#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000067#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068using namespace llvm;
69using namespace llvm::PatternMatch;
70
71STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75STATISTIC(NumSunkInst , "Number of instructions sunk");
76
77namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000078 /// InstCombineWorklist - This is the worklist management logic for
79 /// InstCombine.
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
83
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 public:
87 InstCombineWorklist() {}
88
89 bool isEmpty() const { return Worklist.empty(); }
90
91 /// Add - Add the specified instruction to the worklist if it isn't already
92 /// in it.
93 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +000096 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000097 }
Chris Lattner5119c702009-08-30 05:55:36 +000098 }
99
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
102 Add(I);
103 }
104
Chris Lattnerb5663c72009-10-12 03:58:40 +0000105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
116 }
117 }
118
Chris Lattner3183fb62009-08-30 06:13:40 +0000119 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
123
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
126
127 WorklistMap.erase(It);
128 }
129
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
132 Worklist.pop_back();
133 WorklistMap.erase(I);
134 return I;
135 }
136
Chris Lattner4796b622009-08-30 06:22:51 +0000137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
139 /// now.
140 ///
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 UI != UE; ++UI)
144 Add(cast<Instruction>(*UI));
145 }
146
Chris Lattner5119c702009-08-30 05:55:36 +0000147
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
150 void Zap() {
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152
153 // Do an explicit clear, this shrinks the map if needed.
154 WorklistMap.clear();
155 }
156 };
157} // end anonymous namespace.
158
159
160namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
166 public:
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172 Worklist.Add(I);
173 }
174 };
175} // end anonymous namespace
176
177
178namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 TargetData *TD;
182 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000183 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000185 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000186 InstCombineWorklist Worklist;
187
Chris Lattnerc7694852009-08-30 07:44:24 +0000188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +0000190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000191 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000192
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195
Owen Anderson175b6542009-07-22 00:24:57 +0000196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000198
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 public:
200 virtual bool runOnFunction(Function &F);
201
202 bool DoOneIteration(Function &F, unsigned ItNum);
203
204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 AU.addPreservedID(LCSSAID);
206 AU.setPreservesCFG();
207 }
208
Dan Gohmana80e2712009-07-21 23:21:54 +0000209 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210
211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
213 // Return Value:
214 // null - No change was made
215 // I - Change was made, I is still valid, I may be dead though
216 // otherwise - Change was made, replace I with returned instruction
217 //
218 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000219 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000221 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000223 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 Instruction *visitURem(BinaryOperator &I);
225 Instruction *visitSRem(BinaryOperator &I);
226 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000227 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 Instruction *commonRemTransforms(BinaryOperator &I);
229 Instruction *commonIRemTransforms(BinaryOperator &I);
230 Instruction *commonDivTransforms(BinaryOperator &I);
231 Instruction *commonIDivTransforms(BinaryOperator &I);
232 Instruction *visitUDiv(BinaryOperator &I);
233 Instruction *visitSDiv(BinaryOperator &I);
234 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000235 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000236 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000238 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000239 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000240 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000241 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 Instruction *visitOr (BinaryOperator &I);
243 Instruction *visitXor(BinaryOperator &I);
244 Instruction *visitShl(BinaryOperator &I);
245 Instruction *visitAShr(BinaryOperator &I);
246 Instruction *visitLShr(BinaryOperator &I);
247 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000248 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 Instruction *visitFCmpInst(FCmpInst &I);
251 Instruction *visitICmpInst(ICmpInst &I);
252 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
253 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254 Instruction *LHS,
255 ConstantInt *RHS);
256 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257 ConstantInt *DivRHS);
258
Dan Gohman17f46f72009-07-28 01:40:03 +0000259 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 ICmpInst::Predicate Cond, Instruction &I);
261 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
262 BinaryOperator &I);
263 Instruction *commonCastTransforms(CastInst &CI);
264 Instruction *commonIntCastTransforms(CastInst &CI);
265 Instruction *commonPointerCastTransforms(CastInst &CI);
266 Instruction *visitTrunc(TruncInst &CI);
267 Instruction *visitZExt(ZExtInst &CI);
268 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000269 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000271 Instruction *visitFPToUI(FPToUIInst &FI);
272 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 Instruction *visitUIToFP(CastInst &CI);
274 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000275 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000276 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 Instruction *visitBitCast(BitCastInst &CI);
278 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000280 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000281 Instruction *visitSelectInst(SelectInst &SI);
282 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 Instruction *visitCallInst(CallInst &CI);
284 Instruction *visitInvokeInst(InvokeInst &II);
285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
287 Instruction *visitAllocationInst(AllocationInst &AI);
288 Instruction *visitFreeInst(FreeInst &FI);
289 Instruction *visitLoadInst(LoadInst &LI);
290 Instruction *visitStoreInst(StoreInst &SI);
291 Instruction *visitBranchInst(BranchInst &BI);
292 Instruction *visitSwitchInst(SwitchInst &SI);
293 Instruction *visitInsertElementInst(InsertElementInst &IE);
294 Instruction *visitExtractElementInst(ExtractElementInst &EI);
295 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000296 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297
298 // visitInstruction - Specify what to return for unhandled instructions...
299 Instruction *visitInstruction(Instruction &I) { return 0; }
300
301 private:
302 Instruction *visitCallSite(CallSite CS);
303 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000304 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000305 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
306 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000307 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000308 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
309
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310
311 public:
312 // InsertNewInstBefore - insert an instruction New before instruction Old
313 // in the program. Add the new instruction to the worklist.
314 //
315 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
316 assert(New && New->getParent() == 0 &&
317 "New instruction already inserted into a basic block!");
318 BasicBlock *BB = Old.getParent();
319 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000320 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 return New;
322 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 // ReplaceInstUsesWith - This method is to be used when an instruction is
325 // found to be dead, replacable with another preexisting expression. Here
326 // we add all uses of I to the worklist, replace all uses of I with the new
327 // value, then return I, so that the inst combiner will know that I was
328 // modified.
329 //
330 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000331 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000332
333 // If we are replacing the instruction with itself, this must be in a
334 // segment of unreachable code, so just clobber the instruction.
335 if (&I == V)
336 V = UndefValue::get(I.getType());
337
338 I.replaceAllUsesWith(V);
339 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 }
341
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 // EraseInstFromFunction - When dealing with an instruction that has side
343 // effects or produces a void value, we can't rely on DCE to delete the
344 // instruction. Instead, visit methods should return the value returned by
345 // this function.
346 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000347 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000348
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000350 // Make sure that we reprocess all operands now that we reduced their
351 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000352 if (I.getNumOperands() < 8) {
353 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
354 if (Instruction *Op = dyn_cast<Instruction>(*i))
355 Worklist.Add(Op);
356 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000357 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000359 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 return 0; // Don't do anything with FI
361 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000362
363 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
364 APInt &KnownOne, unsigned Depth = 0) const {
365 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
366 }
367
368 bool MaskedValueIsZero(Value *V, const APInt &Mask,
369 unsigned Depth = 0) const {
370 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371 }
372 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
373 return llvm::ComputeNumSignBits(Op, TD, Depth);
374 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
376 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377
378 /// SimplifyCommutative - This performs a few simplifications for
379 /// commutative operators.
380 bool SimplifyCommutative(BinaryOperator &I);
381
382 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
383 /// most-complex to least-complex order.
384 bool SimplifyCompare(CmpInst &I);
385
Chris Lattner676c78e2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng63295ab2009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402
Chris Lattnerf7843b72009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
419
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420
421 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
422 ConstantInt *AndRHS, BinaryOperator &TheAnd);
423
424 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
425 bool isSub, Instruction &I);
426 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
427 bool isSigned, bool Inside, Instruction &IB);
428 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
429 Instruction *MatchBSwap(BinaryOperator &I);
430 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000431 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000432 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434
435 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000436
Dan Gohman8fd520a2009-06-15 22:12:54 +0000437 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000438 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000439 unsigned GetOrEnforceKnownAlignment(Value *V,
440 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000441
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 };
Chris Lattner5119c702009-08-30 05:55:36 +0000443} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444
Dan Gohman089efff2008-05-13 00:00:25 +0000445char InstCombiner::ID = 0;
446static RegisterPass<InstCombiner>
447X("instcombine", "Combine redundant instructions");
448
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449// getComplexity: Assign a complexity or rank value to LLVM Values...
450// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000451static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000453 if (BinaryOperator::isNeg(V) ||
454 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000455 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456 return 3;
457 return 4;
458 }
459 if (isa<Argument>(V)) return 3;
460 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
461}
462
463// isOnlyUse - Return true if this instruction will be deleted if we stop using
464// it.
465static bool isOnlyUse(Value *V) {
466 return V->hasOneUse() || isa<Constant>(V);
467}
468
469// getPromotedType - Return the specified type promoted as it would be to pass
470// though a va_arg area...
471static const Type *getPromotedType(const Type *Ty) {
472 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
473 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000474 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 }
476 return Ty;
477}
478
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000479/// getBitCastOperand - If the specified operand is a CastInst, a constant
480/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
481/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000483 if (Operator *O = dyn_cast<Operator>(V)) {
484 if (O->getOpcode() == Instruction::BitCast)
485 return O->getOperand(0);
486 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
487 if (GEP->hasAllZeroIndices())
488 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000489 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 return 0;
491}
492
493/// This function is a wrapper around CastInst::isEliminableCastPair. It
494/// simply extracts arguments and returns what that function returns.
495static Instruction::CastOps
496isEliminableCastPair(
497 const CastInst *CI, ///< The first cast instruction
498 unsigned opcode, ///< The opcode of the second cast instruction
499 const Type *DstTy, ///< The target type for the second cast instruction
500 TargetData *TD ///< The target data for pointer size
501) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000502
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
504 const Type *MidTy = CI->getType(); // B from above
505
506 // Get the opcodes of the two Cast instructions
507 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
508 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
509
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000510 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000511 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000512 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000513
514 // We don't want to form an inttoptr or ptrtoint that converts to an integer
515 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000516 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000517 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000518 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000519 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000520 Res = 0;
521
522 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523}
524
525/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
526/// in any code being generated. It does not require codegen if V is simple
527/// enough or if the cast can be folded into other casts.
528static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
529 const Type *Ty, TargetData *TD) {
530 if (V->getType() == Ty || isa<Constant>(V)) return false;
531
532 // If this is another cast that can be eliminated, it isn't codegen either.
533 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000534 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 return false;
536 return true;
537}
538
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539// SimplifyCommutative - This performs a few simplifications for commutative
540// operators:
541//
542// 1. Order operands such that they are listed from right (least complex) to
543// left (most complex). This puts constants before unary operators before
544// binary operators.
545//
546// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
547// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
548//
549bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
550 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000551 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 Changed = !I.swapOperands();
553
554 if (!I.isAssociative()) return Changed;
555 Instruction::BinaryOps Opcode = I.getOpcode();
556 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
557 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
558 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000559 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000560 cast<Constant>(I.getOperand(1)),
561 cast<Constant>(Op->getOperand(1)));
562 I.setOperand(0, Op->getOperand(0));
563 I.setOperand(1, Folded);
564 return true;
565 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
566 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
567 isOnlyUse(Op) && isOnlyUse(Op1)) {
568 Constant *C1 = cast<Constant>(Op->getOperand(1));
569 Constant *C2 = cast<Constant>(Op1->getOperand(1));
570
571 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000572 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000573 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574 Op1->getOperand(0),
575 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000576 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 I.setOperand(0, New);
578 I.setOperand(1, Folded);
579 return true;
580 }
581 }
582 return Changed;
583}
584
585/// SimplifyCompare - For a CmpInst this function just orders the operands
586/// so that theyare listed from right (least complex) to left (most complex).
587/// This puts constants before unary operators before binary operators.
588bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman5d138f92009-08-29 23:39:38 +0000589 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 return false;
591 I.swapOperands();
592 // Compare instructions are not associative so there's nothing else we can do.
593 return true;
594}
595
596// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
597// if the LHS is a constant zero (which is the 'negate' form).
598//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000599static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000600 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 return BinaryOperator::getNegArgument(V);
602
603 // Constants can be considered to be negated values if they can be folded.
604 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000605 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000606
607 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
608 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000609 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000610
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 return 0;
612}
613
Dan Gohman7ce405e2009-06-04 22:49:04 +0000614// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
615// instruction if the LHS is a constant negative zero (which is the 'negate'
616// form).
617//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000618static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000619 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000620 return BinaryOperator::getFNegArgument(V);
621
622 // Constants can be considered to be negated values if they can be folded.
623 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000624 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000625
626 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000628 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000629
630 return 0;
631}
632
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000633static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 if (BinaryOperator::isNot(V))
635 return BinaryOperator::getNotArgument(V);
636
637 // Constants can be considered to be not'ed values...
638 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000639 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 return 0;
641}
642
643// dyn_castFoldableMul - If this value is a multiply that can be folded into
644// other computations (because it has a constant operand), return the
645// non-constant operand of the multiply, and set CST to point to the multiplier.
646// Otherwise, return null.
647//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000648static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 if (V->hasOneUse() && V->getType()->isInteger())
650 if (Instruction *I = dyn_cast<Instruction>(V)) {
651 if (I->getOpcode() == Instruction::Mul)
652 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
653 return I->getOperand(0);
654 if (I->getOpcode() == Instruction::Shl)
655 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
656 // The multiplier is really 1 << CST.
657 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
658 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000659 CST = ConstantInt::get(V->getType()->getContext(),
660 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 return I->getOperand(0);
662 }
663 }
664 return 0;
665}
666
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000668static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000669 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000670 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671}
672/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000673static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000674 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000675 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000677/// MultiplyOverflows - True if the multiply can not be expressed in an int
678/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000679static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000680 uint32_t W = C1->getBitWidth();
681 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
682 if (sign) {
683 LHSExt.sext(W * 2);
684 RHSExt.sext(W * 2);
685 } else {
686 LHSExt.zext(W * 2);
687 RHSExt.zext(W * 2);
688 }
689
690 APInt MulExt = LHSExt * RHSExt;
691
692 if (sign) {
693 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
694 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
695 return MulExt.slt(Min) || MulExt.sgt(Max);
696 } else
697 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
698}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700
701/// ShrinkDemandedConstant - Check to see if the specified operand of the
702/// specified instruction is a constant integer. If so, check to see if there
703/// are any bits set in the constant that are not demanded. If so, shrink the
704/// constant and return true.
705static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000706 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 assert(I && "No instruction?");
708 assert(OpNo < I->getNumOperands() && "Operand index too large");
709
710 // If the operand is not a constant integer, nothing to do.
711 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
712 if (!OpC) return false;
713
714 // If there are no bits set that aren't demanded, nothing to do.
715 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
716 if ((~Demanded & OpC->getValue()) == 0)
717 return false;
718
719 // This instruction is producing bits that are not demanded. Shrink the RHS.
720 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000721 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 return true;
723}
724
725// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
726// set of known zero and one bits, compute the maximum and minimum values that
727// could have the specified known zero and known one bits, returning them in
728// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000729static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 const APInt& KnownOne,
731 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000732 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
733 KnownZero.getBitWidth() == Min.getBitWidth() &&
734 KnownZero.getBitWidth() == Max.getBitWidth() &&
735 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 APInt UnknownBits = ~(KnownZero|KnownOne);
737
738 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
739 // bit if it is unknown.
740 Min = KnownOne;
741 Max = KnownOne|UnknownBits;
742
Dan Gohman7934d592009-04-25 17:12:48 +0000743 if (UnknownBits.isNegative()) { // Sign bit is unknown
744 Min.set(Min.getBitWidth()-1);
745 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 }
747}
748
749// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
750// a set of known zero and one bits, compute the maximum and minimum values that
751// could have the specified known zero and known one bits, returning them in
752// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000753static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000754 const APInt &KnownOne,
755 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000756 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
757 KnownZero.getBitWidth() == Min.getBitWidth() &&
758 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
760 APInt UnknownBits = ~(KnownZero|KnownOne);
761
762 // The minimum value is when the unknown bits are all zeros.
763 Min = KnownOne;
764 // The maximum value is when the unknown bits are all ones.
765 Max = KnownOne|UnknownBits;
766}
767
Chris Lattner676c78e2009-01-31 08:15:18 +0000768/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
769/// SimplifyDemandedBits knows about. See if the instruction has any
770/// properties that allow us to simplify its operands.
771bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000772 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000773 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
774 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
775
776 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
777 KnownZero, KnownOne, 0);
778 if (V == 0) return false;
779 if (V == &Inst) return true;
780 ReplaceInstUsesWith(Inst, V);
781 return true;
782}
783
784/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
785/// specified instruction operand if possible, updating it in place. It returns
786/// true if it made any change and false otherwise.
787bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
788 APInt &KnownZero, APInt &KnownOne,
789 unsigned Depth) {
790 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
791 KnownZero, KnownOne, Depth);
792 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000793 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000794 return true;
795}
796
797
798/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
799/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800/// that only the bits set in DemandedMask of the result of V are ever used
801/// downstream. Consequently, depending on the mask and V, it may be possible
802/// to replace V with a constant or one of its operands. In such cases, this
803/// function does the replacement and returns true. In all other cases, it
804/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000805/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806/// to be zero in the expression. These are provided to potentially allow the
807/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
808/// the expression. KnownOne and KnownZero always follow the invariant that
809/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
810/// the bits in KnownOne and KnownZero may only be accurate for those bits set
811/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
812/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000813///
814/// This returns null if it did not change anything and it permits no
815/// simplification. This returns V itself if it did some simplification of V's
816/// operands based on the information about what bits are demanded. This returns
817/// some other non-null value if it found out that V is equal to another value
818/// in the context where the specified bits are demanded, but not for all users.
819Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
820 APInt &KnownZero, APInt &KnownOne,
821 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 assert(V != 0 && "Null pointer of Value???");
823 assert(Depth <= 6 && "Limit Search Depth");
824 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000825 const Type *VTy = V->getType();
826 assert((TD || !isa<PointerType>(VTy)) &&
827 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000828 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
829 (!VTy->isIntOrIntVector() ||
830 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000831 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000833 "Value *V, DemandedMask, KnownZero and KnownOne "
834 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
836 // We know all of the bits for a constant!
837 KnownOne = CI->getValue() & DemandedMask;
838 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000839 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000840 }
Dan Gohman7934d592009-04-25 17:12:48 +0000841 if (isa<ConstantPointerNull>(V)) {
842 // We know all of the bits for a constant!
843 KnownOne.clear();
844 KnownZero = DemandedMask;
845 return 0;
846 }
847
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000848 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000850 if (DemandedMask == 0) { // Not demanding any bits from V.
851 if (isa<UndefValue>(V))
852 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000853 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 }
855
Chris Lattner08817332009-01-31 08:24:16 +0000856 if (Depth == 6) // Limit search depth.
857 return 0;
858
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000859 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
860 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
861
Dan Gohman7934d592009-04-25 17:12:48 +0000862 Instruction *I = dyn_cast<Instruction>(V);
863 if (!I) {
864 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
865 return 0; // Only analyze instructions.
866 }
867
Chris Lattner08817332009-01-31 08:24:16 +0000868 // If there are multiple uses of this value and we aren't at the root, then
869 // we can't do any simplifications of the operands, because DemandedMask
870 // only reflects the bits demanded by *one* of the users.
871 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000872 // Despite the fact that we can't simplify this instruction in all User's
873 // context, we can at least compute the knownzero/knownone bits, and we can
874 // do simplifications that apply to *just* the one user if we know that
875 // this instruction has a simpler value in that context.
876 if (I->getOpcode() == Instruction::And) {
877 // If either the LHS or the RHS are Zero, the result is zero.
878 ComputeMaskedBits(I->getOperand(1), DemandedMask,
879 RHSKnownZero, RHSKnownOne, Depth+1);
880 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
881 LHSKnownZero, LHSKnownOne, Depth+1);
882
883 // If all of the demanded bits are known 1 on one side, return the other.
884 // These bits cannot contribute to the result of the 'and' in this
885 // context.
886 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
887 (DemandedMask & ~LHSKnownZero))
888 return I->getOperand(0);
889 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
890 (DemandedMask & ~RHSKnownZero))
891 return I->getOperand(1);
892
893 // If all of the demanded bits in the inputs are known zeros, return zero.
894 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000895 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000896
897 } else if (I->getOpcode() == Instruction::Or) {
898 // We can simplify (X|Y) -> X or Y in the user's context if we know that
899 // only bits from X or Y are demanded.
900
901 // If either the LHS or the RHS are One, the result is One.
902 ComputeMaskedBits(I->getOperand(1), DemandedMask,
903 RHSKnownZero, RHSKnownOne, Depth+1);
904 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
905 LHSKnownZero, LHSKnownOne, Depth+1);
906
907 // If all of the demanded bits are known zero on one side, return the
908 // other. These bits cannot contribute to the result of the 'or' in this
909 // context.
910 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
911 (DemandedMask & ~LHSKnownOne))
912 return I->getOperand(0);
913 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
914 (DemandedMask & ~RHSKnownOne))
915 return I->getOperand(1);
916
917 // If all of the potentially set bits on one side are known to be set on
918 // the other side, just use the 'other' side.
919 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
920 (DemandedMask & (~RHSKnownZero)))
921 return I->getOperand(0);
922 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
923 (DemandedMask & (~LHSKnownZero)))
924 return I->getOperand(1);
925 }
926
Chris Lattner08817332009-01-31 08:24:16 +0000927 // Compute the KnownZero/KnownOne bits to simplify things downstream.
928 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
929 return 0;
930 }
931
932 // If this is the root being simplified, allow it to have multiple uses,
933 // just set the DemandedMask to all bits so that we can try to simplify the
934 // operands. This allows visitTruncInst (for example) to simplify the
935 // operand of a trunc without duplicating all the logic below.
936 if (Depth == 0 && !V->hasOneUse())
937 DemandedMask = APInt::getAllOnesValue(BitWidth);
938
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000940 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000941 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000942 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 case Instruction::And:
944 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000945 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1) ||
947 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000949 return I;
950 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
951 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952
953 // If all of the demanded bits are known 1 on one side, return the other.
954 // These bits cannot contribute to the result of the 'and'.
955 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
956 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000957 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
959 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000960 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961
962 // If all of the demanded bits in the inputs are known zeros, return zero.
963 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000964 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965
966 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000967 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000968 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969
970 // Output known-1 bits are only known if set in both the LHS & RHS.
971 RHSKnownOne &= LHSKnownOne;
972 // Output known-0 are known to be clear if zero in either the LHS | RHS.
973 RHSKnownZero |= LHSKnownZero;
974 break;
975 case Instruction::Or:
976 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'or'.
987 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
988 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000989 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
991 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000992 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // If all of the potentially set bits on one side are known to be set on
995 // the other side, just use the 'other' side.
996 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
997 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000998 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1000 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001001 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002
1003 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001004 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001005 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006
1007 // Output known-0 bits are only known if clear in both the LHS & RHS.
1008 RHSKnownZero &= LHSKnownZero;
1009 // Output known-1 are known to be set if set in either the LHS | RHS.
1010 RHSKnownOne |= LHSKnownOne;
1011 break;
1012 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001013 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1014 RHSKnownZero, RHSKnownOne, Depth+1) ||
1015 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001017 return I;
1018 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1019 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020
1021 // If all of the demanded bits are known zero on one side, return the other.
1022 // These bits cannot contribute to the result of the 'xor'.
1023 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001024 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001026 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027
1028 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1029 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1030 (RHSKnownOne & LHSKnownOne);
1031 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1032 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1033 (RHSKnownOne & LHSKnownZero);
1034
1035 // If all of the demanded bits are known to be zero on one side or the
1036 // other, turn this into an *inclusive* or.
1037 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001038 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1039 Instruction *Or =
1040 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1041 I->getName());
1042 return InsertNewInstBefore(Or, *I);
1043 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044
1045 // If all of the demanded bits on one side are known, and all of the set
1046 // bits on that side are also known to be set on the other side, turn this
1047 // into an AND, as we know the bits will be cleared.
1048 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1049 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1050 // all known
1051 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001052 Constant *AndC = Constant::getIntegerValue(VTy,
1053 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001055 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 }
1058 }
1059
1060 // If the RHS is a constant, see if we can simplify it.
1061 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001062 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001063 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064
Chris Lattnereefa89c2009-10-11 22:22:13 +00001065 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1066 // are flipping are known to be set, then the xor is just resetting those
1067 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1068 // simplifying both of them.
1069 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1070 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1071 isa<ConstantInt>(I->getOperand(1)) &&
1072 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1073 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1074 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1075 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1076 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1077
1078 Constant *AndC =
1079 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1080 Instruction *NewAnd =
1081 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1082 InsertNewInstBefore(NewAnd, *I);
1083
1084 Constant *XorC =
1085 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1086 Instruction *NewXor =
1087 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1088 return InsertNewInstBefore(NewXor, *I);
1089 }
1090
1091
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 RHSKnownZero = KnownZeroOut;
1093 RHSKnownOne = KnownOneOut;
1094 break;
1095 }
1096 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001097 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1098 RHSKnownZero, RHSKnownOne, Depth+1) ||
1099 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001101 return I;
1102 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1103 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104
1105 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001106 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1107 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001108 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109
1110 // Only known if known in both the LHS and RHS.
1111 RHSKnownOne &= LHSKnownOne;
1112 RHSKnownZero &= LHSKnownZero;
1113 break;
1114 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001115 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 DemandedMask.zext(truncBf);
1117 RHSKnownZero.zext(truncBf);
1118 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001119 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001121 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 DemandedMask.trunc(BitWidth);
1123 RHSKnownZero.trunc(BitWidth);
1124 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001125 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 break;
1127 }
1128 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001129 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001130 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001131
1132 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1133 if (const VectorType *SrcVTy =
1134 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1135 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1136 // Don't touch a bitcast between vectors of different element counts.
1137 return false;
1138 } else
1139 // Don't touch a scalar-to-vector bitcast.
1140 return false;
1141 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1142 // Don't touch a vector-to-scalar bitcast.
1143 return false;
1144
Chris Lattner676c78e2009-01-31 08:15:18 +00001145 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001147 return I;
1148 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 break;
1150 case Instruction::ZExt: {
1151 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001152 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153
1154 DemandedMask.trunc(SrcBitWidth);
1155 RHSKnownZero.trunc(SrcBitWidth);
1156 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001157 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001159 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 DemandedMask.zext(BitWidth);
1161 RHSKnownZero.zext(BitWidth);
1162 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001163 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 // The top bits are known to be zero.
1165 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166 break;
1167 }
1168 case Instruction::SExt: {
1169 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001170 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171
1172 APInt InputDemandedBits = DemandedMask &
1173 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174
1175 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1176 // If any of the sign extended bits are demanded, we know that the sign
1177 // bit is demanded.
1178 if ((NewBits & DemandedMask) != 0)
1179 InputDemandedBits.set(SrcBitWidth-1);
1180
1181 InputDemandedBits.trunc(SrcBitWidth);
1182 RHSKnownZero.trunc(SrcBitWidth);
1183 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001184 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001186 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 InputDemandedBits.zext(BitWidth);
1188 RHSKnownZero.zext(BitWidth);
1189 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001190 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191
1192 // If the sign bit of the input is known set or clear, then we know the
1193 // top bits of the result.
1194
1195 // If the input sign bit is known zero, or if the NewBits are not demanded
1196 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001197 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001199 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1200 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1202 RHSKnownOne |= NewBits;
1203 }
1204 break;
1205 }
1206 case Instruction::Add: {
1207 // Figure out what the input bits are. If the top bits of the and result
1208 // are not demanded, then the add doesn't demand them from its input
1209 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001210 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211
1212 // If there is a constant on the RHS, there are a variety of xformations
1213 // we can do.
1214 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215 // If null, this should be simplified elsewhere. Some of the xforms here
1216 // won't work if the RHS is zero.
1217 if (RHS->isZero())
1218 break;
1219
1220 // If the top bit of the output is demanded, demand everything from the
1221 // input. Otherwise, we demand all the input bits except NLZ top bits.
1222 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1223
1224 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001225 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001227 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228
1229 // If the RHS of the add has bits set that can't affect the input, reduce
1230 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001231 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001232 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233
1234 // Avoid excess work.
1235 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1236 break;
1237
1238 // Turn it into OR if input bits are zero.
1239 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001241 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001243 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 }
1245
1246 // We can say something about the output known-zero and known-one bits,
1247 // depending on potential carries from the input constant and the
1248 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1249 // bits set and the RHS constant is 0x01001, then we know we have a known
1250 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1251
1252 // To compute this, we first compute the potential carry bits. These are
1253 // the bits which may be modified. I'm not aware of a better way to do
1254 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001255 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1257
1258 // Now that we know which bits have carries, compute the known-1/0 sets.
1259
1260 // Bits are known one if they are known zero in one operand and one in the
1261 // other, and there is no input carry.
1262 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1263 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1264
1265 // Bits are known zero if they are known zero in both operands and there
1266 // is no input carry.
1267 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1268 } else {
1269 // If the high-bits of this ADD are not demanded, then it does not demand
1270 // the high bits of its LHS or RHS.
1271 if (DemandedMask[BitWidth-1] == 0) {
1272 // Right fill the mask of bits for this ADD to demand the most
1273 // significant bit and all those below it.
1274 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001275 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1276 LHSKnownZero, LHSKnownOne, Depth+1) ||
1277 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001279 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 }
1281 }
1282 break;
1283 }
1284 case Instruction::Sub:
1285 // If the high-bits of this SUB are not demanded, then it does not demand
1286 // the high bits of its LHS or RHS.
1287 if (DemandedMask[BitWidth-1] == 0) {
1288 // Right fill the mask of bits for this SUB to demand the most
1289 // significant bit and all those below it.
1290 uint32_t NLZ = DemandedMask.countLeadingZeros();
1291 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001292 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1293 LHSKnownZero, LHSKnownOne, Depth+1) ||
1294 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001296 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001298 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1299 // the known zeros and ones.
1300 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 break;
1302 case Instruction::Shl:
1303 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1304 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1305 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001306 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001308 return I;
1309 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 RHSKnownZero <<= ShiftAmt;
1311 RHSKnownOne <<= ShiftAmt;
1312 // low bits known zero.
1313 if (ShiftAmt)
1314 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1315 }
1316 break;
1317 case Instruction::LShr:
1318 // For a logical shift right
1319 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1320 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1321
1322 // Unsigned shift right.
1323 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001324 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001326 return I;
1327 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330 if (ShiftAmt) {
1331 // Compute the new bits that are at the top now.
1332 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1333 RHSKnownZero |= HighBits; // high bits known zero.
1334 }
1335 }
1336 break;
1337 case Instruction::AShr:
1338 // If this is an arithmetic shift right and only the low-bit is set, we can
1339 // always convert this into a logical shr, even if the shift amount is
1340 // variable. The low bit of the shift cannot be an input sign bit unless
1341 // the shift amount is >= the size of the datatype, which is undefined.
1342 if (DemandedMask == 1) {
1343 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001344 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001346 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 }
1348
1349 // If the sign bit is the only bit demanded by this ashr, then there is no
1350 // need to do it, the shift doesn't change the high bit.
1351 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001352 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353
1354 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1355 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1356
1357 // Signed shift right.
1358 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1359 // If any of the "high bits" are demanded, we should set the sign bit as
1360 // demanded.
1361 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1362 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001363 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001365 return I;
1366 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 // Compute the new bits that are at the top now.
1368 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1369 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1370 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371
1372 // Handle the sign bits.
1373 APInt SignBit(APInt::getSignBit(BitWidth));
1374 // Adjust to where it is now in the mask.
1375 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1376
1377 // If the input sign bit is known to be zero, or if none of the top bits
1378 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001379 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 (HighBits & ~DemandedMask) == HighBits) {
1381 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001382 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001384 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1386 RHSKnownOne |= HighBits;
1387 }
1388 }
1389 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001390 case Instruction::SRem:
1391 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001392 APInt RA = Rem->getValue().abs();
1393 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001394 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001395 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001396
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001397 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001398 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001399 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001400 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001401 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001402
1403 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1404 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001405
1406 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001407
Chris Lattner676c78e2009-01-31 08:15:18 +00001408 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001409 }
1410 }
1411 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001412 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001413 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1414 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001415 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1416 KnownZero2, KnownOne2, Depth+1) ||
1417 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001418 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001419 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001420
Chris Lattneree5417c2009-01-21 18:09:24 +00001421 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001422 Leaders = std::max(Leaders,
1423 KnownZero2.countLeadingOnes());
1424 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001425 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 }
Chris Lattner989ba312008-06-18 04:33:20 +00001427 case Instruction::Call:
1428 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1429 switch (II->getIntrinsicID()) {
1430 default: break;
1431 case Intrinsic::bswap: {
1432 // If the only bits demanded come from one byte of the bswap result,
1433 // just shift the input byte into position to eliminate the bswap.
1434 unsigned NLZ = DemandedMask.countLeadingZeros();
1435 unsigned NTZ = DemandedMask.countTrailingZeros();
1436
1437 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1438 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1439 // have 14 leading zeros, round to 8.
1440 NLZ &= ~7;
1441 NTZ &= ~7;
1442 // If we need exactly one byte, we can do this transformation.
1443 if (BitWidth-NLZ-NTZ == 8) {
1444 unsigned ResultBit = NTZ;
1445 unsigned InputBit = BitWidth-NTZ-8;
1446
1447 // Replace this with either a left or right shift to get the byte into
1448 // the right place.
1449 Instruction *NewVal;
1450 if (InputBit > ResultBit)
1451 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001452 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001453 else
1454 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001455 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001456 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001457 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001458 }
1459
1460 // TODO: Could compute known zero/one bits based on the input.
1461 break;
1462 }
1463 }
1464 }
Chris Lattner4946e222008-06-18 18:11:55 +00001465 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001466 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001467 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468
1469 // If the client is only demanding bits that we know, return the known
1470 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001471 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1472 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 return false;
1474}
1475
1476
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001477/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001478/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479/// actually used by the caller. This method analyzes which elements of the
1480/// operand are undef and returns that information in UndefElts.
1481///
1482/// If the information about demanded elements can be used to simplify the
1483/// operation, the operation is simplified, then the resultant value is
1484/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001485Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1486 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 unsigned Depth) {
1488 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001489 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001490 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491
1492 if (isa<UndefValue>(V)) {
1493 // If the entire vector is undefined, just return this info.
1494 UndefElts = EltMask;
1495 return 0;
1496 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1497 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001498 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001500
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501 UndefElts = 0;
1502 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1503 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001504 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505
1506 std::vector<Constant*> Elts;
1507 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001508 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001510 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1512 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001513 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514 } else { // Otherwise, defined.
1515 Elts.push_back(CP->getOperand(i));
1516 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001517
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001519 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520 return NewCP != CP ? NewCP : 0;
1521 } else if (isa<ConstantAggregateZero>(V)) {
1522 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1523 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001524
1525 // Check if this is identity. If so, return 0 since we are not simplifying
1526 // anything.
1527 if (DemandedElts == ((1ULL << VWidth) -1))
1528 return 0;
1529
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001531 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001532 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001534 for (unsigned i = 0; i != VWidth; ++i) {
1535 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1536 Elts.push_back(Elt);
1537 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001539 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 }
1541
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001542 // Limit search depth.
1543 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001544 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001545
1546 // If multiple users are using the root value, procede with
1547 // simplification conservatively assuming that all elements
1548 // are needed.
1549 if (!V->hasOneUse()) {
1550 // Quit if we find multiple users of a non-root value though.
1551 // They'll be handled when it's their turn to be visited by
1552 // the main instcombine process.
1553 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001555 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001556
1557 // Conservatively assume that all elements are needed.
1558 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559 }
1560
1561 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001562 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563
1564 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001565 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566 Value *TmpV;
1567 switch (I->getOpcode()) {
1568 default: break;
1569
1570 case Instruction::InsertElement: {
1571 // If this is a variable index, we don't know which element it overwrites.
1572 // demand exactly the same input as we produce.
1573 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1574 if (Idx == 0) {
1575 // Note that we can't propagate undef elt info, because we don't know
1576 // which elt is getting updated.
1577 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1578 UndefElts2, Depth+1);
1579 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1580 break;
1581 }
1582
1583 // If this is inserting an element that isn't demanded, remove this
1584 // insertelement.
1585 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001586 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1587 Worklist.Add(I);
1588 return I->getOperand(0);
1589 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001590
1591 // Otherwise, the element inserted overwrites whatever was there, so the
1592 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001593 APInt DemandedElts2 = DemandedElts;
1594 DemandedElts2.clear(IdxNo);
1595 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 UndefElts, Depth+1);
1597 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001600 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001601 break;
1602 }
1603 case Instruction::ShuffleVector: {
1604 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001605 uint64_t LHSVWidth =
1606 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001607 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001608 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001609 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001610 unsigned MaskVal = Shuffle->getMaskValue(i);
1611 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001612 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001613 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001614 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001615 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001616 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001617 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001618 }
1619 }
1620 }
1621
Nate Begemanb4d176f2009-02-11 22:36:25 +00001622 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001623 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001624 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001625 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626
Nate Begemanb4d176f2009-02-11 22:36:25 +00001627 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001628 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1629 UndefElts3, Depth+1);
1630 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1631
1632 bool NewUndefElts = false;
1633 for (unsigned i = 0; i < VWidth; i++) {
1634 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001635 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001636 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001637 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001638 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001639 NewUndefElts = true;
1640 UndefElts.set(i);
1641 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001642 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001643 if (UndefElts3[MaskVal - LHSVWidth]) {
1644 NewUndefElts = true;
1645 UndefElts.set(i);
1646 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001647 }
1648 }
1649
1650 if (NewUndefElts) {
1651 // Add additional discovered undefs.
1652 std::vector<Constant*> Elts;
1653 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001654 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001655 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001656 else
Owen Anderson35b47072009-08-13 21:58:54 +00001657 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001658 Shuffle->getMaskValue(i)));
1659 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001660 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001661 MadeChange = true;
1662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 break;
1664 }
1665 case Instruction::BitCast: {
1666 // Vector->vector casts only.
1667 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1668 if (!VTy) break;
1669 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001670 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 unsigned Ratio;
1672
1673 if (VWidth == InVWidth) {
1674 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1675 // elements as are demanded of us.
1676 Ratio = 1;
1677 InputDemandedElts = DemandedElts;
1678 } else if (VWidth > InVWidth) {
1679 // Untested so far.
1680 break;
1681
1682 // If there are more elements in the result than there are in the source,
1683 // then an input element is live if any of the corresponding output
1684 // elements are live.
1685 Ratio = VWidth/InVWidth;
1686 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001687 if (DemandedElts[OutIdx])
1688 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 }
1690 } else {
1691 // Untested so far.
1692 break;
1693
1694 // If there are more elements in the source than there are in the result,
1695 // then an input element is live if the corresponding output element is
1696 // live.
1697 Ratio = InVWidth/VWidth;
1698 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001699 if (DemandedElts[InIdx/Ratio])
1700 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 }
1702
1703 // div/rem demand all inputs, because they don't want divide by zero.
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1705 UndefElts2, Depth+1);
1706 if (TmpV) {
1707 I->setOperand(0, TmpV);
1708 MadeChange = true;
1709 }
1710
1711 UndefElts = UndefElts2;
1712 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001713 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714 // If there are more elements in the result than there are in the source,
1715 // then an output element is undef if the corresponding input element is
1716 // undef.
1717 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001718 if (UndefElts2[OutIdx/Ratio])
1719 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001721 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 // If there are more elements in the source than there are in the result,
1723 // then a result element is undef if all of the corresponding input
1724 // elements are undef.
1725 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1726 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001727 if (!UndefElts2[InIdx]) // Not undef?
1728 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729 }
1730 break;
1731 }
1732 case Instruction::And:
1733 case Instruction::Or:
1734 case Instruction::Xor:
1735 case Instruction::Add:
1736 case Instruction::Sub:
1737 case Instruction::Mul:
1738 // div/rem demand all inputs, because they don't want divide by zero.
1739 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1740 UndefElts, Depth+1);
1741 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1742 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1743 UndefElts2, Depth+1);
1744 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1745
1746 // Output elements are undefined if both are undefined. Consider things
1747 // like undef&0. The result is known zero, not undef.
1748 UndefElts &= UndefElts2;
1749 break;
1750
1751 case Instruction::Call: {
1752 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1753 if (!II) break;
1754 switch (II->getIntrinsicID()) {
1755 default: break;
1756
1757 // Binary vector operations that work column-wise. A dest element is a
1758 // function of the corresponding input elements from the two inputs.
1759 case Intrinsic::x86_sse_sub_ss:
1760 case Intrinsic::x86_sse_mul_ss:
1761 case Intrinsic::x86_sse_min_ss:
1762 case Intrinsic::x86_sse_max_ss:
1763 case Intrinsic::x86_sse2_sub_sd:
1764 case Intrinsic::x86_sse2_mul_sd:
1765 case Intrinsic::x86_sse2_min_sd:
1766 case Intrinsic::x86_sse2_max_sd:
1767 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1768 UndefElts, Depth+1);
1769 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1770 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1771 UndefElts2, Depth+1);
1772 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1773
1774 // If only the low elt is demanded and this is a scalarizable intrinsic,
1775 // scalarize it now.
1776 if (DemandedElts == 1) {
1777 switch (II->getIntrinsicID()) {
1778 default: break;
1779 case Intrinsic::x86_sse_sub_ss:
1780 case Intrinsic::x86_sse_mul_ss:
1781 case Intrinsic::x86_sse2_sub_sd:
1782 case Intrinsic::x86_sse2_mul_sd:
1783 // TODO: Lower MIN/MAX/ABS/etc
1784 Value *LHS = II->getOperand(1);
1785 Value *RHS = II->getOperand(2);
1786 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001787 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001788 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001789 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001790 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791
1792 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001793 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 case Intrinsic::x86_sse_sub_ss:
1795 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001796 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001797 II->getName()), *II);
1798 break;
1799 case Intrinsic::x86_sse_mul_ss:
1800 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001801 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 II->getName()), *II);
1803 break;
1804 }
1805
1806 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001807 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001808 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001809 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811 return New;
1812 }
1813 }
1814
1815 // Output elements are undefined if both are undefined. Consider things
1816 // like undef&0. The result is known zero, not undef.
1817 UndefElts &= UndefElts2;
1818 break;
1819 }
1820 break;
1821 }
1822 }
1823 return MadeChange ? I : 0;
1824}
1825
Dan Gohman5d56fd42008-05-19 22:14:15 +00001826
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827/// AssociativeOpt - Perform an optimization on an associative operator. This
1828/// function is designed to check a chain of associative operators for a
1829/// potential to apply a certain optimization. Since the optimization may be
1830/// applicable if the expression was reassociated, this checks the chain, then
1831/// reassociates the expression as necessary to expose the optimization
1832/// opportunity. This makes use of a special Functor, which must define
1833/// 'shouldApply' and 'apply' methods.
1834///
1835template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001836static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001837 unsigned Opcode = Root.getOpcode();
1838 Value *LHS = Root.getOperand(0);
1839
1840 // Quick check, see if the immediate LHS matches...
1841 if (F.shouldApply(LHS))
1842 return F.apply(Root);
1843
1844 // Otherwise, if the LHS is not of the same opcode as the root, return.
1845 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1846 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1847 // Should we apply this transform to the RHS?
1848 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1849
1850 // If not to the RHS, check to see if we should apply to the LHS...
1851 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1852 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1853 ShouldApply = true;
1854 }
1855
1856 // If the functor wants to apply the optimization to the RHS of LHSI,
1857 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1858 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001859 // Now all of the instructions are in the current basic block, go ahead
1860 // and perform the reassociation.
1861 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1862
1863 // First move the selected RHS to the LHS of the root...
1864 Root.setOperand(0, LHSI->getOperand(1));
1865
1866 // Make what used to be the LHS of the root be the user of the root...
1867 Value *ExtraOperand = TmpLHSI->getOperand(1);
1868 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001869 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870 return 0;
1871 }
1872 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1873 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001875 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001876 ARI = Root;
1877
1878 // Now propagate the ExtraOperand down the chain of instructions until we
1879 // get to LHSI.
1880 while (TmpLHSI != LHSI) {
1881 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1882 // Move the instruction to immediately before the chain we are
1883 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001884 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 ARI = NextLHSI;
1886
1887 Value *NextOp = NextLHSI->getOperand(1);
1888 NextLHSI->setOperand(1, ExtraOperand);
1889 TmpLHSI = NextLHSI;
1890 ExtraOperand = NextOp;
1891 }
1892
1893 // Now that the instructions are reassociated, have the functor perform
1894 // the transformation...
1895 return F.apply(Root);
1896 }
1897
1898 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1899 }
1900 return 0;
1901}
1902
Dan Gohman089efff2008-05-13 00:00:25 +00001903namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001904
Nick Lewycky27f6c132008-05-23 04:34:58 +00001905// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906struct AddRHS {
1907 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001908 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1910 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001911 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001912 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913 }
1914};
1915
1916// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1917// iff C1&C2 == 0
1918struct AddMaskingAnd {
1919 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001920 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001921 bool shouldApply(Value *LHS) const {
1922 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001923 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001924 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001925 }
1926 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001927 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928 }
1929};
1930
Dan Gohman089efff2008-05-13 00:00:25 +00001931}
1932
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001933static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1934 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001935 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001936 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001937
1938 // Figure out if the constant is the left or the right argument.
1939 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1940 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1941
1942 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1943 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001944 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1945 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001946 }
1947
1948 Value *Op0 = SO, *Op1 = ConstOperand;
1949 if (!ConstIsRHS)
1950 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001951
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001953 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1954 SO->getName()+".op");
1955 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1956 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1957 SO->getName()+".cmp");
1958 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1959 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1960 SO->getName()+".cmp");
1961 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962}
1963
1964// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1965// constant as the other operand, try to fold the binary operator into the
1966// select arguments. This also works for Cast instructions, which obviously do
1967// not have a second operand.
1968static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1969 InstCombiner *IC) {
1970 // Don't modify shared select instructions
1971 if (!SI->hasOneUse()) return 0;
1972 Value *TV = SI->getOperand(1);
1973 Value *FV = SI->getOperand(2);
1974
1975 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1976 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00001977 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001978
1979 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1980 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1981
Gabor Greifd6da1d02008-04-06 20:25:17 +00001982 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1983 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 }
1985 return 0;
1986}
1987
1988
Chris Lattnerf7843b72009-09-27 19:57:57 +00001989/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1990/// has a PHI node as operand #0, see if we can fold the instruction into the
1991/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00001992///
1993/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1994/// that would normally be unprofitable because they strongly encourage jump
1995/// threading.
1996Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1997 bool AllowAggressive) {
1998 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001999 PHINode *PN = cast<PHINode>(I.getOperand(0));
2000 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002001 if (NumPHIValues == 0 ||
2002 // We normally only transform phis with a single use, unless we're trying
2003 // hard to make jump threading happen.
2004 (!PN->hasOneUse() && !AllowAggressive))
2005 return 0;
2006
2007
Chris Lattnerf7843b72009-09-27 19:57:57 +00002008 // Check to see if all of the operands of the PHI are simple constants
2009 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002010 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2011 // bail out. We don't do arbitrary constant expressions here because moving
2012 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013 BasicBlock *NonConstBB = 0;
2014 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002015 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2016 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002017 if (NonConstBB) return 0; // More than one non-const value.
2018 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2019 NonConstBB = PN->getIncomingBlock(i);
2020
2021 // If the incoming non-constant value is in I's block, we have an infinite
2022 // loop.
2023 if (NonConstBB == I.getParent())
2024 return 0;
2025 }
2026
2027 // If there is exactly one non-constant value, we can insert a copy of the
2028 // operation in that block. However, if this is a critical edge, we would be
2029 // inserting the computation one some other paths (e.g. inside a loop). Only
2030 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002031 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2033 if (!BI || !BI->isUnconditional()) return 0;
2034 }
2035
2036 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002037 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002039 InsertNewInstBefore(NewPN, *PN);
2040 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002041
2042 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002043 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2044 // We only currently try to fold the condition of a select when it is a phi,
2045 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002046 Value *TrueV = SI->getTrueValue();
2047 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002048 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002049 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002050 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002051 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2052 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002053 Value *InV = 0;
2054 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002055 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002056 } else {
2057 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002058 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2059 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002060 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002061 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002062 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002063 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002064 }
2065 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002066 Constant *C = cast<Constant>(I.getOperand(1));
2067 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002068 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2070 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002071 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002072 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002073 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002074 } else {
2075 assert(PN->getIncomingBlock(i) == NonConstBB);
2076 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002077 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078 PN->getIncomingValue(i), C, "phitmp",
2079 NonConstBB->getTerminator());
2080 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002081 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 CI->getPredicate(),
2083 PN->getIncomingValue(i), C, "phitmp",
2084 NonConstBB->getTerminator());
2085 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002086 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002087
2088 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 }
2090 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2091 }
2092 } else {
2093 CastInst *CI = cast<CastInst>(&I);
2094 const Type *RetTy = CI->getType();
2095 for (unsigned i = 0; i != NumPHIValues; ++i) {
2096 Value *InV;
2097 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002098 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 } else {
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002101 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002102 I.getType(), "phitmp",
2103 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002104 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002105 }
2106 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2107 }
2108 }
2109 return ReplaceInstUsesWith(I, NewPN);
2110}
2111
Chris Lattner55476162008-01-29 06:52:45 +00002112
Chris Lattner3554f972008-05-20 05:46:13 +00002113/// WillNotOverflowSignedAdd - Return true if we can prove that:
2114/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2115/// This basically requires proving that the add in the original type would not
2116/// overflow to change the sign bit or have a carry out.
2117bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2118 // There are different heuristics we can use for this. Here are some simple
2119 // ones.
2120
2121 // Add has the property that adding any two 2's complement numbers can only
2122 // have one carry bit which can change a sign. As such, if LHS and RHS each
2123 // have at least two sign bits, we know that the addition of the two values will
2124 // sign extend fine.
2125 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2126 return true;
2127
2128
2129 // If one of the operands only has one non-zero bit, and if the other operand
2130 // has a known-zero bit in a more significant place than it (not including the
2131 // sign bit) the ripple may go up to and fill the zero, but won't change the
2132 // sign. For example, (X & ~4) + 1.
2133
2134 // TODO: Implement.
2135
2136 return false;
2137}
2138
Chris Lattner55476162008-01-29 06:52:45 +00002139
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002140Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2141 bool Changed = SimplifyCommutative(I);
2142 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2143
2144 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2145 // X + undef -> undef
2146 if (isa<UndefValue>(RHS))
2147 return ReplaceInstUsesWith(I, RHS);
2148
2149 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002150 if (RHSC->isNullValue())
2151 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152
2153 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2154 // X + (signbit) --> X ^ signbit
2155 const APInt& Val = CI->getValue();
2156 uint32_t BitWidth = Val.getBitWidth();
2157 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002158 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159
2160 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2161 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002162 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002163 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002164
Eli Friedmana21526d2009-07-13 22:27:52 +00002165 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002166 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002167 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002168 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169 }
2170
2171 if (isa<PHINode>(LHS))
2172 if (Instruction *NV = FoldOpIntoPhi(I))
2173 return NV;
2174
2175 ConstantInt *XorRHS = 0;
2176 Value *XorLHS = 0;
2177 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002178 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002179 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2181
2182 uint32_t Size = TySizeBits / 2;
2183 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2184 APInt CFF80Val(-C0080Val);
2185 do {
2186 if (TySizeBits > Size) {
2187 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2188 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2189 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2190 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2191 // This is a sign extend if the top bits are known zero.
2192 if (!MaskedValueIsZero(XorLHS,
2193 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2194 Size = 0; // Not a sign ext, but can't be any others either.
2195 break;
2196 }
2197 }
2198 Size >>= 1;
2199 C0080Val = APIntOps::lshr(C0080Val, Size);
2200 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2201 } while (Size >= 1);
2202
2203 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002204 // with funny bit widths then this switch statement should be removed. It
2205 // is just here to get the size of the "middle" type back up to something
2206 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002207 const Type *MiddleType = 0;
2208 switch (Size) {
2209 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002210 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2211 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2212 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002213 }
2214 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002215 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002216 return new SExtInst(NewTrunc, I.getType(), I.getName());
2217 }
2218 }
2219 }
2220
Owen Anderson35b47072009-08-13 21:58:54 +00002221 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002222 return BinaryOperator::CreateXor(LHS, RHS);
2223
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002224 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002225 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002226 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002227 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228
2229 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2230 if (RHSI->getOpcode() == Instruction::Sub)
2231 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2232 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2233 }
2234 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2235 if (LHSI->getOpcode() == Instruction::Sub)
2236 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2237 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2238 }
2239 }
2240
2241 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002242 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002243 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002244 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002245 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002246 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002247 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002248 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002249 }
2250
Gabor Greifa645dd32008-05-16 19:29:10 +00002251 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002252 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253
2254 // A + -B --> A - B
2255 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002256 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258
2259
2260 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002261 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002263 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264
2265 // X*C1 + X*C2 --> X * (C1+C2)
2266 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002267 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002268 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 }
2270
2271 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002272 if (dyn_castFoldableMul(RHS, C2) == LHS)
2273 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274
2275 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002276 if (dyn_castNotVal(LHS) == RHS ||
2277 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002278 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279
2280
2281 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002282 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2283 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002285
2286 // A+B --> A|B iff A and B have no bits set in common.
2287 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2288 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2289 APInt LHSKnownOne(IT->getBitWidth(), 0);
2290 APInt LHSKnownZero(IT->getBitWidth(), 0);
2291 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2292 if (LHSKnownZero != 0) {
2293 APInt RHSKnownOne(IT->getBitWidth(), 0);
2294 APInt RHSKnownZero(IT->getBitWidth(), 0);
2295 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2296
2297 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002298 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002299 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002300 }
2301 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302
Nick Lewycky83598a72008-02-03 07:42:09 +00002303 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002304 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002305 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002306 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2307 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002308 if (W != Y) {
2309 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002310 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002311 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002312 std::swap(W, X);
2313 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002314 std::swap(Y, Z);
2315 std::swap(W, X);
2316 }
2317 }
2318
2319 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002320 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002321 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002322 }
2323 }
2324 }
2325
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002326 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2327 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002328 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002329 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330
2331 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002332 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002333 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002334 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335 if (Anded == CRHS) {
2336 // See if all bits from the first bit set in the Add RHS up are included
2337 // in the mask. First, get the rightmost bit.
2338 const APInt& AddRHSV = CRHS->getValue();
2339
2340 // Form a mask of all bits from the lowest bit added through the top.
2341 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2342
2343 // See if the and mask includes all of these bits.
2344 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2345
2346 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2347 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002348 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002349 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 }
2351 }
2352 }
2353
2354 // Try to fold constant add into select arguments.
2355 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2356 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2357 return R;
2358 }
2359
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002360 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002361 {
2362 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002363 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002364 if (!SI) {
2365 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002366 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002367 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002368 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002369 Value *TV = SI->getTrueValue();
2370 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002371 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002372
2373 // Can we fold the add into the argument of the select?
2374 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002375 if (match(FV, m_Zero()) &&
2376 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002377 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002378 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002379 if (match(TV, m_Zero()) &&
2380 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002381 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002382 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002383 }
2384 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002385
Chris Lattner3554f972008-05-20 05:46:13 +00002386 // Check for (add (sext x), y), see if we can merge this into an
2387 // integer add followed by a sext.
2388 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2389 // (add (sext x), cst) --> (sext (add x, cst'))
2390 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2391 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002392 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002393 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002394 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002395 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2396 // Insert the new, smaller add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002397 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2398 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002399 return new SExtInst(NewAdd, I.getType());
2400 }
2401 }
2402
2403 // (add (sext x), (sext y)) --> (sext (add int x, y))
2404 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2405 // Only do this if x/y have the same type, if at last one of them has a
2406 // single use (so we don't increase the number of sexts), and if the
2407 // integer add will not overflow.
2408 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2409 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2410 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2411 RHSConv->getOperand(0))) {
2412 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002413 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2414 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002415 return new SExtInst(NewAdd, I.getType());
2416 }
2417 }
2418 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002419
2420 return Changed ? &I : 0;
2421}
2422
2423Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2424 bool Changed = SimplifyCommutative(I);
2425 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2426
2427 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2428 // X + 0 --> X
2429 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002430 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002431 (I.getType())->getValueAPF()))
2432 return ReplaceInstUsesWith(I, LHS);
2433 }
2434
2435 if (isa<PHINode>(LHS))
2436 if (Instruction *NV = FoldOpIntoPhi(I))
2437 return NV;
2438 }
2439
2440 // -A + B --> B - A
2441 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002442 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002443 return BinaryOperator::CreateFSub(RHS, LHSV);
2444
2445 // A + -B --> A - B
2446 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002447 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002448 return BinaryOperator::CreateFSub(LHS, V);
2449
2450 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2451 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2452 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2453 return ReplaceInstUsesWith(I, LHS);
2454
Chris Lattner3554f972008-05-20 05:46:13 +00002455 // Check for (add double (sitofp x), y), see if we can merge this into an
2456 // integer add followed by a promotion.
2457 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2458 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2459 // ... if the constant fits in the integer value. This is useful for things
2460 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2461 // requires a constant pool load, and generally allows the add to be better
2462 // instcombined.
2463 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2464 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002465 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002466 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002467 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002468 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2469 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002470 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2471 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002472 return new SIToFPInst(NewAdd, I.getType());
2473 }
2474 }
2475
2476 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2477 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2478 // Only do this if x/y have the same type, if at last one of them has a
2479 // single use (so we don't increase the number of int->fp conversions),
2480 // and if the integer add will not overflow.
2481 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2482 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2483 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2484 RHSConv->getOperand(0))) {
2485 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002486 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2487 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002488 return new SIToFPInst(NewAdd, I.getType());
2489 }
2490 }
2491 }
2492
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 return Changed ? &I : 0;
2494}
2495
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2497 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2498
Dan Gohman7ce405e2009-06-04 22:49:04 +00002499 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501
2502 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002503 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505
2506 if (isa<UndefValue>(Op0))
2507 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2508 if (isa<UndefValue>(Op1))
2509 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2510
2511 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2512 // Replace (-1 - A) with (~A)...
2513 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002514 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515
2516 // C - ~X == X + (1+C)
2517 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002518 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002519 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520
2521 // -(X >>u 31) -> (X >>s 31)
2522 // -(X >>s 31) -> (X >>u 31)
2523 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002524 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 if (SI->getOpcode() == Instruction::LShr) {
2526 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2527 // Check to see if we are shifting out everything but the sign bit.
2528 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2529 SI->getType()->getPrimitiveSizeInBits()-1) {
2530 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002531 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532 SI->getOperand(0), CU, SI->getName());
2533 }
2534 }
2535 }
2536 else if (SI->getOpcode() == Instruction::AShr) {
2537 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2538 // Check to see if we are shifting out everything but the sign bit.
2539 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2540 SI->getType()->getPrimitiveSizeInBits()-1) {
2541 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002542 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002543 SI->getOperand(0), CU, SI->getName());
2544 }
2545 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002546 }
2547 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 }
2549
2550 // Try to fold constant sub into select arguments.
2551 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2552 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2553 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002554
2555 // C - zext(bool) -> bool ? C - 1 : C
2556 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002557 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002558 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002559 }
2560
Owen Anderson35b47072009-08-13 21:58:54 +00002561 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002562 return BinaryOperator::CreateXor(Op0, Op1);
2563
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002564 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002565 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002567 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002568 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002570 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002571 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2573 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2574 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002575 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002576 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 }
2578 }
2579
2580 if (Op1I->hasOneUse()) {
2581 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2582 // is not used by anyone else...
2583 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002584 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585 // Swap the two operands of the subexpr...
2586 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2587 Op1I->setOperand(0, IIOp1);
2588 Op1I->setOperand(1, IIOp0);
2589
2590 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002591 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002592 }
2593
2594 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2595 //
2596 if (Op1I->getOpcode() == Instruction::And &&
2597 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2598 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2599
Chris Lattnerc7694852009-08-30 07:44:24 +00002600 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002601 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 }
2603
2604 // 0 - (X sdiv C) -> (X sdiv -C)
2605 if (Op1I->getOpcode() == Instruction::SDiv)
2606 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2607 if (CSI->isZero())
2608 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002609 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002610 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002611
2612 // X - X*C --> X * (1-C)
2613 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002614 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002615 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002616 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002617 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002618 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619 }
2620 }
2621 }
2622
Dan Gohman7ce405e2009-06-04 22:49:04 +00002623 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2624 if (Op0I->getOpcode() == Instruction::Add) {
2625 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2626 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2627 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2628 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2629 } else if (Op0I->getOpcode() == Instruction::Sub) {
2630 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002631 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002632 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002633 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002634 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635
2636 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002637 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002639 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002640
2641 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002642 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002643 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002644 }
2645 return 0;
2646}
2647
Dan Gohman7ce405e2009-06-04 22:49:04 +00002648Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2650
2651 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002652 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002653 return BinaryOperator::CreateFAdd(Op0, V);
2654
2655 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2656 if (Op1I->getOpcode() == Instruction::FAdd) {
2657 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002658 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002659 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002660 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002661 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002662 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002663 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002664 }
2665
2666 return 0;
2667}
2668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2670/// comparison only checks the sign bit. If it only checks the sign bit, set
2671/// TrueIfSigned if the result of the comparison is true when the input value is
2672/// signed.
2673static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2674 bool &TrueIfSigned) {
2675 switch (pred) {
2676 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2677 TrueIfSigned = true;
2678 return RHS->isZero();
2679 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2680 TrueIfSigned = true;
2681 return RHS->isAllOnesValue();
2682 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2683 TrueIfSigned = false;
2684 return RHS->isAllOnesValue();
2685 case ICmpInst::ICMP_UGT:
2686 // True if LHS u> RHS and RHS == high-bit-mask - 1
2687 TrueIfSigned = true;
2688 return RHS->getValue() ==
2689 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2690 case ICmpInst::ICMP_UGE:
2691 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2692 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002693 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002694 default:
2695 return false;
2696 }
2697}
2698
2699Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2700 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002702
Chris Lattner3508c5c2009-10-11 21:36:10 +00002703 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002704 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002705
Chris Lattner6438c582009-10-11 07:53:15 +00002706 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002707 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2708 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709
2710 // ((X << C1)*C2) == (X * (C2 << C1))
2711 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2712 if (SI->getOpcode() == Instruction::Shl)
2713 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002714 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002715 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716
2717 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00002718 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 if (CI->equalsInt(1)) // X * 1 == X
2720 return ReplaceInstUsesWith(I, Op0);
2721 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002722 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723
2724 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2725 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002727 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002729 } else if (isa<VectorType>(Op1C->getType())) {
2730 if (Op1C->isNullValue())
2731 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00002732
Chris Lattner3508c5c2009-10-11 21:36:10 +00002733 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00002734 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002735 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002736
2737 // As above, vector X*splat(1.0) -> X in all defined cases.
2738 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002739 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2740 if (CI->equalsInt(1))
2741 return ReplaceInstUsesWith(I, Op0);
2742 }
2743 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002744 }
2745
2746 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2747 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00002748 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002750 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2751 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002752 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753
2754 }
2755
2756 // Try to fold constant mul into select arguments.
2757 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2758 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2759 return R;
2760
2761 if (isa<PHINode>(Op0))
2762 if (Instruction *NV = FoldOpIntoPhi(I))
2763 return NV;
2764 }
2765
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002766 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00002767 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002768 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002769
Nick Lewycky1c246402008-11-21 07:33:58 +00002770 // (X / Y) * Y = X - (X % Y)
2771 // (X / Y) * -Y = (X % Y) - X
2772 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00002773 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00002774 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2775 if (!BO ||
2776 (BO->getOpcode() != Instruction::UDiv &&
2777 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00002778 Op1C = Op0;
2779 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002780 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002781 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00002782 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00002783 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00002784 (BO->getOpcode() == Instruction::UDiv ||
2785 BO->getOpcode() == Instruction::SDiv)) {
2786 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2787
Dan Gohman07878902009-08-12 16:33:09 +00002788 // If the division is exact, X % Y is zero.
2789 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2790 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00002791 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00002792 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002793 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00002794 }
2795
Chris Lattnerc7694852009-08-30 07:44:24 +00002796 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00002797 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00002798 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002799 else
Chris Lattnerc7694852009-08-30 07:44:24 +00002800 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002801 Rem->takeName(BO);
2802
Chris Lattner3508c5c2009-10-11 21:36:10 +00002803 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00002804 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00002805 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002806 }
2807 }
2808
Chris Lattner6438c582009-10-11 07:53:15 +00002809 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00002810 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00002811 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002812
Chris Lattner6438c582009-10-11 07:53:15 +00002813 // X*(1 << Y) --> X << Y
2814 // (1 << Y)*X --> X << Y
2815 {
2816 Value *Y;
2817 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00002818 return BinaryOperator::CreateShl(Op1, Y);
2819 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00002820 return BinaryOperator::CreateShl(Op0, Y);
2821 }
2822
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002823 // If one of the operands of the multiply is a cast from a boolean value, then
2824 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00002825 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2826 if (!isa<VectorType>(I.getType())) {
2827 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00002828 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00002829
Chris Lattner4ca76f72009-10-11 21:29:45 +00002830 Value *BoolCast = 0, *OtherOp = 0;
2831 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00002832 BoolCast = Op0, OtherOp = Op1;
2833 else if (MaskedValueIsZero(Op1, Negative2))
2834 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00002835
Chris Lattner291872e2009-10-11 21:22:21 +00002836 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00002837 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2838 BoolCast, "tmp");
2839 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 }
2841 }
2842
2843 return Changed ? &I : 0;
2844}
2845
Dan Gohman7ce405e2009-06-04 22:49:04 +00002846Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2847 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00002849
2850 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00002851 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2852 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002853 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2854 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2855 if (Op1F->isExactlyValue(1.0))
2856 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00002857 } else if (isa<VectorType>(Op1C->getType())) {
2858 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002859 // As above, vector X*splat(1.0) -> X in all defined cases.
2860 if (Constant *Splat = Op1V->getSplatValue()) {
2861 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2862 if (F->isExactlyValue(1.0))
2863 return ReplaceInstUsesWith(I, Op0);
2864 }
2865 }
2866 }
2867
2868 // Try to fold constant mul into select arguments.
2869 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2870 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2871 return R;
2872
2873 if (isa<PHINode>(Op0))
2874 if (Instruction *NV = FoldOpIntoPhi(I))
2875 return NV;
2876 }
2877
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002878 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00002879 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002880 return BinaryOperator::CreateFMul(Op0v, Op1v);
2881
2882 return Changed ? &I : 0;
2883}
2884
Chris Lattner76972db2008-07-14 00:15:52 +00002885/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2886/// instruction.
2887bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2888 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2889
2890 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2891 int NonNullOperand = -1;
2892 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2893 if (ST->isNullValue())
2894 NonNullOperand = 2;
2895 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2896 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2897 if (ST->isNullValue())
2898 NonNullOperand = 1;
2899
2900 if (NonNullOperand == -1)
2901 return false;
2902
2903 Value *SelectCond = SI->getOperand(0);
2904
2905 // Change the div/rem to use 'Y' instead of the select.
2906 I.setOperand(1, SI->getOperand(NonNullOperand));
2907
2908 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2909 // problem. However, the select, or the condition of the select may have
2910 // multiple uses. Based on our knowledge that the operand must be non-zero,
2911 // propagate the known value for the select into other uses of it, and
2912 // propagate a known value of the condition into its other users.
2913
2914 // If the select and condition only have a single use, don't bother with this,
2915 // early exit.
2916 if (SI->use_empty() && SelectCond->hasOneUse())
2917 return true;
2918
2919 // Scan the current block backward, looking for other uses of SI.
2920 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2921
2922 while (BBI != BBFront) {
2923 --BBI;
2924 // If we found a call to a function, we can't assume it will return, so
2925 // information from below it cannot be propagated above it.
2926 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2927 break;
2928
2929 // Replace uses of the select or its condition with the known values.
2930 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2931 I != E; ++I) {
2932 if (*I == SI) {
2933 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00002934 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002935 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002936 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2937 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00002938 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002939 }
2940 }
2941
2942 // If we past the instruction, quit looking for it.
2943 if (&*BBI == SI)
2944 SI = 0;
2945 if (&*BBI == SelectCond)
2946 SelectCond = 0;
2947
2948 // If we ran out of things to eliminate, break out of the loop.
2949 if (SelectCond == 0 && SI == 0)
2950 break;
2951
2952 }
2953 return true;
2954}
2955
2956
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002957/// This function implements the transforms on div instructions that work
2958/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2959/// used by the visitors to those instructions.
2960/// @brief Transforms common to all three div instructions
2961Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2963
Chris Lattner653ef3c2008-02-19 06:12:18 +00002964 // undef / X -> 0 for integer.
2965 // undef / X -> undef for FP (the undef could be a snan).
2966 if (isa<UndefValue>(Op0)) {
2967 if (Op0->getType()->isFPOrFPVector())
2968 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002969 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002970 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971
2972 // X / undef -> undef
2973 if (isa<UndefValue>(Op1))
2974 return ReplaceInstUsesWith(I, Op1);
2975
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976 return 0;
2977}
2978
2979/// This function implements the transforms common to both integer division
2980/// instructions (udiv and sdiv). It is called by the visitors to those integer
2981/// division instructions.
2982/// @brief Common integer divide transforms
2983Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2985
Chris Lattnercefb36c2008-05-16 02:59:42 +00002986 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002987 if (Op0 == Op1) {
2988 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002989 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002990 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002991 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002992 }
2993
Owen Andersoneacb44d2009-07-24 23:12:02 +00002994 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002995 return ReplaceInstUsesWith(I, CI);
2996 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002997
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 if (Instruction *Common = commonDivTransforms(I))
2999 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003000
3001 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3002 // This does not apply for fdiv.
3003 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3004 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005
3006 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3007 // div X, 1 == X
3008 if (RHS->equalsInt(1))
3009 return ReplaceInstUsesWith(I, Op0);
3010
3011 // (X / C1) / C2 -> X / (C1*C2)
3012 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3013 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3014 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003015 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003016 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003018 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003019 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003020 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 }
3022
3023 if (!RHS->isZero()) { // avoid X udiv 0
3024 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3025 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3026 return R;
3027 if (isa<PHINode>(Op0))
3028 if (Instruction *NV = FoldOpIntoPhi(I))
3029 return NV;
3030 }
3031 }
3032
3033 // 0 / X == 0, we don't need to preserve faults!
3034 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3035 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003036 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003038 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003039 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003040 return ReplaceInstUsesWith(I, Op0);
3041
Nick Lewycky94418732008-11-27 20:21:08 +00003042 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3043 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3044 // div X, 1 == X
3045 if (X->isOne())
3046 return ReplaceInstUsesWith(I, Op0);
3047 }
3048
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049 return 0;
3050}
3051
3052Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054
3055 // Handle the integer div common cases
3056 if (Instruction *Common = commonIDivTransforms(I))
3057 return Common;
3058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003059 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003060 // X udiv C^2 -> X >> C
3061 // Check to see if this is an unsigned division with an exact power of 2,
3062 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003064 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003065 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003066
3067 // X udiv C, where C >= signbit
3068 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003069 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003070 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003071 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003072 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003073 }
3074
3075 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3076 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3077 if (RHSI->getOpcode() == Instruction::Shl &&
3078 isa<ConstantInt>(RHSI->getOperand(0))) {
3079 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3080 if (C1.isPowerOf2()) {
3081 Value *N = RHSI->getOperand(1);
3082 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003083 if (uint32_t C2 = C1.logBase2())
3084 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 }
3087 }
3088 }
3089
3090 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3091 // where C1&C2 are powers of two.
3092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3093 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3094 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3095 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3096 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3097 // Compute the shift amounts
3098 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3099 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003100 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003101 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003102
3103 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003104 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003105 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003106
3107 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003108 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109 }
3110 }
3111 return 0;
3112}
3113
3114Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3116
3117 // Handle the integer div common cases
3118 if (Instruction *Common = commonIDivTransforms(I))
3119 return Common;
3120
3121 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3122 // sdiv X, -1 == -X
3123 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003124 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003125
Dan Gohman07878902009-08-12 16:33:09 +00003126 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003127 if (cast<SDivOperator>(&I)->isExact() &&
3128 RHS->getValue().isNonNegative() &&
3129 RHS->getValue().isPowerOf2()) {
3130 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3131 RHS->getValue().exactLogBase2());
3132 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3133 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003134
3135 // -X/C --> X/-C provided the negation doesn't overflow.
3136 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3137 if (isa<Constant>(Sub->getOperand(0)) &&
3138 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003139 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003140 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3141 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003142 }
3143
3144 // If the sign bits of both operands are zero (i.e. we can prove they are
3145 // unsigned inputs), turn this into a udiv.
3146 if (I.getType()->isInteger()) {
3147 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003148 if (MaskedValueIsZero(Op0, Mask)) {
3149 if (MaskedValueIsZero(Op1, Mask)) {
3150 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3151 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3152 }
3153 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003154 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003155 ShiftedInt->getValue().isPowerOf2()) {
3156 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3157 // Safe because the only negative value (1 << Y) can take on is
3158 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3159 // the sign bit set.
3160 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3161 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003163 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003164
3165 return 0;
3166}
3167
3168Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3169 return commonDivTransforms(I);
3170}
3171
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172/// This function implements the transforms on rem instructions that work
3173/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3174/// is used by the visitors to those instructions.
3175/// @brief Transforms common to all three rem instructions
3176Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3178
Chris Lattner653ef3c2008-02-19 06:12:18 +00003179 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3180 if (I.getType()->isFPOrFPVector())
3181 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003182 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003183 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 if (isa<UndefValue>(Op1))
3185 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3186
3187 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003188 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3189 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190
3191 return 0;
3192}
3193
3194/// This function implements the transforms common to both integer remainder
3195/// instructions (urem and srem). It is called by the visitors to those integer
3196/// remainder instructions.
3197/// @brief Common integer remainder transforms
3198Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3199 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3200
3201 if (Instruction *common = commonRemTransforms(I))
3202 return common;
3203
Dale Johannesena51f7372009-01-21 00:35:19 +00003204 // 0 % X == 0 for integer, we don't need to preserve faults!
3205 if (Constant *LHS = dyn_cast<Constant>(Op0))
3206 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003207 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003209 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210 // X % 0 == undef, we don't need to preserve faults!
3211 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003212 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213
3214 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003215 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216
3217 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3219 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3220 return R;
3221 } else if (isa<PHINode>(Op0I)) {
3222 if (Instruction *NV = FoldOpIntoPhi(I))
3223 return NV;
3224 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003225
3226 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003227 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003228 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229 }
3230 }
3231
3232 return 0;
3233}
3234
3235Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3236 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3237
3238 if (Instruction *common = commonIRemTransforms(I))
3239 return common;
3240
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3242 // X urem C^2 -> X and C
3243 // Check to see if this is an unsigned remainder with an exact power of 2,
3244 // if so, convert to a bitwise and.
3245 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3246 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003247 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003248 }
3249
3250 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3251 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3252 if (RHSI->getOpcode() == Instruction::Shl &&
3253 isa<ConstantInt>(RHSI->getOperand(0))) {
3254 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003255 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003256 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003257 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003258 }
3259 }
3260 }
3261
3262 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3263 // where C1&C2 are powers of two.
3264 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3265 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3266 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3267 // STO == 0 and SFO == 0 handled above.
3268 if ((STO->getValue().isPowerOf2()) &&
3269 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003270 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3271 SI->getName()+".t");
3272 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3273 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003274 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003275 }
3276 }
3277 }
3278
3279 return 0;
3280}
3281
3282Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
Dan Gohmandb3dd962007-11-05 23:16:33 +00003285 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003286 if (Instruction *Common = commonIRemTransforms(I))
3287 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003288
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003289 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003290 if (!isa<Constant>(RHSNeg) ||
3291 (isa<ConstantInt>(RHSNeg) &&
3292 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003293 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003294 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295 I.setOperand(1, RHSNeg);
3296 return &I;
3297 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003298
Dan Gohmandb3dd962007-11-05 23:16:33 +00003299 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003300 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003301 if (I.getType()->isInteger()) {
3302 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3303 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3304 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003305 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003306 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307 }
3308
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003309 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003310 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3311 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003312
Nick Lewyckyfd746832008-12-20 16:48:00 +00003313 bool hasNegative = false;
3314 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3315 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3316 if (RHS->getValue().isNegative())
3317 hasNegative = true;
3318
3319 if (hasNegative) {
3320 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003321 for (unsigned i = 0; i != VWidth; ++i) {
3322 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3323 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003324 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003325 else
3326 Elts[i] = RHS;
3327 }
3328 }
3329
Owen Anderson2f422e02009-07-28 21:19:26 +00003330 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003331 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003332 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003333 I.setOperand(1, NewRHSV);
3334 return &I;
3335 }
3336 }
3337 }
3338
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003339 return 0;
3340}
3341
3342Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3343 return commonRemTransforms(I);
3344}
3345
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346// isOneBitSet - Return true if there is exactly one bit set in the specified
3347// constant.
3348static bool isOneBitSet(const ConstantInt *CI) {
3349 return CI->getValue().isPowerOf2();
3350}
3351
3352// isHighOnes - Return true if the constant is of the form 1+0+.
3353// This is the same as lowones(~X).
3354static bool isHighOnes(const ConstantInt *CI) {
3355 return (~CI->getValue() + 1).isPowerOf2();
3356}
3357
3358/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3359/// are carefully arranged to allow folding of expressions such as:
3360///
3361/// (A < B) | (A > B) --> (A != B)
3362///
3363/// Note that this is only valid if the first and second predicates have the
3364/// same sign. Is illegal to do: (A u< B) | (A s> B)
3365///
3366/// Three bits are used to represent the condition, as follows:
3367/// 0 A > B
3368/// 1 A == B
3369/// 2 A < B
3370///
3371/// <=> Value Definition
3372/// 000 0 Always false
3373/// 001 1 A > B
3374/// 010 2 A == B
3375/// 011 3 A >= B
3376/// 100 4 A < B
3377/// 101 5 A != B
3378/// 110 6 A <= B
3379/// 111 7 Always true
3380///
3381static unsigned getICmpCode(const ICmpInst *ICI) {
3382 switch (ICI->getPredicate()) {
3383 // False -> 0
3384 case ICmpInst::ICMP_UGT: return 1; // 001
3385 case ICmpInst::ICMP_SGT: return 1; // 001
3386 case ICmpInst::ICMP_EQ: return 2; // 010
3387 case ICmpInst::ICMP_UGE: return 3; // 011
3388 case ICmpInst::ICMP_SGE: return 3; // 011
3389 case ICmpInst::ICMP_ULT: return 4; // 100
3390 case ICmpInst::ICMP_SLT: return 4; // 100
3391 case ICmpInst::ICMP_NE: return 5; // 101
3392 case ICmpInst::ICMP_ULE: return 6; // 110
3393 case ICmpInst::ICMP_SLE: return 6; // 110
3394 // True -> 7
3395 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003396 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397 return 0;
3398 }
3399}
3400
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003401/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3402/// predicate into a three bit mask. It also returns whether it is an ordered
3403/// predicate by reference.
3404static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3405 isOrdered = false;
3406 switch (CC) {
3407 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3408 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003409 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3410 case FCmpInst::FCMP_UGT: return 1; // 001
3411 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3412 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003413 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3414 case FCmpInst::FCMP_UGE: return 3; // 011
3415 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3416 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003417 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3418 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003419 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3420 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003421 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003422 default:
3423 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003424 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003425 return 0;
3426 }
3427}
3428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429/// getICmpValue - This is the complement of getICmpCode, which turns an
3430/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003431/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003432/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003433static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003434 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003435 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003436 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003437 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003438 case 1:
3439 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003440 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003442 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3443 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 case 3:
3445 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003446 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003448 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003449 case 4:
3450 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003451 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003453 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3454 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455 case 6:
3456 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003457 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003459 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003460 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461 }
3462}
3463
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003464/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3465/// opcode and two operands into either a FCmp instruction. isordered is passed
3466/// in to determine which kind of predicate to use in the new fcmp instruction.
3467static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003468 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003469 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003470 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003471 case 0:
3472 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003473 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003474 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003475 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003476 case 1:
3477 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003478 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003479 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003480 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003481 case 2:
3482 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003483 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003484 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003485 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003486 case 3:
3487 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003488 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003489 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003490 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003491 case 4:
3492 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003493 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003494 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003495 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003496 case 5:
3497 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003498 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003499 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003500 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003501 case 6:
3502 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003503 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003504 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003505 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003506 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003507 }
3508}
3509
Chris Lattner2972b822008-11-16 04:55:20 +00003510/// PredicatesFoldable - Return true if both predicates match sign or if at
3511/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3513 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003514 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3515 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516}
3517
3518namespace {
3519// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3520struct FoldICmpLogical {
3521 InstCombiner &IC;
3522 Value *LHS, *RHS;
3523 ICmpInst::Predicate pred;
3524 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3525 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3526 pred(ICI->getPredicate()) {}
3527 bool shouldApply(Value *V) const {
3528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3529 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003530 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3531 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532 return false;
3533 }
3534 Instruction *apply(Instruction &Log) const {
3535 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3536 if (ICI->getOperand(0) != LHS) {
3537 assert(ICI->getOperand(1) == LHS);
3538 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3539 }
3540
3541 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3542 unsigned LHSCode = getICmpCode(ICI);
3543 unsigned RHSCode = getICmpCode(RHSICI);
3544 unsigned Code;
3545 switch (Log.getOpcode()) {
3546 case Instruction::And: Code = LHSCode & RHSCode; break;
3547 case Instruction::Or: Code = LHSCode | RHSCode; break;
3548 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003549 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 }
3551
3552 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3553 ICmpInst::isSignedPredicate(ICI->getPredicate());
3554
Owen Anderson24be4c12009-07-03 00:17:18 +00003555 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003556 if (Instruction *I = dyn_cast<Instruction>(RV))
3557 return I;
3558 // Otherwise, it's a constant boolean value...
3559 return IC.ReplaceInstUsesWith(Log, RV);
3560 }
3561};
3562} // end anonymous namespace
3563
3564// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3565// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3566// guaranteed to be a binary operator.
3567Instruction *InstCombiner::OptAndOp(Instruction *Op,
3568 ConstantInt *OpRHS,
3569 ConstantInt *AndRHS,
3570 BinaryOperator &TheAnd) {
3571 Value *X = Op->getOperand(0);
3572 Constant *Together = 0;
3573 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003574 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003575
3576 switch (Op->getOpcode()) {
3577 case Instruction::Xor:
3578 if (Op->hasOneUse()) {
3579 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003580 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003581 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003582 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003583 }
3584 break;
3585 case Instruction::Or:
3586 if (Together == AndRHS) // (X | C) & C --> C
3587 return ReplaceInstUsesWith(TheAnd, AndRHS);
3588
3589 if (Op->hasOneUse() && Together != OpRHS) {
3590 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003591 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003592 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003593 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003594 }
3595 break;
3596 case Instruction::Add:
3597 if (Op->hasOneUse()) {
3598 // Adding a one to a single bit bit-field should be turned into an XOR
3599 // of the bit. First thing to check is to see if this AND is with a
3600 // single bit constant.
3601 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3602
3603 // If there is only one bit set...
3604 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3605 // Ok, at this point, we know that we are masking the result of the
3606 // ADD down to exactly one bit. If the constant we are adding has
3607 // no bits set below this bit, then we can eliminate the ADD.
3608 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3609
3610 // Check to see if any bits below the one bit set in AndRHSV are set.
3611 if ((AddRHS & (AndRHSV-1)) == 0) {
3612 // If not, the only thing that can effect the output of the AND is
3613 // the bit specified by AndRHSV. If that bit is set, the effect of
3614 // the XOR is to toggle the bit. If it is clear, then the ADD has
3615 // no effect.
3616 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3617 TheAnd.setOperand(0, X);
3618 return &TheAnd;
3619 } else {
3620 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003621 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003622 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003623 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003624 }
3625 }
3626 }
3627 }
3628 break;
3629
3630 case Instruction::Shl: {
3631 // We know that the AND will not produce any of the bits shifted in, so if
3632 // the anded constant includes them, clear them now!
3633 //
3634 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3635 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3636 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003637 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003638
3639 if (CI->getValue() == ShlMask) {
3640 // Masking out bits that the shift already masks
3641 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3642 } else if (CI != AndRHS) { // Reducing bits set in and.
3643 TheAnd.setOperand(1, CI);
3644 return &TheAnd;
3645 }
3646 break;
3647 }
3648 case Instruction::LShr:
3649 {
3650 // We know that the AND will not produce any of the bits shifted in, so if
3651 // the anded constant includes them, clear them now! This only applies to
3652 // unsigned shifts, because a signed shr may bring in set bits!
3653 //
3654 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3655 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3656 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003657 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003658
3659 if (CI->getValue() == ShrMask) {
3660 // Masking out bits that the shift already masks.
3661 return ReplaceInstUsesWith(TheAnd, Op);
3662 } else if (CI != AndRHS) {
3663 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3664 return &TheAnd;
3665 }
3666 break;
3667 }
3668 case Instruction::AShr:
3669 // Signed shr.
3670 // See if this is shifting in some sign extension, then masking it out
3671 // with an and.
3672 if (Op->hasOneUse()) {
3673 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3674 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3675 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003676 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003677 if (C == AndRHS) { // Masking out bits shifted in.
3678 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3679 // Make the argument unsigned.
3680 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003681 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003682 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003683 }
3684 }
3685 break;
3686 }
3687 return 0;
3688}
3689
3690
3691/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3692/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3693/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3694/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3695/// insert new instructions.
3696Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3697 bool isSigned, bool Inside,
3698 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003699 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003700 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3701 "Lo is not <= Hi in range emission code!");
3702
3703 if (Inside) {
3704 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706
3707 // V >= Min && V < Hi --> V < Hi
3708 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3709 ICmpInst::Predicate pred = (isSigned ?
3710 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003711 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003712 }
3713
3714 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003715 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003716 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003717 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003718 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003719 }
3720
3721 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003722 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003723
3724 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003725 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003726 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3727 ICmpInst::Predicate pred = (isSigned ?
3728 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003729 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 }
3731
3732 // Emit V-Lo >u Hi-1-Lo
3733 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003734 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003735 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003736 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003737 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003738}
3739
3740// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3741// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3742// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3743// not, since all 1s are not contiguous.
3744static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3745 const APInt& V = Val->getValue();
3746 uint32_t BitWidth = Val->getType()->getBitWidth();
3747 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3748
3749 // look for the first zero bit after the run of ones
3750 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3751 // look for the first non-zero bit
3752 ME = V.getActiveBits();
3753 return true;
3754}
3755
3756/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3757/// where isSub determines whether the operator is a sub. If we can fold one of
3758/// the following xforms:
3759///
3760/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3761/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3763///
3764/// return (A +/- B).
3765///
3766Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3767 ConstantInt *Mask, bool isSub,
3768 Instruction &I) {
3769 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3770 if (!LHSI || LHSI->getNumOperands() != 2 ||
3771 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3772
3773 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3774
3775 switch (LHSI->getOpcode()) {
3776 default: return 0;
3777 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003778 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003779 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3780 if ((Mask->getValue().countLeadingZeros() +
3781 Mask->getValue().countPopulation()) ==
3782 Mask->getValue().getBitWidth())
3783 break;
3784
3785 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3786 // part, we don't need any explicit masks to take them out of A. If that
3787 // is all N is, ignore it.
3788 uint32_t MB = 0, ME = 0;
3789 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3790 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3791 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3792 if (MaskedValueIsZero(RHS, Mask))
3793 break;
3794 }
3795 }
3796 return 0;
3797 case Instruction::Or:
3798 case Instruction::Xor:
3799 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3800 if ((Mask->getValue().countLeadingZeros() +
3801 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003802 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803 break;
3804 return 0;
3805 }
3806
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00003808 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3809 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810}
3811
Chris Lattner0631ea72008-11-16 05:06:21 +00003812/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3813Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3814 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003815 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003816 ConstantInt *LHSCst, *RHSCst;
3817 ICmpInst::Predicate LHSCC, RHSCC;
3818
Chris Lattnerf3803482008-11-16 05:10:52 +00003819 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003820 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003821 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003822 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003823 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003824 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003825
3826 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3827 // where C is a power of 2
3828 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3829 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003830 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00003831 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003832 }
3833
3834 // From here on, we only handle:
3835 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3836 if (Val != Val2) return 0;
3837
Chris Lattner0631ea72008-11-16 05:06:21 +00003838 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3839 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3840 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3841 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3842 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3843 return 0;
3844
3845 // We can't fold (ugt x, C) & (sgt x, C2).
3846 if (!PredicatesFoldable(LHSCC, RHSCC))
3847 return 0;
3848
3849 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003850 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003851 if (ICmpInst::isSignedPredicate(LHSCC) ||
3852 (ICmpInst::isEquality(LHSCC) &&
3853 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003854 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003855 else
Chris Lattner665298f2008-11-16 05:14:43 +00003856 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3857
3858 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003859 std::swap(LHS, RHS);
3860 std::swap(LHSCst, RHSCst);
3861 std::swap(LHSCC, RHSCC);
3862 }
3863
3864 // At this point, we know we have have two icmp instructions
3865 // comparing a value against two constants and and'ing the result
3866 // together. Because of the above check, we know that we only have
3867 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3868 // (from the FoldICmpLogical check above), that the two constants
3869 // are not equal and that the larger constant is on the RHS
3870 assert(LHSCst != RHSCst && "Compares not folded above?");
3871
3872 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_EQ:
3875 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003876 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3878 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3879 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003880 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3882 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3883 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3884 return ReplaceInstUsesWith(I, LHS);
3885 }
3886 case ICmpInst::ICMP_NE:
3887 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003888 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003889 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003890 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003891 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003892 break; // (X != 13 & X u< 15) -> no change
3893 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003894 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003895 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003896 break; // (X != 13 & X s< 15) -> no change
3897 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3898 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3899 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3900 return ReplaceInstUsesWith(I, RHS);
3901 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003902 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003903 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003904 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00003905 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003906 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003907 }
3908 break; // (X != 13 & X != 15) -> no change
3909 }
3910 break;
3911 case ICmpInst::ICMP_ULT:
3912 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003913 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3915 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003916 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003917 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3920 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3921 return ReplaceInstUsesWith(I, LHS);
3922 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3923 break;
3924 }
3925 break;
3926 case ICmpInst::ICMP_SLT:
3927 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003928 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003929 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3930 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003931 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003932 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3933 break;
3934 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3935 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3936 return ReplaceInstUsesWith(I, LHS);
3937 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3938 break;
3939 }
3940 break;
3941 case ICmpInst::ICMP_UGT:
3942 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003943 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003944 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3945 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3946 return ReplaceInstUsesWith(I, RHS);
3947 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3948 break;
3949 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003950 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003951 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003952 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003953 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003954 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003955 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003956 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3957 break;
3958 }
3959 break;
3960 case ICmpInst::ICMP_SGT:
3961 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003962 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003963 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3964 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3965 return ReplaceInstUsesWith(I, RHS);
3966 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3967 break;
3968 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003969 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003970 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003971 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003972 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003973 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003974 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003975 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3976 break;
3977 }
3978 break;
3979 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003980
3981 return 0;
3982}
3983
Chris Lattner93a359a2009-07-23 05:14:02 +00003984Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3985 FCmpInst *RHS) {
3986
3987 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3988 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3989 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3990 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3991 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3992 // If either of the constants are nans, then the whole thing returns
3993 // false.
3994 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00003996 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00003997 LHS->getOperand(0), RHS->getOperand(0));
3998 }
Chris Lattnercf373552009-07-23 05:32:17 +00003999
4000 // Handle vector zeros. This occurs because the canonical form of
4001 // "fcmp ord x,x" is "fcmp ord x, 0".
4002 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4003 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004004 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004005 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004006 return 0;
4007 }
4008
4009 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4010 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4011 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4012
4013
4014 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4015 // Swap RHS operands to match LHS.
4016 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4017 std::swap(Op1LHS, Op1RHS);
4018 }
4019
4020 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4021 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4022 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004023 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004024
4025 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004026 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004027 if (Op0CC == FCmpInst::FCMP_TRUE)
4028 return ReplaceInstUsesWith(I, RHS);
4029 if (Op1CC == FCmpInst::FCMP_TRUE)
4030 return ReplaceInstUsesWith(I, LHS);
4031
4032 bool Op0Ordered;
4033 bool Op1Ordered;
4034 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4035 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4036 if (Op1Pred == 0) {
4037 std::swap(LHS, RHS);
4038 std::swap(Op0Pred, Op1Pred);
4039 std::swap(Op0Ordered, Op1Ordered);
4040 }
4041 if (Op0Pred == 0) {
4042 // uno && ueq -> uno && (uno || eq) -> ueq
4043 // ord && olt -> ord && (ord && lt) -> olt
4044 if (Op0Ordered == Op1Ordered)
4045 return ReplaceInstUsesWith(I, RHS);
4046
4047 // uno && oeq -> uno && (ord && eq) -> false
4048 // uno && ord -> false
4049 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004050 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004051 // ord && ueq -> ord && (uno || eq) -> oeq
4052 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4053 Op0LHS, Op0RHS, Context));
4054 }
4055 }
4056
4057 return 0;
4058}
4059
Chris Lattner0631ea72008-11-16 05:06:21 +00004060
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004061Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4062 bool Changed = SimplifyCommutative(I);
4063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4064
4065 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004067
4068 // and X, X = X
4069 if (Op0 == Op1)
4070 return ReplaceInstUsesWith(I, Op1);
4071
4072 // See if we can simplify any instructions used by the instruction whose sole
4073 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004074 if (SimplifyDemandedInstructionBits(I))
4075 return &I;
4076 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004077 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4078 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4079 return ReplaceInstUsesWith(I, I.getOperand(0));
4080 } else if (isa<ConstantAggregateZero>(Op1)) {
4081 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4082 }
4083 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004085 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004086 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004087 APInt NotAndRHS(~AndRHSMask);
4088
4089 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004090 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091 Value *Op0LHS = Op0I->getOperand(0);
4092 Value *Op0RHS = Op0I->getOperand(1);
4093 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004094 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004095 case Instruction::Xor:
4096 case Instruction::Or:
4097 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004098 if (!Op0I->hasOneUse()) break;
4099
4100 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4101 // Not masking anything out for the LHS, move to RHS.
4102 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4103 Op0RHS->getName()+".masked");
4104 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4105 }
4106 if (!isa<Constant>(Op0RHS) &&
4107 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4108 // Not masking anything out for the RHS, move to LHS.
4109 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4110 Op0LHS->getName()+".masked");
4111 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004112 }
4113
4114 break;
4115 case Instruction::Add:
4116 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4117 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4119 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004120 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004121 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004122 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004123 break;
4124
4125 case Instruction::Sub:
4126 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4127 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4129 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004130 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004131
Nick Lewyckya349ba42008-07-10 05:51:40 +00004132 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4133 // has 1's for all bits that the subtraction with A might affect.
4134 if (Op0I->hasOneUse()) {
4135 uint32_t BitWidth = AndRHSMask.getBitWidth();
4136 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4137 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4138
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004139 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004140 if (!(A && A->isZero()) && // avoid infinite recursion.
4141 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004142 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004143 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4144 }
4145 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004147
4148 case Instruction::Shl:
4149 case Instruction::LShr:
4150 // (1 << x) & 1 --> zext(x == 0)
4151 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004152 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004153 Value *NewICmp =
4154 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004155 return new ZExtInst(NewICmp, I.getType());
4156 }
4157 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004158 }
4159
4160 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4161 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4162 return Res;
4163 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4164 // If this is an integer truncation or change from signed-to-unsigned, and
4165 // if the source is an and/or with immediate, transform it. This
4166 // frequently occurs for bitfield accesses.
4167 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4168 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4169 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004170 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004171 if (CastOp->getOpcode() == Instruction::And) {
4172 // Change: and (cast (and X, C1) to T), C2
4173 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4174 // This will fold the two constants together, which may allow
4175 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004176 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004177 CastOp->getOperand(0), I.getType(),
4178 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004179 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004180 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004181 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004182 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004183 } else if (CastOp->getOpcode() == Instruction::Or) {
4184 // Change: and (cast (or X, C1) to T), C2
4185 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004186 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004187 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004188 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004189 return ReplaceInstUsesWith(I, AndRHS);
4190 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004191 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004192 }
4193 }
4194
4195 // Try to fold constant and into select arguments.
4196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4198 return R;
4199 if (isa<PHINode>(Op0))
4200 if (Instruction *NV = FoldOpIntoPhi(I))
4201 return NV;
4202 }
4203
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004204 Value *Op0NotVal = dyn_castNotVal(Op0);
4205 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206
4207 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004208 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004209
4210 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4211 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004212 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4213 I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004214 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004215 }
4216
4217 {
4218 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004219 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004220 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4221 return ReplaceInstUsesWith(I, Op1);
4222
4223 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004224 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004226 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004227 }
4228 }
4229
Dan Gohmancdff2122009-08-12 16:23:25 +00004230 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004231 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4232 return ReplaceInstUsesWith(I, Op0);
4233
4234 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004235 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004236 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004237 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004238 }
4239 }
4240
4241 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004242 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004243 if (A == Op1) { // (A^B)&A -> A&(A^B)
4244 I.swapOperands(); // Simplify below
4245 std::swap(Op0, Op1);
4246 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4247 cast<BinaryOperator>(Op0)->swapOperands();
4248 I.swapOperands(); // Simplify below
4249 std::swap(Op0, Op1);
4250 }
4251 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004252
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004254 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255 if (B == Op0) { // B&(A^B) -> B&(B^A)
4256 cast<BinaryOperator>(Op1)->swapOperands();
4257 std::swap(A, B);
4258 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004259 if (A == Op0) // A&(A^B) -> A & ~B
4260 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004261 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004262
4263 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004264 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4265 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004266 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004267 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4268 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004269 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004270 }
4271
4272 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4273 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004274 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004275 return R;
4276
Chris Lattner0631ea72008-11-16 05:06:21 +00004277 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4278 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4279 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004280 }
4281
4282 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4283 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4284 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4285 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4286 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004287 if (SrcTy == Op1C->getOperand(0)->getType() &&
4288 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004289 // Only do this if the casts both really cause code to be generated.
4290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4291 I.getType(), TD) &&
4292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4293 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004294 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4295 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004296 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004297 }
4298 }
4299
4300 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4301 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4302 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4303 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4304 SI0->getOperand(1) == SI1->getOperand(1) &&
4305 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004306 Value *NewOp =
4307 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4308 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004309 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310 SI1->getOperand(1));
4311 }
4312 }
4313
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004314 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004315 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004316 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4317 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4318 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004319 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004320
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 return Changed ? &I : 0;
4322}
4323
Chris Lattner567f5112008-10-05 02:13:19 +00004324/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4325/// capable of providing pieces of a bswap. The subexpression provides pieces
4326/// of a bswap if it is proven that each of the non-zero bytes in the output of
4327/// the expression came from the corresponding "byte swapped" byte in some other
4328/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4329/// we know that the expression deposits the low byte of %X into the high byte
4330/// of the bswap result and that all other bytes are zero. This expression is
4331/// accepted, the high byte of ByteValues is set to X to indicate a correct
4332/// match.
4333///
4334/// This function returns true if the match was unsuccessful and false if so.
4335/// On entry to the function the "OverallLeftShift" is a signed integer value
4336/// indicating the number of bytes that the subexpression is later shifted. For
4337/// example, if the expression is later right shifted by 16 bits, the
4338/// OverallLeftShift value would be -2 on entry. This is used to specify which
4339/// byte of ByteValues is actually being set.
4340///
4341/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4342/// byte is masked to zero by a user. For example, in (X & 255), X will be
4343/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4344/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4345/// always in the local (OverallLeftShift) coordinate space.
4346///
4347static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4348 SmallVector<Value*, 8> &ByteValues) {
4349 if (Instruction *I = dyn_cast<Instruction>(V)) {
4350 // If this is an or instruction, it may be an inner node of the bswap.
4351 if (I->getOpcode() == Instruction::Or) {
4352 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353 ByteValues) ||
4354 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4355 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004356 }
Chris Lattner567f5112008-10-05 02:13:19 +00004357
4358 // If this is a logical shift by a constant multiple of 8, recurse with
4359 // OverallLeftShift and ByteMask adjusted.
4360 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4361 unsigned ShAmt =
4362 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4363 // Ensure the shift amount is defined and of a byte value.
4364 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4365 return true;
4366
4367 unsigned ByteShift = ShAmt >> 3;
4368 if (I->getOpcode() == Instruction::Shl) {
4369 // X << 2 -> collect(X, +2)
4370 OverallLeftShift += ByteShift;
4371 ByteMask >>= ByteShift;
4372 } else {
4373 // X >>u 2 -> collect(X, -2)
4374 OverallLeftShift -= ByteShift;
4375 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004376 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004377 }
4378
4379 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4380 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4381
4382 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4383 ByteValues);
4384 }
4385
4386 // If this is a logical 'and' with a mask that clears bytes, clear the
4387 // corresponding bytes in ByteMask.
4388 if (I->getOpcode() == Instruction::And &&
4389 isa<ConstantInt>(I->getOperand(1))) {
4390 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4391 unsigned NumBytes = ByteValues.size();
4392 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4393 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4394
4395 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4396 // If this byte is masked out by a later operation, we don't care what
4397 // the and mask is.
4398 if ((ByteMask & (1 << i)) == 0)
4399 continue;
4400
4401 // If the AndMask is all zeros for this byte, clear the bit.
4402 APInt MaskB = AndMask & Byte;
4403 if (MaskB == 0) {
4404 ByteMask &= ~(1U << i);
4405 continue;
4406 }
4407
4408 // If the AndMask is not all ones for this byte, it's not a bytezap.
4409 if (MaskB != Byte)
4410 return true;
4411
4412 // Otherwise, this byte is kept.
4413 }
4414
4415 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4416 ByteValues);
4417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004418 }
4419
Chris Lattner567f5112008-10-05 02:13:19 +00004420 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4421 // the input value to the bswap. Some observations: 1) if more than one byte
4422 // is demanded from this input, then it could not be successfully assembled
4423 // into a byteswap. At least one of the two bytes would not be aligned with
4424 // their ultimate destination.
4425 if (!isPowerOf2_32(ByteMask)) return true;
4426 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004427
Chris Lattner567f5112008-10-05 02:13:19 +00004428 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4429 // is demanded, it needs to go into byte 0 of the result. This means that the
4430 // byte needs to be shifted until it lands in the right byte bucket. The
4431 // shift amount depends on the position: if the byte is coming from the high
4432 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4433 // low part, it must be shifted left.
4434 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4435 if (InputByteNo < ByteValues.size()/2) {
4436 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4437 return true;
4438 } else {
4439 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4440 return true;
4441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004442
4443 // If the destination byte value is already defined, the values are or'd
4444 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004445 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004446 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004447 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004448 return false;
4449}
4450
4451/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4452/// If so, insert the new bswap intrinsic and return it.
4453Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4454 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004455 if (!ITy || ITy->getBitWidth() % 16 ||
4456 // ByteMask only allows up to 32-byte values.
4457 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004458 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4459
4460 /// ByteValues - For each byte of the result, we keep track of which value
4461 /// defines each byte.
4462 SmallVector<Value*, 8> ByteValues;
4463 ByteValues.resize(ITy->getBitWidth()/8);
4464
4465 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004466 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4467 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004468 return 0;
4469
4470 // Check to see if all of the bytes come from the same value.
4471 Value *V = ByteValues[0];
4472 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4473
4474 // Check to make sure that all of the bytes come from the same value.
4475 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4476 if (ByteValues[i] != V)
4477 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004478 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004479 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004480 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004481 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004482}
4483
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004484/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4485/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4486/// we can simplify this expression to "cond ? C : D or B".
4487static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004488 Value *C, Value *D,
4489 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004490 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004491 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004492 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004493 return 0;
4494
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004495 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004496 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004497 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004498 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004499 return SelectInst::Create(Cond, C, B);
4500 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004501 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004502 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004503 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004504 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004505 return 0;
4506}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004507
Chris Lattner0c678e52008-11-16 05:20:07 +00004508/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4509Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4510 ICmpInst *LHS, ICmpInst *RHS) {
4511 Value *Val, *Val2;
4512 ConstantInt *LHSCst, *RHSCst;
4513 ICmpInst::Predicate LHSCC, RHSCC;
4514
4515 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004516 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004517 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004518 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004519 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004520 return 0;
4521
4522 // From here on, we only handle:
4523 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4524 if (Val != Val2) return 0;
4525
4526 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4527 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4528 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4529 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4530 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4531 return 0;
4532
4533 // We can't fold (ugt x, C) | (sgt x, C2).
4534 if (!PredicatesFoldable(LHSCC, RHSCC))
4535 return 0;
4536
4537 // Ensure that the larger constant is on the RHS.
4538 bool ShouldSwap;
4539 if (ICmpInst::isSignedPredicate(LHSCC) ||
4540 (ICmpInst::isEquality(LHSCC) &&
4541 ICmpInst::isSignedPredicate(RHSCC)))
4542 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4543 else
4544 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4545
4546 if (ShouldSwap) {
4547 std::swap(LHS, RHS);
4548 std::swap(LHSCst, RHSCst);
4549 std::swap(LHSCC, RHSCC);
4550 }
4551
4552 // At this point, we know we have have two icmp instructions
4553 // comparing a value against two constants and or'ing the result
4554 // together. Because of the above check, we know that we only have
4555 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4556 // FoldICmpLogical check above), that the two constants are not
4557 // equal.
4558 assert(LHSCst != RHSCst && "Compares not folded above?");
4559
4560 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004561 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004562 case ICmpInst::ICMP_EQ:
4563 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004564 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004565 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004566 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004567 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004568 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004569 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004570 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004571 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004572 }
4573 break; // (X == 13 | X == 15) -> no change
4574 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4575 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4576 break;
4577 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4578 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4579 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4580 return ReplaceInstUsesWith(I, RHS);
4581 }
4582 break;
4583 case ICmpInst::ICMP_NE:
4584 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004585 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004586 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4587 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4588 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4589 return ReplaceInstUsesWith(I, LHS);
4590 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4591 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4592 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004593 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004594 }
4595 break;
4596 case ICmpInst::ICMP_ULT:
4597 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004598 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004599 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4600 break;
4601 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4602 // If RHSCst is [us]MAXINT, it is always false. Not handling
4603 // this can cause overflow.
4604 if (RHSCst->isMaxValue(false))
4605 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004606 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004607 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004608 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4609 break;
4610 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4611 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4612 return ReplaceInstUsesWith(I, RHS);
4613 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4614 break;
4615 }
4616 break;
4617 case ICmpInst::ICMP_SLT:
4618 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004619 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004620 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4621 break;
4622 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4623 // If RHSCst is [us]MAXINT, it is always false. Not handling
4624 // this can cause overflow.
4625 if (RHSCst->isMaxValue(true))
4626 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004627 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004628 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004629 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4632 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4633 return ReplaceInstUsesWith(I, RHS);
4634 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4635 break;
4636 }
4637 break;
4638 case ICmpInst::ICMP_UGT:
4639 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004640 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4642 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4645 break;
4646 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4647 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004649 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4650 break;
4651 }
4652 break;
4653 case ICmpInst::ICMP_SGT:
4654 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004655 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004656 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4657 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4658 return ReplaceInstUsesWith(I, LHS);
4659 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4660 break;
4661 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4662 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004663 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004664 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4665 break;
4666 }
4667 break;
4668 }
4669 return 0;
4670}
4671
Chris Lattner57e66fa2009-07-23 05:46:22 +00004672Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4673 FCmpInst *RHS) {
4674 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4675 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4676 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4677 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4678 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4679 // If either of the constants are nans, then the whole thing returns
4680 // true.
4681 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004682 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004683
4684 // Otherwise, no need to compare the two constants, compare the
4685 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004686 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004687 LHS->getOperand(0), RHS->getOperand(0));
4688 }
4689
4690 // Handle vector zeros. This occurs because the canonical form of
4691 // "fcmp uno x,x" is "fcmp uno x, 0".
4692 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4693 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004694 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004695 LHS->getOperand(0), RHS->getOperand(0));
4696
4697 return 0;
4698 }
4699
4700 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4701 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4702 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4703
4704 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4705 // Swap RHS operands to match LHS.
4706 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4707 std::swap(Op1LHS, Op1RHS);
4708 }
4709 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4710 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4711 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004712 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004713 Op0LHS, Op0RHS);
4714 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004715 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004716 if (Op0CC == FCmpInst::FCMP_FALSE)
4717 return ReplaceInstUsesWith(I, RHS);
4718 if (Op1CC == FCmpInst::FCMP_FALSE)
4719 return ReplaceInstUsesWith(I, LHS);
4720 bool Op0Ordered;
4721 bool Op1Ordered;
4722 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4723 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4724 if (Op0Ordered == Op1Ordered) {
4725 // If both are ordered or unordered, return a new fcmp with
4726 // or'ed predicates.
4727 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4728 Op0LHS, Op0RHS, Context);
4729 if (Instruction *I = dyn_cast<Instruction>(RV))
4730 return I;
4731 // Otherwise, it's a constant boolean value...
4732 return ReplaceInstUsesWith(I, RV);
4733 }
4734 }
4735 return 0;
4736}
4737
Bill Wendlingdae376a2008-12-01 08:23:25 +00004738/// FoldOrWithConstants - This helper function folds:
4739///
Bill Wendling236a1192008-12-02 05:09:00 +00004740/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004741///
4742/// into:
4743///
Bill Wendling236a1192008-12-02 05:09:00 +00004744/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004745///
Bill Wendling236a1192008-12-02 05:09:00 +00004746/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004747Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004748 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004749 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4750 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004751
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004752 Value *V1 = 0;
4753 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004754 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004755
Bill Wendling86ee3162008-12-02 06:18:11 +00004756 APInt Xor = CI1->getValue() ^ CI2->getValue();
4757 if (!Xor.isAllOnesValue()) return 0;
4758
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004759 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004760 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004761 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004762 }
4763
4764 return 0;
4765}
4766
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004767Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4768 bool Changed = SimplifyCommutative(I);
4769 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4770
4771 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004772 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004773
4774 // or X, X = X
4775 if (Op0 == Op1)
4776 return ReplaceInstUsesWith(I, Op0);
4777
4778 // See if we can simplify any instructions used by the instruction whose sole
4779 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004780 if (SimplifyDemandedInstructionBits(I))
4781 return &I;
4782 if (isa<VectorType>(I.getType())) {
4783 if (isa<ConstantAggregateZero>(Op1)) {
4784 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4785 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4786 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4787 return ReplaceInstUsesWith(I, I.getOperand(1));
4788 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004789 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791 // or X, -1 == -1
4792 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4793 ConstantInt *C1 = 0; Value *X = 0;
4794 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004795 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004796 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004797 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004798 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004799 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004800 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004801 }
4802
4803 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004804 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004805 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004806 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004807 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004808 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004809 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004810 }
4811
4812 // Try to fold constant and into select arguments.
4813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4814 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4815 return R;
4816 if (isa<PHINode>(Op0))
4817 if (Instruction *NV = FoldOpIntoPhi(I))
4818 return NV;
4819 }
4820
4821 Value *A = 0, *B = 0;
4822 ConstantInt *C1 = 0, *C2 = 0;
4823
Dan Gohmancdff2122009-08-12 16:23:25 +00004824 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004825 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4826 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004827 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004828 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4829 return ReplaceInstUsesWith(I, Op0);
4830
4831 // (A | B) | C and A | (B | C) -> bswap if possible.
4832 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004833 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4834 match(Op1, m_Or(m_Value(), m_Value())) ||
4835 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4836 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004837 if (Instruction *BSwap = MatchBSwap(I))
4838 return BSwap;
4839 }
4840
4841 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004842 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004843 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004844 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004845 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004846 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004847 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004848 }
4849
4850 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004851 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004852 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004853 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004854 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004855 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004856 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004857 }
4858
4859 // (A & C)|(B & D)
4860 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004861 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4862 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004863 Value *V1 = 0, *V2 = 0, *V3 = 0;
4864 C1 = dyn_cast<ConstantInt>(C);
4865 C2 = dyn_cast<ConstantInt>(D);
4866 if (C1 && C2) { // (A & C1)|(B & C2)
4867 // If we have: ((V + N) & C1) | (V & C2)
4868 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4869 // replace with V+N.
4870 if (C1->getValue() == ~C2->getValue()) {
4871 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004872 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004873 // Add commutes, try both ways.
4874 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4875 return ReplaceInstUsesWith(I, A);
4876 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4877 return ReplaceInstUsesWith(I, A);
4878 }
4879 // Or commutes, try both ways.
4880 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004881 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004882 // Add commutes, try both ways.
4883 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4884 return ReplaceInstUsesWith(I, B);
4885 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4886 return ReplaceInstUsesWith(I, B);
4887 }
4888 }
4889 V1 = 0; V2 = 0; V3 = 0;
4890 }
4891
4892 // Check to see if we have any common things being and'ed. If so, find the
4893 // terms for V1 & (V2|V3).
4894 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4895 if (A == B) // (A & C)|(A & D) == A & (C|D)
4896 V1 = A, V2 = C, V3 = D;
4897 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4898 V1 = A, V2 = B, V3 = C;
4899 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4900 V1 = C, V2 = A, V3 = D;
4901 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4902 V1 = C, V2 = A, V3 = B;
4903
4904 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004905 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00004906 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004907 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004908 }
Dan Gohman279952c2008-10-28 22:38:57 +00004909
Dan Gohman35b76162008-10-30 20:40:10 +00004910 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004911 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004912 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004913 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004914 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004915 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004916 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004917 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004918 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004919
Bill Wendling22ca8352008-11-30 13:52:49 +00004920 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004921 if ((match(C, m_Not(m_Specific(D))) &&
4922 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004923 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004924 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004925 if ((match(A, m_Not(m_Specific(D))) &&
4926 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004927 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004928 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004929 if ((match(C, m_Not(m_Specific(B))) &&
4930 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004931 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004932 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004933 if ((match(A, m_Not(m_Specific(B))) &&
4934 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004935 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004936 }
4937
4938 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4939 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4940 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4941 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4942 SI0->getOperand(1) == SI1->getOperand(1) &&
4943 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004944 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4945 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004946 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004947 SI1->getOperand(1));
4948 }
4949 }
4950
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004951 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004952 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4953 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004954 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004955 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004956 }
4957 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004958 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4959 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004960 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004961 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004962 }
4963
Dan Gohmancdff2122009-08-12 16:23:25 +00004964 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004965 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004966 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004967 } else {
4968 A = 0;
4969 }
4970 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004971 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004972 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004973 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004974
4975 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4976 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004977 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004978 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004979 }
4980 }
4981
4982 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4983 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004984 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004985 return R;
4986
Chris Lattner0c678e52008-11-16 05:20:07 +00004987 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4988 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4989 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004990 }
4991
4992 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004993 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004994 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4995 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004996 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4997 !isa<ICmpInst>(Op1C->getOperand(0))) {
4998 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004999 if (SrcTy == Op1C->getOperand(0)->getType() &&
5000 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005001 // Only do this if the casts both really cause code to be
5002 // generated.
5003 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5004 I.getType(), TD) &&
5005 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5006 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005007 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5008 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005009 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005010 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005011 }
5012 }
Chris Lattner91882432007-10-24 05:38:08 +00005013 }
5014
5015
5016 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5017 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005018 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5019 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5020 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005021 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005022
5023 return Changed ? &I : 0;
5024}
5025
Dan Gohman089efff2008-05-13 00:00:25 +00005026namespace {
5027
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005028// XorSelf - Implements: X ^ X --> 0
5029struct XorSelf {
5030 Value *RHS;
5031 XorSelf(Value *rhs) : RHS(rhs) {}
5032 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5033 Instruction *apply(BinaryOperator &Xor) const {
5034 return &Xor;
5035 }
5036};
5037
Dan Gohman089efff2008-05-13 00:00:25 +00005038}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005039
5040Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5041 bool Changed = SimplifyCommutative(I);
5042 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5043
Evan Chenge5cd8032008-03-25 20:07:13 +00005044 if (isa<UndefValue>(Op1)) {
5045 if (isa<UndefValue>(Op0))
5046 // Handle undef ^ undef -> 0 special case. This is a common
5047 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005050 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005051
5052 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005053 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005054 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005056 }
5057
5058 // See if we can simplify any instructions used by the instruction whose sole
5059 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005060 if (SimplifyDemandedInstructionBits(I))
5061 return &I;
5062 if (isa<VectorType>(I.getType()))
5063 if (isa<ConstantAggregateZero>(Op1))
5064 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065
5066 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005067 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005068 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5069 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5071 if (Op0I->getOpcode() == Instruction::And ||
5072 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005073 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5074 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005075 Value *NotY =
5076 Builder->CreateNot(Op0I->getOperand(1),
5077 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005078 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005080 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005081 }
5082 }
5083 }
5084 }
5085
5086
5087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005088 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005089 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005090 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005091 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005092 ICI->getOperand(0), ICI->getOperand(1));
5093
Nick Lewycky1405e922007-08-06 20:04:16 +00005094 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005095 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005096 FCI->getOperand(0), FCI->getOperand(1));
5097 }
5098
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005099 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5100 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5101 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5102 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5103 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005104 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5105 (RHS == ConstantExpr::getCast(Opcode,
5106 ConstantInt::getTrue(*Context),
5107 Op0C->getDestTy()))) {
5108 CI->setPredicate(CI->getInversePredicate());
5109 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005110 }
5111 }
5112 }
5113 }
5114
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005115 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5116 // ~(c-X) == X-c-1 == X+(-c-1)
5117 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5118 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005119 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5120 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005121 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005123 }
5124
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005125 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005126 if (Op0I->getOpcode() == Instruction::Add) {
5127 // ~(X-c) --> (-c-1)-X
5128 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005129 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005130 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005131 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005132 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005133 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 } else if (RHS->getValue().isSignBit()) {
5135 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005136 Constant *C = ConstantInt::get(*Context,
5137 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005138 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139
5140 }
5141 } else if (Op0I->getOpcode() == Instruction::Or) {
5142 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5143 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005144 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005145 // Anything in both C1 and C2 is known to be zero, remove it from
5146 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005147 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5148 NewRHS = ConstantExpr::getAnd(NewRHS,
5149 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005150 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005151 I.setOperand(0, Op0I->getOperand(0));
5152 I.setOperand(1, NewRHS);
5153 return &I;
5154 }
5155 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005156 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005157 }
5158
5159 // Try to fold constant and into select arguments.
5160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5162 return R;
5163 if (isa<PHINode>(Op0))
5164 if (Instruction *NV = FoldOpIntoPhi(I))
5165 return NV;
5166 }
5167
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005168 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005169 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005170 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005172 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005173 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005174 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005175
5176
5177 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5178 if (Op1I) {
5179 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005180 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 if (A == Op0) { // B^(B|A) == (A|B)^B
5182 Op1I->swapOperands();
5183 I.swapOperands();
5184 std::swap(Op0, Op1);
5185 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5186 I.swapOperands(); // Simplified below.
5187 std::swap(Op0, Op1);
5188 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005189 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005190 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005191 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005192 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005193 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005194 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005195 if (A == Op0) { // A^(A&B) -> A^(B&A)
5196 Op1I->swapOperands();
5197 std::swap(A, B);
5198 }
5199 if (B == Op0) { // A^(B&A) -> (B&A)^A
5200 I.swapOperands(); // Simplified below.
5201 std::swap(Op0, Op1);
5202 }
5203 }
5204 }
5205
5206 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5207 if (Op0I) {
5208 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005209 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005210 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005211 if (A == Op1) // (B|A)^B == (A|B)^B
5212 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005213 if (B == Op1) // (A|B)^B == A & ~B
5214 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005215 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005216 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005217 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005218 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005219 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005220 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005221 if (A == Op1) // (A&B)^A -> (B&A)^A
5222 std::swap(A, B);
5223 if (B == Op1 && // (B&A)^A == ~B & A
5224 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005225 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005226 }
5227 }
5228 }
5229
5230 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5231 if (Op0I && Op1I && Op0I->isShift() &&
5232 Op0I->getOpcode() == Op1I->getOpcode() &&
5233 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5234 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005235 Value *NewOp =
5236 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5237 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005238 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 Op1I->getOperand(1));
5240 }
5241
5242 if (Op0I && Op1I) {
5243 Value *A, *B, *C, *D;
5244 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005245 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5246 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005247 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005248 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005249 }
5250 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005251 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5252 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005253 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005254 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005255 }
5256
5257 // (A & B)^(C & D)
5258 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005259 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5260 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005261 // (X & Y)^(X & Y) -> (Y^Z) & X
5262 Value *X = 0, *Y = 0, *Z = 0;
5263 if (A == C)
5264 X = A, Y = B, Z = D;
5265 else if (A == D)
5266 X = A, Y = B, Z = C;
5267 else if (B == C)
5268 X = B, Y = A, Z = D;
5269 else if (B == D)
5270 X = B, Y = A, Z = C;
5271
5272 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005273 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005274 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005275 }
5276 }
5277 }
5278
5279 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5280 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005281 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005282 return R;
5283
5284 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005285 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005286 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5287 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5288 const Type *SrcTy = Op0C->getOperand(0)->getType();
5289 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5290 // Only do this if the casts both really cause code to be generated.
5291 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5292 I.getType(), TD) &&
5293 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5294 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005295 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5296 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005297 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005298 }
5299 }
Chris Lattner91882432007-10-24 05:38:08 +00005300 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005301
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005302 return Changed ? &I : 0;
5303}
5304
Owen Anderson24be4c12009-07-03 00:17:18 +00005305static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005306 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005307 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005308}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005309
Dan Gohman8fd520a2009-06-15 22:12:54 +00005310static bool HasAddOverflow(ConstantInt *Result,
5311 ConstantInt *In1, ConstantInt *In2,
5312 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005313 if (IsSigned)
5314 if (In2->getValue().isNegative())
5315 return Result->getValue().sgt(In1->getValue());
5316 else
5317 return Result->getValue().slt(In1->getValue());
5318 else
5319 return Result->getValue().ult(In1->getValue());
5320}
5321
Dan Gohman8fd520a2009-06-15 22:12:54 +00005322/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005323/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005324static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005325 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005326 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005327 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005328
Dan Gohman8fd520a2009-06-15 22:12:54 +00005329 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5330 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005331 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005332 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5333 ExtractElement(In1, Idx, Context),
5334 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005335 IsSigned))
5336 return true;
5337 }
5338 return false;
5339 }
5340
5341 return HasAddOverflow(cast<ConstantInt>(Result),
5342 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5343 IsSigned);
5344}
5345
5346static bool HasSubOverflow(ConstantInt *Result,
5347 ConstantInt *In1, ConstantInt *In2,
5348 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005349 if (IsSigned)
5350 if (In2->getValue().isNegative())
5351 return Result->getValue().slt(In1->getValue());
5352 else
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().ugt(In1->getValue());
5356}
5357
Dan Gohman8fd520a2009-06-15 22:12:54 +00005358/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5359/// overflowed for this type.
5360static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005361 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005362 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005363 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005364
5365 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5366 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005367 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005368 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5369 ExtractElement(In1, Idx, Context),
5370 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005371 IsSigned))
5372 return true;
5373 }
5374 return false;
5375 }
5376
5377 return HasSubOverflow(cast<ConstantInt>(Result),
5378 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5379 IsSigned);
5380}
5381
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005382/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5383/// code necessary to compute the offset from the base pointer (without adding
5384/// in the base pointer). Return the result as a signed integer of intptr size.
5385static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005386 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005387 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson35b47072009-08-13 21:58:54 +00005388 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersonaac28372009-07-31 20:28:14 +00005389 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390
5391 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005392 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005393 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5394
Gabor Greif17396002008-06-12 21:37:33 +00005395 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5396 ++i, ++GTI) {
5397 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005398 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005399 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5400 if (OpC->isZero()) continue;
5401
5402 // Handle a struct index, which adds its field offset to the pointer.
5403 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5404 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5405
Chris Lattnerc7694852009-08-30 07:44:24 +00005406 Result = IC.Builder->CreateAdd(Result,
5407 ConstantInt::get(IntPtrTy, Size),
5408 GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005409 continue;
5410 }
5411
Owen Andersoneacb44d2009-07-24 23:12:02 +00005412 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005413 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005414 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5415 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnerc7694852009-08-30 07:44:24 +00005416 // Emit an add instruction.
5417 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005418 continue;
5419 }
5420 // Convert to correct type.
Chris Lattnerc7694852009-08-30 07:44:24 +00005421 if (Op->getType() != IntPtrTy)
5422 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005423 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005424 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnerc7694852009-08-30 07:44:24 +00005425 // We'll let instcombine(mul) convert this to a shl if possible.
5426 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005427 }
5428
5429 // Emit an add instruction.
Chris Lattnerc7694852009-08-30 07:44:24 +00005430 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 }
5432 return Result;
5433}
5434
Chris Lattnereba75862008-04-22 02:53:33 +00005435
Dan Gohmanff9b4732009-07-17 22:16:21 +00005436/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5437/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5438/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5439/// be complex, and scales are involved. The above expression would also be
5440/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5441/// This later form is less amenable to optimization though, and we are allowed
5442/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005443///
5444/// If we can't emit an optimized form for this expression, this returns null.
5445///
5446static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5447 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005448 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005449 gep_type_iterator GTI = gep_type_begin(GEP);
5450
5451 // Check to see if this gep only has a single variable index. If so, and if
5452 // any constant indices are a multiple of its scale, then we can compute this
5453 // in terms of the scale of the variable index. For example, if the GEP
5454 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5455 // because the expression will cross zero at the same point.
5456 unsigned i, e = GEP->getNumOperands();
5457 int64_t Offset = 0;
5458 for (i = 1; i != e; ++i, ++GTI) {
5459 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5460 // Compute the aggregate offset of constant indices.
5461 if (CI->isZero()) continue;
5462
5463 // Handle a struct index, which adds its field offset to the pointer.
5464 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5465 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5466 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005467 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005468 Offset += Size*CI->getSExtValue();
5469 }
5470 } else {
5471 // Found our variable index.
5472 break;
5473 }
5474 }
5475
5476 // If there are no variable indices, we must have a constant offset, just
5477 // evaluate it the general way.
5478 if (i == e) return 0;
5479
5480 Value *VariableIdx = GEP->getOperand(i);
5481 // Determine the scale factor of the variable element. For example, this is
5482 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005483 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005484
5485 // Verify that there are no other variable indices. If so, emit the hard way.
5486 for (++i, ++GTI; i != e; ++i, ++GTI) {
5487 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5488 if (!CI) return 0;
5489
5490 // Compute the aggregate offset of constant indices.
5491 if (CI->isZero()) continue;
5492
5493 // Handle a struct index, which adds its field offset to the pointer.
5494 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005497 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005498 Offset += Size*CI->getSExtValue();
5499 }
5500 }
5501
5502 // Okay, we know we have a single variable index, which must be a
5503 // pointer/array/vector index. If there is no offset, life is simple, return
5504 // the index.
5505 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5506 if (Offset == 0) {
5507 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5508 // we don't need to bother extending: the extension won't affect where the
5509 // computation crosses zero.
5510 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson35b47072009-08-13 21:58:54 +00005511 VariableIdx = new TruncInst(VariableIdx,
5512 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005513 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005514 return VariableIdx;
5515 }
5516
5517 // Otherwise, there is an index. The computation we will do will be modulo
5518 // the pointer size, so get it.
5519 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5520
5521 Offset &= PtrSizeMask;
5522 VariableScale &= PtrSizeMask;
5523
5524 // To do this transformation, any constant index must be a multiple of the
5525 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5526 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5527 // multiple of the variable scale.
5528 int64_t NewOffs = Offset / (int64_t)VariableScale;
5529 if (Offset != NewOffs*(int64_t)VariableScale)
5530 return 0;
5531
5532 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson35b47072009-08-13 21:58:54 +00005533 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattnereba75862008-04-22 02:53:33 +00005534 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005535 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005536 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005537 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005538 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005539 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005540}
5541
5542
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005543/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5544/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005545Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005546 ICmpInst::Predicate Cond,
5547 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005548 // Look through bitcasts.
5549 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5550 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005551
5552 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005553 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005554 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005555 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005556 // know pointers can't overflow since the gep is inbounds. See if we can
5557 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005558 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5559
5560 // If not, synthesize the offset the hard way.
5561 if (Offset == 0)
5562 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005563 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005564 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005565 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005566 // If the base pointers are different, but the indices are the same, just
5567 // compare the base pointer.
5568 if (PtrBase != GEPRHS->getOperand(0)) {
5569 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5570 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5571 GEPRHS->getOperand(0)->getType();
5572 if (IndicesTheSame)
5573 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5574 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5575 IndicesTheSame = false;
5576 break;
5577 }
5578
5579 // If all indices are the same, just compare the base pointers.
5580 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005581 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005582 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5583
5584 // Otherwise, the base pointers are different and the indices are
5585 // different, bail out.
5586 return 0;
5587 }
5588
5589 // If one of the GEPs has all zero indices, recurse.
5590 bool AllZeros = true;
5591 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5592 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5593 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5594 AllZeros = false;
5595 break;
5596 }
5597 if (AllZeros)
5598 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5599 ICmpInst::getSwappedPredicate(Cond), I);
5600
5601 // If the other GEP has all zero indices, recurse.
5602 AllZeros = true;
5603 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5604 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5605 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5606 AllZeros = false;
5607 break;
5608 }
5609 if (AllZeros)
5610 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5611
5612 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5613 // If the GEPs only differ by one index, compare it.
5614 unsigned NumDifferences = 0; // Keep track of # differences.
5615 unsigned DiffOperand = 0; // The operand that differs.
5616 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5617 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5618 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5619 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5620 // Irreconcilable differences.
5621 NumDifferences = 2;
5622 break;
5623 } else {
5624 if (NumDifferences++) break;
5625 DiffOperand = i;
5626 }
5627 }
5628
5629 if (NumDifferences == 0) // SAME GEP?
5630 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005631 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005632 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005633
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005634 else if (NumDifferences == 1) {
5635 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5636 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5637 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005638 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005639 }
5640 }
5641
5642 // Only lower this if the icmp is the only user of the GEP or if we expect
5643 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005644 if (TD &&
5645 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005646 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5647 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5648 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5649 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005650 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005651 }
5652 }
5653 return 0;
5654}
5655
Chris Lattnere6b62d92008-05-19 20:18:56 +00005656/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5657///
5658Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5659 Instruction *LHSI,
5660 Constant *RHSC) {
5661 if (!isa<ConstantFP>(RHSC)) return 0;
5662 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5663
5664 // Get the width of the mantissa. We don't want to hack on conversions that
5665 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005666 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005667 if (MantissaWidth == -1) return 0; // Unknown.
5668
5669 // Check to see that the input is converted from an integer type that is small
5670 // enough that preserves all bits. TODO: check here for "known" sign bits.
5671 // 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 +00005672 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005673
5674 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005675 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5676 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005677 ++InputSize;
5678
5679 // If the conversion would lose info, don't hack on this.
5680 if ((int)InputSize > MantissaWidth)
5681 return 0;
5682
5683 // Otherwise, we can potentially simplify the comparison. We know that it
5684 // will always come through as an integer value and we know the constant is
5685 // not a NAN (it would have been previously simplified).
5686 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5687
5688 ICmpInst::Predicate Pred;
5689 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005690 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005691 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005692 case FCmpInst::FCMP_OEQ:
5693 Pred = ICmpInst::ICMP_EQ;
5694 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005695 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005696 case FCmpInst::FCMP_OGT:
5697 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5698 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005699 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005700 case FCmpInst::FCMP_OGE:
5701 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5702 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005703 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005704 case FCmpInst::FCMP_OLT:
5705 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5706 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005707 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005708 case FCmpInst::FCMP_OLE:
5709 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5710 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005711 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005712 case FCmpInst::FCMP_ONE:
5713 Pred = ICmpInst::ICMP_NE;
5714 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005715 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005716 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005717 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005718 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005719 }
5720
5721 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5722
5723 // Now we know that the APFloat is a normal number, zero or inf.
5724
Chris Lattnerf13ff492008-05-20 03:50:52 +00005725 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005726 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005727 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005728
Bill Wendling20636df2008-11-09 04:26:50 +00005729 if (!LHSUnsigned) {
5730 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5731 // and large values.
5732 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5733 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5734 APFloat::rmNearestTiesToEven);
5735 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5736 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5737 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005738 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5739 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005740 }
5741 } else {
5742 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5743 // +INF and large values.
5744 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5745 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5746 APFloat::rmNearestTiesToEven);
5747 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5748 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5749 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5751 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005752 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005753 }
5754
Bill Wendling20636df2008-11-09 04:26:50 +00005755 if (!LHSUnsigned) {
5756 // See if the RHS value is < SignedMin.
5757 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5758 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5759 APFloat::rmNearestTiesToEven);
5760 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5761 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5762 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005763 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5764 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005765 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005766 }
5767
Bill Wendling20636df2008-11-09 04:26:50 +00005768 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5769 // [0, UMAX], but it may still be fractional. See if it is fractional by
5770 // casting the FP value to the integer value and back, checking for equality.
5771 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005772 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005773 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5774 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005775 if (!RHS.isZero()) {
5776 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005777 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5778 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005779 if (!Equal) {
5780 // If we had a comparison against a fractional value, we have to adjust
5781 // the compare predicate and sometimes the value. RHSC is rounded towards
5782 // zero at this point.
5783 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005784 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005785 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005786 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005787 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005788 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005789 case ICmpInst::ICMP_ULE:
5790 // (float)int <= 4.4 --> int <= 4
5791 // (float)int <= -4.4 --> false
5792 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005793 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005794 break;
5795 case ICmpInst::ICMP_SLE:
5796 // (float)int <= 4.4 --> int <= 4
5797 // (float)int <= -4.4 --> int < -4
5798 if (RHS.isNegative())
5799 Pred = ICmpInst::ICMP_SLT;
5800 break;
5801 case ICmpInst::ICMP_ULT:
5802 // (float)int < -4.4 --> false
5803 // (float)int < 4.4 --> int <= 4
5804 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005805 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005806 Pred = ICmpInst::ICMP_ULE;
5807 break;
5808 case ICmpInst::ICMP_SLT:
5809 // (float)int < -4.4 --> int < -4
5810 // (float)int < 4.4 --> int <= 4
5811 if (!RHS.isNegative())
5812 Pred = ICmpInst::ICMP_SLE;
5813 break;
5814 case ICmpInst::ICMP_UGT:
5815 // (float)int > 4.4 --> int > 4
5816 // (float)int > -4.4 --> true
5817 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005818 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005819 break;
5820 case ICmpInst::ICMP_SGT:
5821 // (float)int > 4.4 --> int > 4
5822 // (float)int > -4.4 --> int >= -4
5823 if (RHS.isNegative())
5824 Pred = ICmpInst::ICMP_SGE;
5825 break;
5826 case ICmpInst::ICMP_UGE:
5827 // (float)int >= -4.4 --> true
5828 // (float)int >= 4.4 --> int > 4
5829 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005830 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005831 Pred = ICmpInst::ICMP_UGT;
5832 break;
5833 case ICmpInst::ICMP_SGE:
5834 // (float)int >= -4.4 --> int >= -4
5835 // (float)int >= 4.4 --> int > 4
5836 if (!RHS.isNegative())
5837 Pred = ICmpInst::ICMP_SGT;
5838 break;
5839 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005840 }
5841 }
5842
5843 // Lower this FP comparison into an appropriate integer version of the
5844 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005845 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005846}
5847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005848Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5849 bool Changed = SimplifyCompare(I);
5850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5851
5852 // Fold trivial predicates.
5853 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner41c09932009-09-02 05:12:37 +00005854 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005855 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner41c09932009-09-02 05:12:37 +00005856 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005857
5858 // Simplify 'fcmp pred X, X'
5859 if (Op0 == Op1) {
5860 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005861 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005862 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5863 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5864 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner41c09932009-09-02 05:12:37 +00005865 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005866 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5867 case FCmpInst::FCMP_OLT: // True if ordered and less than
5868 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner41c09932009-09-02 05:12:37 +00005869 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005870
5871 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5872 case FCmpInst::FCMP_ULT: // True if unordered or less than
5873 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5874 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5875 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5876 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005877 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005878 return &I;
5879
5880 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5881 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5882 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5883 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5884 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5885 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005886 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005887 return &I;
5888 }
5889 }
5890
5891 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005892 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005893
5894 // Handle fcmp with constant RHS
5895 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005896 // If the constant is a nan, see if we can fold the comparison based on it.
5897 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5898 if (CFP->getValueAPF().isNaN()) {
5899 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005900 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005901 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5902 "Comparison must be either ordered or unordered!");
5903 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005904 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005905 }
5906 }
5907
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005908 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5909 switch (LHSI->getOpcode()) {
5910 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005911 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5912 // block. If in the same block, we're encouraging jump threading. If
5913 // not, we are just pessimizing the code by making an i1 phi.
5914 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00005915 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00005916 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005917 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005918 case Instruction::SIToFP:
5919 case Instruction::UIToFP:
5920 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5921 return NV;
5922 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005923 case Instruction::Select:
5924 // If either operand of the select is a constant, we can fold the
5925 // comparison into the select arms, which will cause one to be
5926 // constant folded and the select turned into a bitwise or.
5927 Value *Op1 = 0, *Op2 = 0;
5928 if (LHSI->hasOneUse()) {
5929 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5930 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005931 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005932 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005933 Op2 = Builder->CreateFCmp(I.getPredicate(),
5934 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005935 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5936 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005937 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005938 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005939 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5940 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005941 }
5942 }
5943
5944 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005945 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005946 break;
5947 }
5948 }
5949
5950 return Changed ? &I : 0;
5951}
5952
5953Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5954 bool Changed = SimplifyCompare(I);
5955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5956 const Type *Ty = Op0->getType();
5957
5958 // icmp X, X
5959 if (Op0 == Op1)
Chris Lattner41c09932009-09-02 05:12:37 +00005960 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005961 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962
5963 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005964 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lambf78cd322007-12-18 21:32:20 +00005965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005966 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5967 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattner95ac4eb2009-10-05 02:47:47 +00005968 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005969 isa<ConstantPointerNull>(Op0)) &&
Chris Lattner95ac4eb2009-10-05 02:47:47 +00005970 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005971 isa<ConstantPointerNull>(Op1)))
Owen Anderson35b47072009-08-13 21:58:54 +00005972 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005973 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005974
5975 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00005976 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005977 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005978 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005979 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00005980 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00005981 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005982 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005983 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005984 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005985
5986 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005987 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005988 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005989 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00005990 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005991 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005992 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005993 case ICmpInst::ICMP_SGT:
5994 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005995 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005996 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005997 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005998 return BinaryOperator::CreateAnd(Not, Op0);
5999 }
6000 case ICmpInst::ICMP_UGE:
6001 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6002 // FALL THROUGH
6003 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006004 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006005 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006006 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006007 case ICmpInst::ICMP_SGE:
6008 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6009 // FALL THROUGH
6010 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006011 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006012 return BinaryOperator::CreateOr(Not, Op0);
6013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006014 }
6015 }
6016
Dan Gohman7934d592009-04-25 17:12:48 +00006017 unsigned BitWidth = 0;
6018 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006019 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6020 else if (Ty->isIntOrIntVector())
6021 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006022
6023 bool isSignBit = false;
6024
Dan Gohman58c09632008-09-16 18:46:06 +00006025 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006026 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006027 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006028
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006029 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6030 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006031 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006032 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006033 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006034 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006035
Dan Gohman58c09632008-09-16 18:46:06 +00006036 // If we have an icmp le or icmp ge instruction, turn it into the
6037 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6038 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006039 switch (I.getPredicate()) {
6040 default: break;
6041 case ICmpInst::ICMP_ULE:
6042 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006043 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006044 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006045 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006046 case ICmpInst::ICMP_SLE:
6047 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006048 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006049 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006050 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006051 case ICmpInst::ICMP_UGE:
6052 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006053 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006054 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006055 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006056 case ICmpInst::ICMP_SGE:
6057 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006058 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006059 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006060 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006061 }
6062
Chris Lattnera1308652008-07-11 05:40:05 +00006063 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006064 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006065 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006066 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6067 }
6068
6069 // See if we can fold the comparison based on range information we can get
6070 // by checking whether bits are known to be zero or one in the input.
6071 if (BitWidth != 0) {
6072 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6073 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6074
6075 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006076 isSignBit ? APInt::getSignBit(BitWidth)
6077 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006078 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006079 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006080 if (SimplifyDemandedBits(I.getOperandUse(1),
6081 APInt::getAllOnesValue(BitWidth),
6082 Op1KnownZero, Op1KnownOne, 0))
6083 return &I;
6084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006085 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006086 // in. Compute the Min, Max and RHS values based on the known bits. For the
6087 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006088 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6089 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6090 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6091 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6092 Op0Min, Op0Max);
6093 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6094 Op1Min, Op1Max);
6095 } else {
6096 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6097 Op0Min, Op0Max);
6098 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6099 Op1Min, Op1Max);
6100 }
6101
Chris Lattnera1308652008-07-11 05:40:05 +00006102 // If Min and Max are known to be the same, then SimplifyDemandedBits
6103 // figured out that the LHS is a constant. Just constant fold this now so
6104 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006105 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006106 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006107 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006108 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006109 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006110 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006111
Chris Lattnera1308652008-07-11 05:40:05 +00006112 // Based on the range information we know about the LHS, see if we can
6113 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006114 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006115 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006116 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006117 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006119 break;
6120 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006121 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006122 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006123 break;
6124 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006125 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006126 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006127 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006128 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006129 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006130 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006131 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6132 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006133 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006134 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006135
6136 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6137 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006138 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006139 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006140 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006141 break;
6142 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006143 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006145 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006147
6148 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006149 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006150 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6151 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006152 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006153 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006154
6155 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6156 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006157 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006158 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006159 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006160 break;
6161 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006162 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006164 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006166 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006167 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006170 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006171 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006172 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006173 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006174 case ICmpInst::ICMP_SGT:
6175 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006177 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006178 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006179
6180 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006181 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006184 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006185 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006186 }
6187 break;
6188 case ICmpInst::ICMP_SGE:
6189 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6190 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006191 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006192 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006193 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006194 break;
6195 case ICmpInst::ICMP_SLE:
6196 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6197 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006198 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006199 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006201 break;
6202 case ICmpInst::ICMP_UGE:
6203 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6204 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006205 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006206 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006207 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006208 break;
6209 case ICmpInst::ICMP_ULE:
6210 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6211 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006212 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006213 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006215 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006216 }
Dan Gohman7934d592009-04-25 17:12:48 +00006217
6218 // Turn a signed comparison into an unsigned one if both operands
6219 // are known to have the same sign.
6220 if (I.isSignedPredicate() &&
6221 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6222 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006223 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006224 }
6225
6226 // Test if the ICmpInst instruction is used exclusively by a select as
6227 // part of a minimum or maximum operation. If so, refrain from doing
6228 // any other folding. This helps out other analyses which understand
6229 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6230 // and CodeGen. And in this case, at least one of the comparison
6231 // operands has at least one user besides the compare (the select),
6232 // which would often largely negate the benefit of folding anyway.
6233 if (I.hasOneUse())
6234 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6235 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6236 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6237 return 0;
6238
6239 // See if we are doing a comparison between a constant and an instruction that
6240 // can be folded into the comparison.
6241 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006242 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6243 // instruction, see if that instruction also has constants so that the
6244 // instruction can be folded into the icmp
6245 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6246 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6247 return Res;
6248 }
6249
6250 // Handle icmp with constant (but not simple integer constant) RHS
6251 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6252 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6253 switch (LHSI->getOpcode()) {
6254 case Instruction::GetElementPtr:
6255 if (RHSC->isNullValue()) {
6256 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6257 bool isAllZeros = true;
6258 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6259 if (!isa<Constant>(LHSI->getOperand(i)) ||
6260 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6261 isAllZeros = false;
6262 break;
6263 }
6264 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006265 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006266 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006267 }
6268 break;
6269
6270 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006271 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006272 // block. If in the same block, we're encouraging jump threading. If
6273 // not, we are just pessimizing the code by making an i1 phi.
6274 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006275 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006276 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006277 break;
6278 case Instruction::Select: {
6279 // If either operand of the select is a constant, we can fold the
6280 // comparison into the select arms, which will cause one to be
6281 // constant folded and the select turned into a bitwise or.
6282 Value *Op1 = 0, *Op2 = 0;
6283 if (LHSI->hasOneUse()) {
6284 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6285 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006286 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006287 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006288 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6289 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006290 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6291 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006292 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006293 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006294 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6295 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006296 }
6297 }
6298
6299 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006300 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006301 break;
6302 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006303 case Instruction::Call:
6304 // If we have (malloc != null), and if the malloc has a single use, we
6305 // can assume it is successful and remove the malloc.
6306 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6307 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006308 // Need to explicitly erase malloc call here, instead of adding it to
6309 // Worklist, because it won't get DCE'd from the Worklist since
6310 // isInstructionTriviallyDead() returns false for function calls.
6311 // It is OK to replace LHSI/MallocCall with Undef because the
6312 // instruction that uses it will be erased via Worklist.
6313 if (extractMallocCall(LHSI)) {
6314 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6315 EraseInstFromFunction(*LHSI);
6316 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006317 ConstantInt::get(Type::getInt1Ty(*Context),
6318 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006319 }
6320 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6321 if (MallocCall->hasOneUse()) {
6322 MallocCall->replaceAllUsesWith(
6323 UndefValue::get(MallocCall->getType()));
6324 EraseInstFromFunction(*MallocCall);
6325 Worklist.Add(LHSI); // The malloc's bitcast use.
6326 return ReplaceInstUsesWith(I,
6327 ConstantInt::get(Type::getInt1Ty(*Context),
6328 !I.isTrueWhenEqual()));
6329 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006330 }
6331 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006332 }
6333 }
6334
6335 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006336 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006337 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6338 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006339 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006340 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6341 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6342 return NI;
6343
6344 // Test to see if the operands of the icmp are casted versions of other
6345 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6346 // now.
6347 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6348 if (isa<PointerType>(Op0->getType()) &&
6349 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6350 // We keep moving the cast from the left operand over to the right
6351 // operand, where it can often be eliminated completely.
6352 Op0 = CI->getOperand(0);
6353
6354 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6355 // so eliminate it as well.
6356 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6357 Op1 = CI2->getOperand(0);
6358
6359 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006360 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006361 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006362 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006363 } else {
6364 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006365 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006366 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006367 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006368 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006369 }
6370 }
6371
6372 if (isa<CastInst>(Op0)) {
6373 // Handle the special case of: icmp (cast bool to X), <cst>
6374 // This comes up when you have code like
6375 // int X = A < B;
6376 // if (X) ...
6377 // For generality, we handle any zero-extension of any operand comparison
6378 // with a constant or another cast from the same type.
6379 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6380 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6381 return R;
6382 }
6383
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006384 // See if it's the same type of instruction on the left and right.
6385 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6386 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006387 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006388 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006389 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006390 default: break;
6391 case Instruction::Add:
6392 case Instruction::Sub:
6393 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006394 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006395 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006396 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006397 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6398 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6399 if (CI->getValue().isSignBit()) {
6400 ICmpInst::Predicate Pred = I.isSignedPredicate()
6401 ? I.getUnsignedPredicate()
6402 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006403 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006404 Op1I->getOperand(0));
6405 }
6406
6407 if (CI->getValue().isMaxSignedValue()) {
6408 ICmpInst::Predicate Pred = I.isSignedPredicate()
6409 ? I.getUnsignedPredicate()
6410 : I.getSignedPredicate();
6411 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006412 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006413 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006414 }
6415 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006416 break;
6417 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006418 if (!I.isEquality())
6419 break;
6420
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6423 // Mask = -1 >> count-trailing-zeros(Cst).
6424 if (!CI->isZero() && !CI->isOne()) {
6425 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006426 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006427 APInt::getLowBitsSet(AP.getBitWidth(),
6428 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006429 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006430 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6431 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006432 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006433 }
6434 }
6435 break;
6436 }
6437 }
6438 }
6439 }
6440
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006441 // ~x < ~y --> y < x
6442 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006443 if (match(Op0, m_Not(m_Value(A))) &&
6444 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006445 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006446 }
6447
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006448 if (I.isEquality()) {
6449 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006450
6451 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006452 if (match(Op0, m_Neg(m_Value(A))) &&
6453 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006454 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006455
Dan Gohmancdff2122009-08-12 16:23:25 +00006456 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006457 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6458 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006459 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006460 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006461 }
6462
Dan Gohmancdff2122009-08-12 16:23:25 +00006463 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006464 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006465 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006466 if (match(B, m_ConstantInt(C1)) &&
6467 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006468 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006469 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006470 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6471 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006472 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006473
6474 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006475 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6476 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6477 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6478 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006479 }
6480 }
6481
Dan Gohmancdff2122009-08-12 16:23:25 +00006482 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006483 (A == Op0 || B == Op0)) {
6484 // A == (A^B) -> B == 0
6485 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006486 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006487 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006488 }
Chris Lattner3b874082008-11-16 05:38:51 +00006489
6490 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006491 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006492 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006493 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006494
6495 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006496 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006497 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006498 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006499
6500 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6501 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006502 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6503 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006504 Value *X = 0, *Y = 0, *Z = 0;
6505
6506 if (A == C) {
6507 X = B; Y = D; Z = A;
6508 } else if (A == D) {
6509 X = B; Y = C; Z = A;
6510 } else if (B == C) {
6511 X = A; Y = D; Z = B;
6512 } else if (B == D) {
6513 X = A; Y = C; Z = B;
6514 }
6515
6516 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006517 Op1 = Builder->CreateXor(X, Y, "tmp");
6518 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006519 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006520 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006521 return &I;
6522 }
6523 }
6524 }
6525 return Changed ? &I : 0;
6526}
6527
6528
6529/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6530/// and CmpRHS are both known to be integer constants.
6531Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6532 ConstantInt *DivRHS) {
6533 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6534 const APInt &CmpRHSV = CmpRHS->getValue();
6535
6536 // FIXME: If the operand types don't match the type of the divide
6537 // then don't attempt this transform. The code below doesn't have the
6538 // logic to deal with a signed divide and an unsigned compare (and
6539 // vice versa). This is because (x /s C1) <s C2 produces different
6540 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6541 // (x /u C1) <u C2. Simply casting the operands and result won't
6542 // work. :( The if statement below tests that condition and bails
6543 // if it finds it.
6544 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6545 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6546 return 0;
6547 if (DivRHS->isZero())
6548 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006549 if (DivIsSigned && DivRHS->isAllOnesValue())
6550 return 0; // The overflow computation also screws up here
6551 if (DivRHS->isOne())
6552 return 0; // Not worth bothering, and eliminates some funny cases
6553 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006554
6555 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6556 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6557 // C2 (CI). By solving for X we can turn this into a range check
6558 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006559 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006560
6561 // Determine if the product overflows by seeing if the product is
6562 // not equal to the divide. Make sure we do the same kind of divide
6563 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006564 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6565 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566
6567 // Get the ICmp opcode
6568 ICmpInst::Predicate Pred = ICI.getPredicate();
6569
6570 // Figure out the interval that is being checked. For example, a comparison
6571 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6572 // Compute this interval based on the constants involved and the signedness of
6573 // the compare/divide. This computes a half-open interval, keeping track of
6574 // whether either value in the interval overflows. After analysis each
6575 // overflow variable is set to 0 if it's corresponding bound variable is valid
6576 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6577 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006578 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006579
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006580 if (!DivIsSigned) { // udiv
6581 // e.g. X/5 op 3 --> [15, 20)
6582 LoBound = Prod;
6583 HiOverflow = LoOverflow = ProdOV;
6584 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006585 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006586 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006587 if (CmpRHSV == 0) { // (X / pos) op 0
6588 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006589 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006590 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006591 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006592 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6593 HiOverflow = LoOverflow = ProdOV;
6594 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006595 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006596 } else { // (X / pos) op neg
6597 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006598 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006599 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6600 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006601 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006602 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006603 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006604 true) ? -1 : 0;
6605 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006606 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006607 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608 if (CmpRHSV == 0) { // (X / neg) op 0
6609 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006610 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006611 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006612 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6613 HiOverflow = 1; // [INTMIN+1, overflow)
6614 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6615 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006616 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006617 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006618 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006619 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6620 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006621 LoOverflow = AddWithOverflow(LoBound, HiBound,
6622 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006623 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006624 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6625 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006626 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006627 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 }
6629
6630 // Dividing by a negative swaps the condition. LT <-> GT
6631 Pred = ICmpInst::getSwappedPredicate(Pred);
6632 }
6633
6634 Value *X = DivI->getOperand(0);
6635 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006636 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006637 case ICmpInst::ICMP_EQ:
6638 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006639 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006641 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006642 ICmpInst::ICMP_UGE, X, LoBound);
6643 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006644 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 ICmpInst::ICMP_ULT, X, HiBound);
6646 else
6647 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6648 case ICmpInst::ICMP_NE:
6649 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006650 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006652 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653 ICmpInst::ICMP_ULT, X, LoBound);
6654 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006655 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 ICmpInst::ICMP_UGE, X, HiBound);
6657 else
6658 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6659 case ICmpInst::ICMP_ULT:
6660 case ICmpInst::ICMP_SLT:
6661 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006662 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006663 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006664 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006665 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006666 case ICmpInst::ICMP_UGT:
6667 case ICmpInst::ICMP_SGT:
6668 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006669 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006671 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006672 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006673 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006674 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006675 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006676 }
6677}
6678
6679
6680/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6681///
6682Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6683 Instruction *LHSI,
6684 ConstantInt *RHS) {
6685 const APInt &RHSV = RHS->getValue();
6686
6687 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006688 case Instruction::Trunc:
6689 if (ICI.isEquality() && LHSI->hasOneUse()) {
6690 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6691 // of the high bits truncated out of x are known.
6692 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6693 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6694 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6695 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6696 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6697
6698 // If all the high bits are known, we can do this xform.
6699 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6700 // Pull in the high bits from known-ones set.
6701 APInt NewRHS(RHS->getValue());
6702 NewRHS.zext(SrcBits);
6703 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006704 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006705 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006706 }
6707 }
6708 break;
6709
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006710 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6711 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6712 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6713 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006714 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6715 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006716 Value *CompareVal = LHSI->getOperand(0);
6717
6718 // If the sign bit of the XorCST is not set, there is no change to
6719 // the operation, just stop using the Xor.
6720 if (!XorCST->getValue().isNegative()) {
6721 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006722 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006723 return &ICI;
6724 }
6725
6726 // Was the old condition true if the operand is positive?
6727 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6728
6729 // If so, the new one isn't.
6730 isTrueIfPositive ^= true;
6731
6732 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006733 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006734 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006735 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006736 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006737 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006738 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006739
6740 if (LHSI->hasOneUse()) {
6741 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6742 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6743 const APInt &SignBit = XorCST->getValue();
6744 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6745 ? ICI.getUnsignedPredicate()
6746 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006747 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006748 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006749 }
6750
6751 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006752 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006753 const APInt &NotSignBit = XorCST->getValue();
6754 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6755 ? ICI.getUnsignedPredicate()
6756 : ICI.getSignedPredicate();
6757 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006758 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006759 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006760 }
6761 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006762 }
6763 break;
6764 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6765 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6766 LHSI->getOperand(0)->hasOneUse()) {
6767 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6768
6769 // If the LHS is an AND of a truncating cast, we can widen the
6770 // and/compare to be the input width without changing the value
6771 // produced, eliminating a cast.
6772 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6773 // We can do this transformation if either the AND constant does not
6774 // have its sign bit set or if it is an equality comparison.
6775 // Extending a relational comparison when we're checking the sign
6776 // bit would not work.
6777 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006778 (ICI.isEquality() ||
6779 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006780 uint32_t BitWidth =
6781 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6782 APInt NewCST = AndCST->getValue();
6783 NewCST.zext(BitWidth);
6784 APInt NewCI = RHSV;
6785 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006786 Value *NewAnd =
6787 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006788 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006789 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006790 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006791 }
6792 }
6793
6794 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6795 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6796 // happens a LOT in code produced by the C front-end, for bitfield
6797 // access.
6798 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6799 if (Shift && !Shift->isShift())
6800 Shift = 0;
6801
6802 ConstantInt *ShAmt;
6803 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6804 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6805 const Type *AndTy = AndCST->getType(); // Type of the and.
6806
6807 // We can fold this as long as we can't shift unknown bits
6808 // into the mask. This can only happen with signed shift
6809 // rights, as they sign-extend.
6810 if (ShAmt) {
6811 bool CanFold = Shift->isLogicalShift();
6812 if (!CanFold) {
6813 // To test for the bad case of the signed shr, see if any
6814 // of the bits shifted in could be tested after the mask.
6815 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6816 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6817
6818 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6819 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6820 AndCST->getValue()) == 0)
6821 CanFold = true;
6822 }
6823
6824 if (CanFold) {
6825 Constant *NewCst;
6826 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006827 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006828 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006829 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006830
6831 // Check to see if we are shifting out any of the bits being
6832 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006833 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006834 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006835 // If we shifted bits out, the fold is not going to work out.
6836 // As a special case, check to see if this means that the
6837 // result is always true or false now.
6838 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006839 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006840 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006841 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006842 } else {
6843 ICI.setOperand(1, NewCst);
6844 Constant *NewAndCST;
6845 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006846 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006847 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006848 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006849 LHSI->setOperand(1, NewAndCST);
6850 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006851 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006852 return &ICI;
6853 }
6854 }
6855 }
6856
6857 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6858 // preferable because it allows the C<<Y expression to be hoisted out
6859 // of a loop if Y is invariant and X is not.
6860 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006861 ICI.isEquality() && !Shift->isArithmeticShift() &&
6862 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006863 // Compute C << Y.
6864 Value *NS;
6865 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006866 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006867 } else {
6868 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006869 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006871
6872 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006873 Value *NewAnd =
6874 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006875
6876 ICI.setOperand(0, NewAnd);
6877 return &ICI;
6878 }
6879 }
6880 break;
6881
6882 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6883 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6884 if (!ShAmt) break;
6885
6886 uint32_t TypeBits = RHSV.getBitWidth();
6887
6888 // Check that the shift amount is in range. If not, don't perform
6889 // undefined shifts. When the shift is visited it will be
6890 // simplified.
6891 if (ShAmt->uge(TypeBits))
6892 break;
6893
6894 if (ICI.isEquality()) {
6895 // If we are comparing against bits always shifted out, the
6896 // comparison cannot succeed.
6897 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006898 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006899 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006900 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6901 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006902 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006903 return ReplaceInstUsesWith(ICI, Cst);
6904 }
6905
6906 if (LHSI->hasOneUse()) {
6907 // Otherwise strength reduce the shift into an and.
6908 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6909 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006910 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006911 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006912
Chris Lattnerc7694852009-08-30 07:44:24 +00006913 Value *And =
6914 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006915 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006916 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006917 }
6918 }
6919
6920 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6921 bool TrueIfSigned = false;
6922 if (LHSI->hasOneUse() &&
6923 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6924 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006925 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006926 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00006927 Value *And =
6928 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006929 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006930 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006931 }
6932 break;
6933 }
6934
6935 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6936 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006937 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006938 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006939 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006940
Chris Lattner5ee84f82008-03-21 05:19:58 +00006941 // Check that the shift amount is in range. If not, don't perform
6942 // undefined shifts. When the shift is visited it will be
6943 // simplified.
6944 uint32_t TypeBits = RHSV.getBitWidth();
6945 if (ShAmt->uge(TypeBits))
6946 break;
6947
6948 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949
Chris Lattner5ee84f82008-03-21 05:19:58 +00006950 // If we are comparing against bits always shifted out, the
6951 // comparison cannot succeed.
6952 APInt Comp = RHSV << ShAmtVal;
6953 if (LHSI->getOpcode() == Instruction::LShr)
6954 Comp = Comp.lshr(ShAmtVal);
6955 else
6956 Comp = Comp.ashr(ShAmtVal);
6957
6958 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6959 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006960 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006961 return ReplaceInstUsesWith(ICI, Cst);
6962 }
6963
6964 // Otherwise, check to see if the bits shifted out are known to be zero.
6965 // If so, we can compare against the unshifted value:
6966 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006967 if (LHSI->hasOneUse() &&
6968 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006969 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006970 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006971 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006972 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006973
Evan Chengfb9292a2008-04-23 00:38:06 +00006974 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006975 // Otherwise strength reduce the shift into an and.
6976 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00006977 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006978
Chris Lattnerc7694852009-08-30 07:44:24 +00006979 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6980 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006981 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00006982 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006983 }
6984 break;
6985 }
6986
6987 case Instruction::SDiv:
6988 case Instruction::UDiv:
6989 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6990 // Fold this div into the comparison, producing a range check.
6991 // Determine, based on the divide type, what the range is being
6992 // checked. If there is an overflow on the low or high side, remember
6993 // it, otherwise compute the range [low, hi) bounding the new value.
6994 // See: InsertRangeTest above for the kinds of replacements possible.
6995 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6996 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6997 DivRHS))
6998 return R;
6999 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007000
7001 case Instruction::Add:
7002 // Fold: icmp pred (add, X, C1), C2
7003
7004 if (!ICI.isEquality()) {
7005 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7006 if (!LHSC) break;
7007 const APInt &LHSV = LHSC->getValue();
7008
7009 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7010 .subtract(LHSV);
7011
7012 if (ICI.isSignedPredicate()) {
7013 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007014 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007015 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007016 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007017 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007018 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007019 }
7020 } else {
7021 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007022 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007023 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007024 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007025 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007026 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007027 }
7028 }
7029 }
7030 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007031 }
7032
7033 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7034 if (ICI.isEquality()) {
7035 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7036
7037 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7038 // the second operand is a constant, simplify a bit.
7039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7040 switch (BO->getOpcode()) {
7041 case Instruction::SRem:
7042 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7043 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7044 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7045 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007046 Value *NewRem =
7047 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7048 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007049 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007050 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007051 }
7052 }
7053 break;
7054 case Instruction::Add:
7055 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7056 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7057 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007058 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007059 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007060 } else if (RHSV == 0) {
7061 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7062 // efficiently invertible, or if the add has just this one use.
7063 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7064
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007065 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007066 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007067 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007068 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007069 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007070 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007071 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007072 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007073 }
7074 }
7075 break;
7076 case Instruction::Xor:
7077 // For the xor case, we can xor two constants together, eliminating
7078 // the explicit xor.
7079 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007080 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007081 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007082
7083 // FALLTHROUGH
7084 case Instruction::Sub:
7085 // Replace (([sub|xor] A, B) != 0) with (A != B)
7086 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007087 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007088 BO->getOperand(1));
7089 break;
7090
7091 case Instruction::Or:
7092 // If bits are being or'd in that are not present in the constant we
7093 // are comparing against, then the comparison could never succeed!
7094 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007095 Constant *NotCI = ConstantExpr::getNot(RHS);
7096 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007097 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007098 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007099 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007100 }
7101 break;
7102
7103 case Instruction::And:
7104 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7105 // If bits are being compared against that are and'd out, then the
7106 // comparison can never succeed!
7107 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007108 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007109 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007110 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111
7112 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7113 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007114 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007115 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007116 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007117
7118 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007119 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007120 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007121 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007122 ICmpInst::Predicate pred = isICMP_NE ?
7123 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007124 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125 }
7126
7127 // ((X & ~7) == 0) --> X < 8
7128 if (RHSV == 0 && isHighOnes(BOC)) {
7129 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007130 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007131 ICmpInst::Predicate pred = isICMP_NE ?
7132 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007133 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007134 }
7135 }
7136 default: break;
7137 }
7138 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7139 // Handle icmp {eq|ne} <intrinsic>, intcst.
7140 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007141 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007142 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007143 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 return &ICI;
7145 }
7146 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 }
7148 return 0;
7149}
7150
7151/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7152/// We only handle extending casts so far.
7153///
7154Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7155 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7156 Value *LHSCIOp = LHSCI->getOperand(0);
7157 const Type *SrcTy = LHSCIOp->getType();
7158 const Type *DestTy = LHSCI->getType();
7159 Value *RHSCIOp;
7160
7161 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7162 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007163 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7164 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007165 cast<IntegerType>(DestTy)->getBitWidth()) {
7166 Value *RHSOp = 0;
7167 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007168 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007169 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7170 RHSOp = RHSC->getOperand(0);
7171 // If the pointer types don't match, insert a bitcast.
7172 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007173 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174 }
7175
7176 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007177 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007178 }
7179
7180 // The code below only handles extension cast instructions, so far.
7181 // Enforce this.
7182 if (LHSCI->getOpcode() != Instruction::ZExt &&
7183 LHSCI->getOpcode() != Instruction::SExt)
7184 return 0;
7185
7186 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7187 bool isSignedCmp = ICI.isSignedPredicate();
7188
7189 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7190 // Not an extension from the same type?
7191 RHSCIOp = CI->getOperand(0);
7192 if (RHSCIOp->getType() != LHSCIOp->getType())
7193 return 0;
7194
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007195 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007196 // and the other is a zext), then we can't handle this.
7197 if (CI->getOpcode() != LHSCI->getOpcode())
7198 return 0;
7199
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007200 // Deal with equality cases early.
7201 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007202 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007203
7204 // A signed comparison of sign extended values simplifies into a
7205 // signed comparison.
7206 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007207 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007208
7209 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007210 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007211 }
7212
7213 // If we aren't dealing with a constant on the RHS, exit early
7214 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7215 if (!CI)
7216 return 0;
7217
7218 // Compute the constant that would happen if we truncated to SrcTy then
7219 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007220 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7221 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007222 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007223
7224 // If the re-extended constant didn't change...
7225 if (Res2 == CI) {
7226 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7227 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007228 // %A = sext i16 %X to i32
7229 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007230 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007231 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007232 // because %A may have negative value.
7233 //
Chris Lattner3d816532008-07-11 04:09:09 +00007234 // However, we allow this when the compare is EQ/NE, because they are
7235 // signless.
7236 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007237 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007238 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007239 }
7240
7241 // The re-extended constant changed so the constant cannot be represented
7242 // in the shorter type. Consequently, we cannot emit a simple comparison.
7243
7244 // First, handle some easy cases. We know the result cannot be equal at this
7245 // point so handle the ICI.isEquality() cases
7246 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007247 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007248 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007249 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007250
7251 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7252 // should have been folded away previously and not enter in here.
7253 Value *Result;
7254 if (isSignedCmp) {
7255 // We're performing a signed comparison.
7256 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007257 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007258 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007259 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007260 } else {
7261 // We're performing an unsigned comparison.
7262 if (isSignedExt) {
7263 // We're performing an unsigned comp with a sign extended value.
7264 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007265 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007266 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007267 } else {
7268 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007269 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007270 }
7271 }
7272
7273 // Finally, return the value computed.
7274 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007275 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007276 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007277
7278 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7279 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7280 "ICmp should be folded!");
7281 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007282 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007283 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007284}
7285
7286Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7287 return commonShiftTransforms(I);
7288}
7289
7290Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7291 return commonShiftTransforms(I);
7292}
7293
7294Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007295 if (Instruction *R = commonShiftTransforms(I))
7296 return R;
7297
7298 Value *Op0 = I.getOperand(0);
7299
7300 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7301 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7302 if (CSI->isAllOnesValue())
7303 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007304
Dan Gohman2526aea2009-06-16 19:55:29 +00007305 // See if we can turn a signed shr into an unsigned shr.
7306 if (MaskedValueIsZero(Op0,
7307 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7308 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7309
7310 // Arithmetic shifting an all-sign-bit value is a no-op.
7311 unsigned NumSignBits = ComputeNumSignBits(Op0);
7312 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7313 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007314
Chris Lattnere3c504f2007-12-06 01:59:46 +00007315 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007316}
7317
7318Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7319 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7321
7322 // shl X, 0 == X and shr X, 0 == X
7323 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007324 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7325 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007326 return ReplaceInstUsesWith(I, Op0);
7327
7328 if (isa<UndefValue>(Op0)) {
7329 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7330 return ReplaceInstUsesWith(I, Op0);
7331 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007332 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333 }
7334 if (isa<UndefValue>(Op1)) {
7335 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7336 return ReplaceInstUsesWith(I, Op0);
7337 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007338 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007339 }
7340
Dan Gohman2bc21562009-05-21 02:28:33 +00007341 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007342 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007343 return &I;
7344
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007345 // Try to fold constant and into select arguments.
7346 if (isa<Constant>(Op0))
7347 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7348 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7349 return R;
7350
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007351 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7352 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7353 return Res;
7354 return 0;
7355}
7356
7357Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7358 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007359 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007360
7361 // See if we can simplify any instructions used by the instruction whose sole
7362 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007363 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007364
Dan Gohman9e1657f2009-06-14 23:30:43 +00007365 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7366 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007367 //
7368 if (Op1->uge(TypeBits)) {
7369 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007370 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007371 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007372 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007373 return &I;
7374 }
7375 }
7376
7377 // ((X*C1) << C2) == (X * (C1 << C2))
7378 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7379 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7380 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007381 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007382 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383
7384 // Try to fold constant and into select arguments.
7385 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7386 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7387 return R;
7388 if (isa<PHINode>(Op0))
7389 if (Instruction *NV = FoldOpIntoPhi(I))
7390 return NV;
7391
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007392 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7393 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7394 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7395 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7396 // place. Don't try to do this transformation in this case. Also, we
7397 // require that the input operand is a shift-by-constant so that we have
7398 // confidence that the shifts will get folded together. We could do this
7399 // xform in more cases, but it is unlikely to be profitable.
7400 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7401 isa<ConstantInt>(TrOp->getOperand(1))) {
7402 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007403 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007404 // (shift2 (shift1 & 0x00FF), c2)
7405 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007406
7407 // For logical shifts, the truncation has the effect of making the high
7408 // part of the register be zeros. Emulate this by inserting an AND to
7409 // clear the top bits as needed. This 'and' will usually be zapped by
7410 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007411 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7412 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007413 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7414
7415 // The mask we constructed says what the trunc would do if occurring
7416 // between the shifts. We want to know the effect *after* the second
7417 // shift. We know that it is a logical shift by a constant, so adjust the
7418 // mask as appropriate.
7419 if (I.getOpcode() == Instruction::Shl)
7420 MaskV <<= Op1->getZExtValue();
7421 else {
7422 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7423 MaskV = MaskV.lshr(Op1->getZExtValue());
7424 }
7425
Chris Lattnerc7694852009-08-30 07:44:24 +00007426 // shift1 & 0x00FF
7427 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7428 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007429
7430 // Return the value truncated to the interesting size.
7431 return new TruncInst(And, I.getType());
7432 }
7433 }
7434
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007435 if (Op0->hasOneUse()) {
7436 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7437 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7438 Value *V1, *V2;
7439 ConstantInt *CC;
7440 switch (Op0BO->getOpcode()) {
7441 default: break;
7442 case Instruction::Add:
7443 case Instruction::And:
7444 case Instruction::Or:
7445 case Instruction::Xor: {
7446 // These operators commute.
7447 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7448 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007449 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007450 m_Specific(Op1)))) {
7451 Value *YS = // (Y << C)
7452 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7453 // (X + (Y << C))
7454 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7455 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007456 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007457 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007458 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7459 }
7460
7461 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7462 Value *Op0BOOp1 = Op0BO->getOperand(1);
7463 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7464 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007465 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007466 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007467 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007468 Value *YS = // (Y << C)
7469 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7470 Op0BO->getName());
7471 // X & (CC << C)
7472 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7473 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007474 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007475 }
7476 }
7477
7478 // FALL THROUGH.
7479 case Instruction::Sub: {
7480 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7481 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007482 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007483 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007484 Value *YS = // (Y << C)
7485 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7486 // (X + (Y << C))
7487 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7488 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007489 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007490 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007491 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7492 }
7493
7494 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7495 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7496 match(Op0BO->getOperand(0),
7497 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007498 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007499 cast<BinaryOperator>(Op0BO->getOperand(0))
7500 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007501 Value *YS = // (Y << C)
7502 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7503 // X & (CC << C)
7504 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7505 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007506
Gabor Greifa645dd32008-05-16 19:29:10 +00007507 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007508 }
7509
7510 break;
7511 }
7512 }
7513
7514
7515 // If the operand is an bitwise operator with a constant RHS, and the
7516 // shift is the only use, we can pull it out of the shift.
7517 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7518 bool isValid = true; // Valid only for And, Or, Xor
7519 bool highBitSet = false; // Transform if high bit of constant set?
7520
7521 switch (Op0BO->getOpcode()) {
7522 default: isValid = false; break; // Do not perform transform!
7523 case Instruction::Add:
7524 isValid = isLeftShift;
7525 break;
7526 case Instruction::Or:
7527 case Instruction::Xor:
7528 highBitSet = false;
7529 break;
7530 case Instruction::And:
7531 highBitSet = true;
7532 break;
7533 }
7534
7535 // If this is a signed shift right, and the high bit is modified
7536 // by the logical operation, do not perform the transformation.
7537 // The highBitSet boolean indicates the value of the high bit of
7538 // the constant which would cause it to be modified for this
7539 // operation.
7540 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007541 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007543
7544 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007545 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007546
Chris Lattnerad7516a2009-08-30 18:50:58 +00007547 Value *NewShift =
7548 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007549 NewShift->takeName(Op0BO);
7550
Gabor Greifa645dd32008-05-16 19:29:10 +00007551 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007552 NewRHS);
7553 }
7554 }
7555 }
7556 }
7557
7558 // Find out if this is a shift of a shift by a constant.
7559 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7560 if (ShiftOp && !ShiftOp->isShift())
7561 ShiftOp = 0;
7562
7563 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7564 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7565 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7566 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7567 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7568 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7569 Value *X = ShiftOp->getOperand(0);
7570
7571 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007572
7573 const IntegerType *Ty = cast<IntegerType>(I.getType());
7574
7575 // Check for (X << c1) << c2 and (X >> c1) >> c2
7576 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007577 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7578 // saturates.
7579 if (AmtSum >= TypeBits) {
7580 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007581 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007582 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7583 }
7584
Gabor Greifa645dd32008-05-16 19:29:10 +00007585 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007586 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007587 }
7588
7589 if (ShiftOp->getOpcode() == Instruction::LShr &&
7590 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007591 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007592 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007594 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007595 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007596 }
7597
7598 if (ShiftOp->getOpcode() == Instruction::AShr &&
7599 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007600 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007601 if (AmtSum >= TypeBits)
7602 AmtSum = TypeBits-1;
7603
Chris Lattnerad7516a2009-08-30 18:50:58 +00007604 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007605
7606 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007607 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007608 }
7609
7610 // Okay, if we get here, one shift must be left, and the other shift must be
7611 // right. See if the amounts are equal.
7612 if (ShiftAmt1 == ShiftAmt2) {
7613 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7614 if (I.getOpcode() == Instruction::Shl) {
7615 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007616 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007617 }
7618 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7619 if (I.getOpcode() == Instruction::LShr) {
7620 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007621 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007622 }
7623 // We can simplify ((X << C) >>s C) into a trunc + sext.
7624 // NOTE: we could do this for any C, but that would make 'unusual' integer
7625 // types. For now, just stick to ones well-supported by the code
7626 // generators.
7627 const Type *SExtType = 0;
7628 switch (Ty->getBitWidth() - ShiftAmt1) {
7629 case 1 :
7630 case 8 :
7631 case 16 :
7632 case 32 :
7633 case 64 :
7634 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007635 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007636 break;
7637 default: break;
7638 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007639 if (SExtType)
7640 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007641 // Otherwise, we can't handle it yet.
7642 } else if (ShiftAmt1 < ShiftAmt2) {
7643 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7644
7645 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7646 if (I.getOpcode() == Instruction::Shl) {
7647 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7648 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007649 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007650
7651 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007652 return BinaryOperator::CreateAnd(Shift,
7653 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007654 }
7655
7656 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7657 if (I.getOpcode() == Instruction::LShr) {
7658 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007659 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007660
7661 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007662 return BinaryOperator::CreateAnd(Shift,
7663 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007664 }
7665
7666 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7667 } else {
7668 assert(ShiftAmt2 < ShiftAmt1);
7669 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7670
7671 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7672 if (I.getOpcode() == Instruction::Shl) {
7673 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7674 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007675 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7676 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007677
7678 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007679 return BinaryOperator::CreateAnd(Shift,
7680 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007681 }
7682
7683 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7684 if (I.getOpcode() == Instruction::LShr) {
7685 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007686 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007687
7688 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007689 return BinaryOperator::CreateAnd(Shift,
7690 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007691 }
7692
7693 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7694 }
7695 }
7696 return 0;
7697}
7698
7699
7700/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7701/// expression. If so, decompose it, returning some value X, such that Val is
7702/// X*Scale+Offset.
7703///
7704static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007705 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007706 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7707 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007708 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7709 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007710 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007711 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007712 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7713 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7714 if (I->getOpcode() == Instruction::Shl) {
7715 // This is a value scaled by '1 << the shift amt'.
7716 Scale = 1U << RHS->getZExtValue();
7717 Offset = 0;
7718 return I->getOperand(0);
7719 } else if (I->getOpcode() == Instruction::Mul) {
7720 // This value is scaled by 'RHS'.
7721 Scale = RHS->getZExtValue();
7722 Offset = 0;
7723 return I->getOperand(0);
7724 } else if (I->getOpcode() == Instruction::Add) {
7725 // We have X+C. Check to see if we really have (X*C2)+C1,
7726 // where C1 is divisible by C2.
7727 unsigned SubScale;
7728 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007729 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7730 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007731 Offset += RHS->getZExtValue();
7732 Scale = SubScale;
7733 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007734 }
7735 }
7736 }
7737
7738 // Otherwise, we can't look past this.
7739 Scale = 1;
7740 Offset = 0;
7741 return Val;
7742}
7743
7744
7745/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7746/// try to eliminate the cast by moving the type information into the alloc.
7747Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7748 AllocationInst &AI) {
7749 const PointerType *PTy = cast<PointerType>(CI.getType());
7750
Chris Lattnerad7516a2009-08-30 18:50:58 +00007751 BuilderTy AllocaBuilder(*Builder);
7752 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7753
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007754 // Remove any uses of AI that are dead.
7755 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7756
7757 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7758 Instruction *User = cast<Instruction>(*UI++);
7759 if (isInstructionTriviallyDead(User)) {
7760 while (UI != E && *UI == User)
7761 ++UI; // If this instruction uses AI more than once, don't break UI.
7762
7763 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007764 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007765 EraseInstFromFunction(*User);
7766 }
7767 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007768
7769 // This requires TargetData to get the alloca alignment and size information.
7770 if (!TD) return 0;
7771
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007772 // Get the type really allocated and the type casted to.
7773 const Type *AllocElTy = AI.getAllocatedType();
7774 const Type *CastElTy = PTy->getElementType();
7775 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7776
7777 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7778 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7779 if (CastElTyAlign < AllocElTyAlign) return 0;
7780
7781 // If the allocation has multiple uses, only promote it if we are strictly
7782 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007783 // same, we open the door to infinite loops of various kinds. (A reference
7784 // from a dbg.declare doesn't count as a use for this purpose.)
7785 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7786 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007787
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007788 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7789 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007790 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7791
7792 // See if we can satisfy the modulus by pulling a scale out of the array
7793 // size argument.
7794 unsigned ArraySizeScale;
7795 int ArrayOffset;
7796 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007797 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7798 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007799
7800 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7801 // do the xform.
7802 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7803 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7804
7805 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7806 Value *Amt = 0;
7807 if (Scale == 1) {
7808 Amt = NumElements;
7809 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007810 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007811 // Insert before the alloca, not before the cast.
7812 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007813 }
7814
7815 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007816 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007817 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007818 }
7819
Victor Hernandez37f513d2009-10-17 01:18:07 +00007820 AllocationInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007821 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007822 New->takeName(&AI);
7823
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007824 // If the allocation has one real use plus a dbg.declare, just remove the
7825 // declare.
7826 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7827 EraseInstFromFunction(*DI);
7828 }
7829 // If the allocation has multiple real uses, insert a cast and change all
7830 // things that used it to use the new cast. This will also hack on CI, but it
7831 // will die soon.
7832 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007833 // New is the allocation instruction, pointer typed. AI is the original
7834 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007835 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007836 AI.replaceAllUsesWith(NewCast);
7837 }
7838 return ReplaceInstUsesWith(CI, New);
7839}
7840
7841/// CanEvaluateInDifferentType - Return true if we can take the specified value
7842/// and return it as type Ty without inserting any new casts and without
7843/// changing the computed value. This is used by code that tries to decide
7844/// whether promoting or shrinking integer operations to wider or smaller types
7845/// will allow us to eliminate a truncate or extend.
7846///
7847/// This is a truncation operation if Ty is smaller than V->getType(), or an
7848/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007849///
7850/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7851/// should return true if trunc(V) can be computed by computing V in the smaller
7852/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7853/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7854/// efficiently truncated.
7855///
7856/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7857/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7858/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007859bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007860 unsigned CastOpc,
7861 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007862 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007863 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864 return true;
7865
7866 Instruction *I = dyn_cast<Instruction>(V);
7867 if (!I) return false;
7868
Dan Gohman8fd520a2009-06-15 22:12:54 +00007869 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007870
Chris Lattneref70bb82007-08-02 06:11:14 +00007871 // If this is an extension or truncate, we can often eliminate it.
7872 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7873 // If this is a cast from the destination type, we can trivially eliminate
7874 // it, and this will remove a cast overall.
7875 if (I->getOperand(0)->getType() == Ty) {
7876 // If the first operand is itself a cast, and is eliminable, do not count
7877 // this as an eliminable cast. We would prefer to eliminate those two
7878 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007879 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007880 ++NumCastsRemoved;
7881 return true;
7882 }
7883 }
7884
7885 // We can't extend or shrink something that has multiple uses: doing so would
7886 // require duplicating the instruction in general, which isn't profitable.
7887 if (!I->hasOneUse()) return false;
7888
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007889 unsigned Opc = I->getOpcode();
7890 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007891 case Instruction::Add:
7892 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007893 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007894 case Instruction::And:
7895 case Instruction::Or:
7896 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007897 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007898 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007899 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007900 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007901 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902
Eli Friedman08c45bc2009-07-13 22:46:01 +00007903 case Instruction::UDiv:
7904 case Instruction::URem: {
7905 // UDiv and URem can be truncated if all the truncated bits are zero.
7906 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7907 uint32_t BitWidth = Ty->getScalarSizeInBits();
7908 if (BitWidth < OrigBitWidth) {
7909 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7910 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7911 MaskedValueIsZero(I->getOperand(1), Mask)) {
7912 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7913 NumCastsRemoved) &&
7914 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7915 NumCastsRemoved);
7916 }
7917 }
7918 break;
7919 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007920 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007921 // If we are truncating the result of this SHL, and if it's a shift of a
7922 // constant amount, we can always perform a SHL in a smaller type.
7923 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007924 uint32_t BitWidth = Ty->getScalarSizeInBits();
7925 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007926 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007927 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007928 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007929 }
7930 break;
7931 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007932 // If this is a truncate of a logical shr, we can truncate it to a smaller
7933 // lshr iff we know that the bits we would otherwise be shifting in are
7934 // already zeros.
7935 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007936 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7937 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007938 if (BitWidth < OrigBitWidth &&
7939 MaskedValueIsZero(I->getOperand(0),
7940 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7941 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007942 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007943 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007944 }
7945 }
7946 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007947 case Instruction::ZExt:
7948 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007949 case Instruction::Trunc:
7950 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007951 // can safely replace it. Note that replacing it does not reduce the number
7952 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007953 if (Opc == CastOpc)
7954 return true;
7955
7956 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007957 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007959 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007960 case Instruction::Select: {
7961 SelectInst *SI = cast<SelectInst>(I);
7962 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007963 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007964 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007965 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007966 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007967 case Instruction::PHI: {
7968 // We can change a phi if we can change all operands.
7969 PHINode *PN = cast<PHINode>(I);
7970 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7971 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007972 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007973 return false;
7974 return true;
7975 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007976 default:
7977 // TODO: Can handle more cases here.
7978 break;
7979 }
7980
7981 return false;
7982}
7983
7984/// EvaluateInDifferentType - Given an expression that
7985/// CanEvaluateInDifferentType returns true for, actually insert the code to
7986/// evaluate the expression.
7987Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7988 bool isSigned) {
7989 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00007990 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007991 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992
7993 // Otherwise, it must be an instruction.
7994 Instruction *I = cast<Instruction>(V);
7995 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007996 unsigned Opc = I->getOpcode();
7997 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007998 case Instruction::Add:
7999 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008000 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008001 case Instruction::And:
8002 case Instruction::Or:
8003 case Instruction::Xor:
8004 case Instruction::AShr:
8005 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008006 case Instruction::Shl:
8007 case Instruction::UDiv:
8008 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8010 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008011 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008012 break;
8013 }
8014 case Instruction::Trunc:
8015 case Instruction::ZExt:
8016 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008017 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008018 // just return the source. There's no need to insert it because it is not
8019 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008020 if (I->getOperand(0)->getType() == Ty)
8021 return I->getOperand(0);
8022
Chris Lattner4200c2062008-06-18 04:00:49 +00008023 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008024 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008025 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008026 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008027 case Instruction::Select: {
8028 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8029 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8030 Res = SelectInst::Create(I->getOperand(0), True, False);
8031 break;
8032 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008033 case Instruction::PHI: {
8034 PHINode *OPN = cast<PHINode>(I);
8035 PHINode *NPN = PHINode::Create(Ty);
8036 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8037 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8038 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8039 }
8040 Res = NPN;
8041 break;
8042 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008043 default:
8044 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008045 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008046 break;
8047 }
8048
Chris Lattner4200c2062008-06-18 04:00:49 +00008049 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008050 return InsertNewInstBefore(Res, *I);
8051}
8052
8053/// @brief Implement the transforms common to all CastInst visitors.
8054Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8055 Value *Src = CI.getOperand(0);
8056
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008057 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8058 // eliminate it now.
8059 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8060 if (Instruction::CastOps opc =
8061 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8062 // The first cast (CSrc) is eliminable so we need to fix up or replace
8063 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008064 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008065 }
8066 }
8067
8068 // If we are casting a select then fold the cast into the select
8069 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8070 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8071 return NV;
8072
8073 // If we are casting a PHI then fold the cast into the PHI
8074 if (isa<PHINode>(Src))
8075 if (Instruction *NV = FoldOpIntoPhi(CI))
8076 return NV;
8077
8078 return 0;
8079}
8080
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008081/// FindElementAtOffset - Given a type and a constant offset, determine whether
8082/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008083/// the specified offset. If so, fill them into NewIndices and return the
8084/// resultant element type, otherwise return null.
8085static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8086 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008087 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008088 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008089 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008090 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008091
8092 // Start with the index over the outer type. Note that the type size
8093 // might be zero (even if the offset isn't zero) if the indexed type
8094 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008095 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008096 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008097 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008098 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008099 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008100
Chris Lattnerce48c462009-01-11 20:15:20 +00008101 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008102 if (Offset < 0) {
8103 --FirstIdx;
8104 Offset += TySize;
8105 assert(Offset >= 0);
8106 }
8107 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8108 }
8109
Owen Andersoneacb44d2009-07-24 23:12:02 +00008110 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008111
8112 // Index into the types. If we fail, set OrigBase to null.
8113 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008114 // Indexing into tail padding between struct/array elements.
8115 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008116 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008117
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008118 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8119 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008120 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8121 "Offset must stay within the indexed type");
8122
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008123 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008124 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008125
8126 Offset -= SL->getElementOffset(Elt);
8127 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008128 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008129 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008130 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008131 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008132 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008133 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008134 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008135 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008136 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008137 }
8138 }
8139
Chris Lattner54dddc72009-01-24 01:00:13 +00008140 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008141}
8142
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008143/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8144Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8145 Value *Src = CI.getOperand(0);
8146
8147 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8148 // If casting the result of a getelementptr instruction with no offset, turn
8149 // this into a cast of the original pointer!
8150 if (GEP->hasAllZeroIndices()) {
8151 // Changing the cast operand is usually not a good idea but it is safe
8152 // here because the pointer operand is being replaced with another
8153 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008154 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008155 CI.setOperand(0, GEP->getOperand(0));
8156 return &CI;
8157 }
8158
8159 // If the GEP has a single use, and the base pointer is a bitcast, and the
8160 // GEP computes a constant offset, see if we can convert these three
8161 // instructions into fewer. This typically happens with unions and other
8162 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008163 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008164 if (GEP->hasAllConstantIndices()) {
8165 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008166 ConstantInt *OffsetV =
8167 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008168 int64_t Offset = OffsetV->getSExtValue();
8169
8170 // Get the base pointer input of the bitcast, and the type it points to.
8171 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8172 const Type *GEPIdxTy =
8173 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008174 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008175 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008176 // If we were able to index down into an element, create the GEP
8177 // and bitcast the result. This eliminates one bitcast, potentially
8178 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008179 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8180 Builder->CreateInBoundsGEP(OrigBase,
8181 NewIndices.begin(), NewIndices.end()) :
8182 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008183 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008184
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008185 if (isa<BitCastInst>(CI))
8186 return new BitCastInst(NGEP, CI.getType());
8187 assert(isa<PtrToIntInst>(CI));
8188 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008189 }
8190 }
8191 }
8192 }
8193
8194 return commonCastTransforms(CI);
8195}
8196
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008197/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8198/// type like i42. We don't want to introduce operations on random non-legal
8199/// integer types where they don't already exist in the code. In the future,
8200/// we should consider making this based off target-data, so that 32-bit targets
8201/// won't get i64 operations etc.
8202static bool isSafeIntegerType(const Type *Ty) {
8203 switch (Ty->getPrimitiveSizeInBits()) {
8204 case 8:
8205 case 16:
8206 case 32:
8207 case 64:
8208 return true;
8209 default:
8210 return false;
8211 }
8212}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008213
Eli Friedman827e37a2009-07-13 20:58:59 +00008214/// commonIntCastTransforms - This function implements the common transforms
8215/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008216Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8217 if (Instruction *Result = commonCastTransforms(CI))
8218 return Result;
8219
8220 Value *Src = CI.getOperand(0);
8221 const Type *SrcTy = Src->getType();
8222 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008223 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8224 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008225
8226 // See if we can simplify any instructions used by the LHS whose sole
8227 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008228 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008229 return &CI;
8230
8231 // If the source isn't an instruction or has more than one use then we
8232 // can't do anything more.
8233 Instruction *SrcI = dyn_cast<Instruction>(Src);
8234 if (!SrcI || !Src->hasOneUse())
8235 return 0;
8236
8237 // Attempt to propagate the cast into the instruction for int->int casts.
8238 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008239 // Only do this if the dest type is a simple type, don't convert the
8240 // expression tree to something weird like i93 unless the source is also
8241 // strange.
8242 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008243 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8244 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008245 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008246 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008247 // eliminates the cast, so it is always a win. If this is a zero-extension,
8248 // we need to do an AND to maintain the clear top-part of the computation,
8249 // so we require that the input have eliminated at least one cast. If this
8250 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008252 bool DoXForm = false;
8253 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008254 switch (CI.getOpcode()) {
8255 default:
8256 // All the others use floating point so we shouldn't actually
8257 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008258 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008259 case Instruction::Trunc:
8260 DoXForm = true;
8261 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008262 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008263 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008264 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008265 // If it's unnecessary to issue an AND to clear the high bits, it's
8266 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008267 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008268 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8269 if (MaskedValueIsZero(TryRes, Mask))
8270 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008271
8272 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008273 if (TryI->use_empty())
8274 EraseInstFromFunction(*TryI);
8275 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008276 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008277 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008278 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008279 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008280 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008281 // If we do not have to emit the truncate + sext pair, then it's always
8282 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008283 //
8284 // It's not safe to eliminate the trunc + sext pair if one of the
8285 // eliminated cast is a truncate. e.g.
8286 // t2 = trunc i32 t1 to i16
8287 // t3 = sext i16 t2 to i32
8288 // !=
8289 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008290 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008291 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8292 if (NumSignBits > (DestBitSize - SrcBitSize))
8293 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008294
8295 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008296 if (TryI->use_empty())
8297 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008298 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008299 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008300 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008301 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008302
8303 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008304 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8305 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008306 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8307 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008308 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008309 // Just replace this cast with the result.
8310 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008312 assert(Res->getType() == DestTy);
8313 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008314 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008315 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008316 // Just replace this cast with the result.
8317 return ReplaceInstUsesWith(CI, Res);
8318 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008319 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008320
8321 // If the high bits are already zero, just replace this cast with the
8322 // result.
8323 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8324 if (MaskedValueIsZero(Res, Mask))
8325 return ReplaceInstUsesWith(CI, Res);
8326
8327 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008328 Constant *C = ConstantInt::get(*Context,
8329 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008330 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008331 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008332 case Instruction::SExt: {
8333 // If the high bits are already filled with sign bit, just replace this
8334 // cast with the result.
8335 unsigned NumSignBits = ComputeNumSignBits(Res);
8336 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008337 return ReplaceInstUsesWith(CI, Res);
8338
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008339 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008340 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008341 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008342 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343 }
8344 }
8345
8346 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8347 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8348
8349 switch (SrcI->getOpcode()) {
8350 case Instruction::Add:
8351 case Instruction::Mul:
8352 case Instruction::And:
8353 case Instruction::Or:
8354 case Instruction::Xor:
8355 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008356 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8357 // Don't insert two casts unless at least one can be eliminated.
8358 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008359 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008360 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8361 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008362 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008363 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8364 }
8365 }
8366
8367 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8368 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8369 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008370 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008371 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008372 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008373 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008374 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008375 }
8376 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008377
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008378 case Instruction::Shl: {
8379 // Canonicalize trunc inside shl, if we can.
8380 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8381 if (CI && DestBitSize < SrcBitSize &&
8382 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008383 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8384 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008385 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008386 }
8387 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008388 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008389 }
8390 return 0;
8391}
8392
8393Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8394 if (Instruction *Result = commonIntCastTransforms(CI))
8395 return Result;
8396
8397 Value *Src = CI.getOperand(0);
8398 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008399 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8400 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008401
8402 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008403 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008404 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008405 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008406 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008407 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008408 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008409
Chris Lattner32177f82009-03-24 18:15:30 +00008410 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8411 ConstantInt *ShAmtV = 0;
8412 Value *ShiftOp = 0;
8413 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008414 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008415 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8416
8417 // Get a mask for the bits shifting in.
8418 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8419 if (MaskedValueIsZero(ShiftOp, Mask)) {
8420 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008421 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008422
8423 // Okay, we can shrink this. Truncate the input, then return a new
8424 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008425 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008426 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008427 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008428 }
8429 }
8430
8431 return 0;
8432}
8433
Evan Chenge3779cf2008-03-24 00:21:34 +00008434/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8435/// in order to eliminate the icmp.
8436Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8437 bool DoXform) {
8438 // If we are just checking for a icmp eq of a single bit and zext'ing it
8439 // to an integer, then shift the bit to the appropriate place and then
8440 // cast to integer to avoid the comparison.
8441 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8442 const APInt &Op1CV = Op1C->getValue();
8443
8444 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8445 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8446 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8447 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8448 if (!DoXform) return ICI;
8449
8450 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008451 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008452 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008453 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008454 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008455 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008456
8457 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008458 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008459 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008460 }
8461
8462 return ReplaceInstUsesWith(CI, In);
8463 }
8464
8465
8466
8467 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8468 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8469 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8470 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8471 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8472 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8473 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8474 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8475 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8476 // This only works for EQ and NE
8477 ICI->isEquality()) {
8478 // If Op1C some other power of two, convert:
8479 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8480 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8481 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8482 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8483
8484 APInt KnownZeroMask(~KnownZero);
8485 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8486 if (!DoXform) return ICI;
8487
8488 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8489 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8490 // (X&4) == 2 --> false
8491 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008492 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008493 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008494 return ReplaceInstUsesWith(CI, Res);
8495 }
8496
8497 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8498 Value *In = ICI->getOperand(0);
8499 if (ShiftAmt) {
8500 // Perform a logical shr by shiftamt.
8501 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008502 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8503 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008504 }
8505
8506 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008507 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008508 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008509 }
8510
8511 if (CI.getType() == In->getType())
8512 return ReplaceInstUsesWith(CI, In);
8513 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008514 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008515 }
8516 }
8517 }
8518
8519 return 0;
8520}
8521
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008522Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8523 // If one of the common conversion will work ..
8524 if (Instruction *Result = commonIntCastTransforms(CI))
8525 return Result;
8526
8527 Value *Src = CI.getOperand(0);
8528
Chris Lattner215d56e2009-02-17 20:47:23 +00008529 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8530 // types and if the sizes are just right we can convert this into a logical
8531 // 'and' which will be much cheaper than the pair of casts.
8532 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8533 // Get the sizes of the types involved. We know that the intermediate type
8534 // will be smaller than A or C, but don't know the relation between A and C.
8535 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008536 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8537 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8538 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008539 // If we're actually extending zero bits, then if
8540 // SrcSize < DstSize: zext(a & mask)
8541 // SrcSize == DstSize: a & mask
8542 // SrcSize > DstSize: trunc(a) & mask
8543 if (SrcSize < DstSize) {
8544 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008545 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008546 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008547 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008548 }
8549
8550 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008551 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008552 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008553 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008554 }
8555 if (SrcSize > DstSize) {
8556 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008557 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008558 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008559 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008560 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008561 }
8562 }
8563
Evan Chenge3779cf2008-03-24 00:21:34 +00008564 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8565 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008566
Evan Chenge3779cf2008-03-24 00:21:34 +00008567 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8568 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8569 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8570 // of the (zext icmp) will be transformed.
8571 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8572 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8573 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8574 (transformZExtICmp(LHS, CI, false) ||
8575 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008576 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8577 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008578 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008579 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008580 }
8581
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008582 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008583 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8584 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8585 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8586 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008587 if (TI0->getType() == CI.getType())
8588 return
8589 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008590 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008591 }
8592
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008593 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8594 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8595 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8596 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8597 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8598 And->getOperand(1) == C)
8599 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8600 Value *TI0 = TI->getOperand(0);
8601 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008602 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008603 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008604 return BinaryOperator::CreateXor(NewAnd, ZC);
8605 }
8606 }
8607
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008608 return 0;
8609}
8610
8611Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8612 if (Instruction *I = commonIntCastTransforms(CI))
8613 return I;
8614
8615 Value *Src = CI.getOperand(0);
8616
Dan Gohman35b76162008-10-30 20:40:10 +00008617 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008618 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008619 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008620 Constant::getAllOnesValue(CI.getType()),
8621 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008622
8623 // See if the value being truncated is already sign extended. If so, just
8624 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008625 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008626 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008627 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8628 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8629 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008630 unsigned NumSignBits = ComputeNumSignBits(Op);
8631
8632 if (OpBits == DestBits) {
8633 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8634 // bits, it is already ready.
8635 if (NumSignBits > DestBits-MidBits)
8636 return ReplaceInstUsesWith(CI, Op);
8637 } else if (OpBits < DestBits) {
8638 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8639 // bits, just sext from i32.
8640 if (NumSignBits > OpBits-MidBits)
8641 return new SExtInst(Op, CI.getType(), "tmp");
8642 } else {
8643 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8644 // bits, just truncate to i32.
8645 if (NumSignBits > OpBits-MidBits)
8646 return new TruncInst(Op, CI.getType(), "tmp");
8647 }
8648 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008649
8650 // If the input is a shl/ashr pair of a same constant, then this is a sign
8651 // extension from a smaller value. If we could trust arbitrary bitwidth
8652 // integers, we could turn this into a truncate to the smaller bit and then
8653 // use a sext for the whole extension. Since we don't, look deeper and check
8654 // for a truncate. If the source and dest are the same type, eliminate the
8655 // trunc and extend and just do shifts. For example, turn:
8656 // %a = trunc i32 %i to i8
8657 // %b = shl i8 %a, 6
8658 // %c = ashr i8 %b, 6
8659 // %d = sext i8 %c to i32
8660 // into:
8661 // %a = shl i32 %i, 30
8662 // %d = ashr i32 %a, 30
8663 Value *A = 0;
8664 ConstantInt *BA = 0, *CA = 0;
8665 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008666 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008667 BA == CA && isa<TruncInst>(A)) {
8668 Value *I = cast<TruncInst>(A)->getOperand(0);
8669 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008670 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8671 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008672 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008673 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008674 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008675 return BinaryOperator::CreateAShr(I, ShAmtV);
8676 }
8677 }
8678
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008679 return 0;
8680}
8681
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008682/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8683/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008684static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008685 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008686 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008687 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008688 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8689 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008690 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008691 return 0;
8692}
8693
8694/// LookThroughFPExtensions - If this is an fp extension instruction, look
8695/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008696static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008697 if (Instruction *I = dyn_cast<Instruction>(V))
8698 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008699 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008700
8701 // If this value is a constant, return the constant in the smallest FP type
8702 // that can accurately represent it. This allows us to turn
8703 // (float)((double)X+2.0) into x+2.0f.
8704 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008705 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008706 return V; // No constant folding of this.
8707 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008708 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008709 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008710 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008711 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008712 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008713 return V;
8714 // Don't try to shrink to various long double types.
8715 }
8716
8717 return V;
8718}
8719
8720Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8721 if (Instruction *I = commonCastTransforms(CI))
8722 return I;
8723
Dan Gohman7ce405e2009-06-04 22:49:04 +00008724 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008725 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008726 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008727 // many builtins (sqrt, etc).
8728 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8729 if (OpI && OpI->hasOneUse()) {
8730 switch (OpI->getOpcode()) {
8731 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008732 case Instruction::FAdd:
8733 case Instruction::FSub:
8734 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008735 case Instruction::FDiv:
8736 case Instruction::FRem:
8737 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008738 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8739 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008740 if (LHSTrunc->getType() != SrcTy &&
8741 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008742 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008743 // If the source types were both smaller than the destination type of
8744 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008745 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8746 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008747 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8748 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008749 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008750 }
8751 }
8752 break;
8753 }
8754 }
8755 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008756}
8757
8758Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8759 return commonCastTransforms(CI);
8760}
8761
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008762Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008763 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8764 if (OpI == 0)
8765 return commonCastTransforms(FI);
8766
8767 // fptoui(uitofp(X)) --> X
8768 // fptoui(sitofp(X)) --> X
8769 // This is safe if the intermediate type has enough bits in its mantissa to
8770 // accurately represent all values of X. For example, do not do this with
8771 // i64->float->i64. This is also safe for sitofp case, because any negative
8772 // 'X' value would cause an undefined result for the fptoui.
8773 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8774 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008775 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008776 OpI->getType()->getFPMantissaWidth())
8777 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008778
8779 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008780}
8781
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008782Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008783 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8784 if (OpI == 0)
8785 return commonCastTransforms(FI);
8786
8787 // fptosi(sitofp(X)) --> X
8788 // fptosi(uitofp(X)) --> X
8789 // This is safe if the intermediate type has enough bits in its mantissa to
8790 // accurately represent all values of X. For example, do not do this with
8791 // i64->float->i64. This is also safe for sitofp case, because any negative
8792 // 'X' value would cause an undefined result for the fptoui.
8793 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8794 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008795 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008796 OpI->getType()->getFPMantissaWidth())
8797 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008798
8799 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008800}
8801
8802Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8803 return commonCastTransforms(CI);
8804}
8805
8806Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8807 return commonCastTransforms(CI);
8808}
8809
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008810Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8811 // If the destination integer type is smaller than the intptr_t type for
8812 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8813 // trunc to be exposed to other transforms. Don't do this for extending
8814 // ptrtoint's, because we don't know if the target sign or zero extends its
8815 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008816 if (TD &&
8817 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008818 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8819 TD->getIntPtrType(CI.getContext()),
8820 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008821 return new TruncInst(P, CI.getType());
8822 }
8823
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008824 return commonPointerCastTransforms(CI);
8825}
8826
Chris Lattner7c1626482008-01-08 07:23:51 +00008827Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008828 // If the source integer type is larger than the intptr_t type for
8829 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8830 // allows the trunc to be exposed to other transforms. Don't do this for
8831 // extending inttoptr's, because we don't know if the target sign or zero
8832 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008833 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008834 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008835 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8836 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008837 return new IntToPtrInst(P, CI.getType());
8838 }
8839
Chris Lattner7c1626482008-01-08 07:23:51 +00008840 if (Instruction *I = commonCastTransforms(CI))
8841 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008842
Chris Lattner7c1626482008-01-08 07:23:51 +00008843 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008844}
8845
8846Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8847 // If the operands are integer typed then apply the integer transforms,
8848 // otherwise just apply the common ones.
8849 Value *Src = CI.getOperand(0);
8850 const Type *SrcTy = Src->getType();
8851 const Type *DestTy = CI.getType();
8852
Eli Friedman5013d3f2009-07-13 20:53:00 +00008853 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008854 if (Instruction *I = commonPointerCastTransforms(CI))
8855 return I;
8856 } else {
8857 if (Instruction *Result = commonCastTransforms(CI))
8858 return Result;
8859 }
8860
8861
8862 // Get rid of casts from one type to the same type. These are useless and can
8863 // be replaced by the operand.
8864 if (DestTy == Src->getType())
8865 return ReplaceInstUsesWith(CI, Src);
8866
8867 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8868 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8869 const Type *DstElTy = DstPTy->getElementType();
8870 const Type *SrcElTy = SrcPTy->getElementType();
8871
Nate Begemandf5b3612008-03-31 00:22:16 +00008872 // If the address spaces don't match, don't eliminate the bitcast, which is
8873 // required for changing types.
8874 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8875 return 0;
8876
Victor Hernandez48c3c542009-09-18 22:35:49 +00008877 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008878 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00008879 // There is no need to modify malloc calls because it is their bitcast that
8880 // needs to be cleaned up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008881 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8882 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8883 return V;
8884
8885 // If the source and destination are pointers, and this cast is equivalent
8886 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8887 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008888 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008889 unsigned NumZeros = 0;
8890 while (SrcElTy != DstElTy &&
8891 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8892 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8893 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8894 ++NumZeros;
8895 }
8896
8897 // If we found a path from the src to dest, create the getelementptr now.
8898 if (SrcElTy == DstElTy) {
8899 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008900 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8901 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008902 }
8903 }
8904
Eli Friedman1d31dee2009-07-18 23:06:53 +00008905 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8906 if (DestVTy->getNumElements() == 1) {
8907 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008908 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008909 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00008910 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008911 }
8912 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8913 }
8914 }
8915
8916 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8917 if (SrcVTy->getNumElements() == 1) {
8918 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008919 Value *Elem =
8920 Builder->CreateExtractElement(Src,
8921 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008922 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8923 }
8924 }
8925 }
8926
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008927 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8928 if (SVI->hasOneUse()) {
8929 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8930 // a bitconvert to a vector with the same # elts.
8931 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008932 cast<VectorType>(DestTy)->getNumElements() ==
8933 SVI->getType()->getNumElements() &&
8934 SVI->getType()->getNumElements() ==
8935 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008936 CastInst *Tmp;
8937 // If either of the operands is a cast from CI.getType(), then
8938 // evaluating the shuffle in the casted destination's type will allow
8939 // us to eliminate at least one cast.
8940 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8941 Tmp->getOperand(0)->getType() == DestTy) ||
8942 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8943 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008944 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8945 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008946 // Return a new shuffle vector. Use the same element ID's, as we
8947 // know the vector types match #elts.
8948 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8949 }
8950 }
8951 }
8952 }
8953 return 0;
8954}
8955
8956/// GetSelectFoldableOperands - We want to turn code that looks like this:
8957/// %C = or %A, %B
8958/// %D = select %cond, %C, %A
8959/// into:
8960/// %C = select %cond, %B, 0
8961/// %D = or %A, %C
8962///
8963/// Assuming that the specified instruction is an operand to the select, return
8964/// a bitmask indicating which operands of this instruction are foldable if they
8965/// equal the other incoming value of the select.
8966///
8967static unsigned GetSelectFoldableOperands(Instruction *I) {
8968 switch (I->getOpcode()) {
8969 case Instruction::Add:
8970 case Instruction::Mul:
8971 case Instruction::And:
8972 case Instruction::Or:
8973 case Instruction::Xor:
8974 return 3; // Can fold through either operand.
8975 case Instruction::Sub: // Can only fold on the amount subtracted.
8976 case Instruction::Shl: // Can only fold on the shift amount.
8977 case Instruction::LShr:
8978 case Instruction::AShr:
8979 return 1;
8980 default:
8981 return 0; // Cannot fold
8982 }
8983}
8984
8985/// GetSelectFoldableConstant - For the same transformation as the previous
8986/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00008987static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00008988 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008989 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008990 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008991 case Instruction::Add:
8992 case Instruction::Sub:
8993 case Instruction::Or:
8994 case Instruction::Xor:
8995 case Instruction::Shl:
8996 case Instruction::LShr:
8997 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00008998 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008999 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009000 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009001 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009002 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009003 }
9004}
9005
9006/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9007/// have the same opcode and only one use each. Try to simplify this.
9008Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9009 Instruction *FI) {
9010 if (TI->getNumOperands() == 1) {
9011 // If this is a non-volatile load or a cast from the same type,
9012 // merge.
9013 if (TI->isCast()) {
9014 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9015 return 0;
9016 } else {
9017 return 0; // unknown unary op.
9018 }
9019
9020 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009021 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009022 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009023 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009024 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009025 TI->getType());
9026 }
9027
9028 // Only handle binary operators here.
9029 if (!isa<BinaryOperator>(TI))
9030 return 0;
9031
9032 // Figure out if the operations have any operands in common.
9033 Value *MatchOp, *OtherOpT, *OtherOpF;
9034 bool MatchIsOpZero;
9035 if (TI->getOperand(0) == FI->getOperand(0)) {
9036 MatchOp = TI->getOperand(0);
9037 OtherOpT = TI->getOperand(1);
9038 OtherOpF = FI->getOperand(1);
9039 MatchIsOpZero = true;
9040 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9041 MatchOp = TI->getOperand(1);
9042 OtherOpT = TI->getOperand(0);
9043 OtherOpF = FI->getOperand(0);
9044 MatchIsOpZero = false;
9045 } else if (!TI->isCommutative()) {
9046 return 0;
9047 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9048 MatchOp = TI->getOperand(0);
9049 OtherOpT = TI->getOperand(1);
9050 OtherOpF = FI->getOperand(0);
9051 MatchIsOpZero = true;
9052 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9053 MatchOp = TI->getOperand(1);
9054 OtherOpT = TI->getOperand(0);
9055 OtherOpF = FI->getOperand(1);
9056 MatchIsOpZero = true;
9057 } else {
9058 return 0;
9059 }
9060
9061 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009062 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9063 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009064 InsertNewInstBefore(NewSI, SI);
9065
9066 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9067 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009068 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009069 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009070 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009071 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009072 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009073 return 0;
9074}
9075
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009076static bool isSelect01(Constant *C1, Constant *C2) {
9077 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9078 if (!C1I)
9079 return false;
9080 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9081 if (!C2I)
9082 return false;
9083 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9084}
9085
9086/// FoldSelectIntoOp - Try fold the select into one of the operands to
9087/// facilitate further optimization.
9088Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9089 Value *FalseVal) {
9090 // See the comment above GetSelectFoldableOperands for a description of the
9091 // transformation we are doing here.
9092 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9093 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9094 !isa<Constant>(FalseVal)) {
9095 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9096 unsigned OpToFold = 0;
9097 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9098 OpToFold = 1;
9099 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9100 OpToFold = 2;
9101 }
9102
9103 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009104 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009105 Value *OOp = TVI->getOperand(2-OpToFold);
9106 // Avoid creating select between 2 constants unless it's selecting
9107 // between 0 and 1.
9108 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9109 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9110 InsertNewInstBefore(NewSel, SI);
9111 NewSel->takeName(TVI);
9112 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9113 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009114 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009115 }
9116 }
9117 }
9118 }
9119 }
9120
9121 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9122 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9123 !isa<Constant>(TrueVal)) {
9124 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9125 unsigned OpToFold = 0;
9126 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9127 OpToFold = 1;
9128 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9129 OpToFold = 2;
9130 }
9131
9132 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009133 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009134 Value *OOp = FVI->getOperand(2-OpToFold);
9135 // Avoid creating select between 2 constants unless it's selecting
9136 // between 0 and 1.
9137 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9138 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9139 InsertNewInstBefore(NewSel, SI);
9140 NewSel->takeName(FVI);
9141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9142 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009143 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009144 }
9145 }
9146 }
9147 }
9148 }
9149
9150 return 0;
9151}
9152
Dan Gohman58c09632008-09-16 18:46:06 +00009153/// visitSelectInstWithICmp - Visit a SelectInst that has an
9154/// ICmpInst as its first operand.
9155///
9156Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9157 ICmpInst *ICI) {
9158 bool Changed = false;
9159 ICmpInst::Predicate Pred = ICI->getPredicate();
9160 Value *CmpLHS = ICI->getOperand(0);
9161 Value *CmpRHS = ICI->getOperand(1);
9162 Value *TrueVal = SI.getTrueValue();
9163 Value *FalseVal = SI.getFalseValue();
9164
9165 // Check cases where the comparison is with a constant that
9166 // can be adjusted to fit the min/max idiom. We may edit ICI in
9167 // place here, so make sure the select is the only user.
9168 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009169 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009170 switch (Pred) {
9171 default: break;
9172 case ICmpInst::ICMP_ULT:
9173 case ICmpInst::ICMP_SLT: {
9174 // X < MIN ? T : F --> F
9175 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9176 return ReplaceInstUsesWith(SI, FalseVal);
9177 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009178 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009179 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9180 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9181 Pred = ICmpInst::getSwappedPredicate(Pred);
9182 CmpRHS = AdjustedRHS;
9183 std::swap(FalseVal, TrueVal);
9184 ICI->setPredicate(Pred);
9185 ICI->setOperand(1, CmpRHS);
9186 SI.setOperand(1, TrueVal);
9187 SI.setOperand(2, FalseVal);
9188 Changed = true;
9189 }
9190 break;
9191 }
9192 case ICmpInst::ICMP_UGT:
9193 case ICmpInst::ICMP_SGT: {
9194 // X > MAX ? T : F --> F
9195 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9196 return ReplaceInstUsesWith(SI, FalseVal);
9197 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009198 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009199 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9200 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9201 Pred = ICmpInst::getSwappedPredicate(Pred);
9202 CmpRHS = AdjustedRHS;
9203 std::swap(FalseVal, TrueVal);
9204 ICI->setPredicate(Pred);
9205 ICI->setOperand(1, CmpRHS);
9206 SI.setOperand(1, TrueVal);
9207 SI.setOperand(2, FalseVal);
9208 Changed = true;
9209 }
9210 break;
9211 }
9212 }
9213
Dan Gohman35b76162008-10-30 20:40:10 +00009214 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9215 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009216 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009217 if (match(TrueVal, m_ConstantInt<-1>()) &&
9218 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009219 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009220 else if (match(TrueVal, m_ConstantInt<0>()) &&
9221 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009222 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9223
Dan Gohman35b76162008-10-30 20:40:10 +00009224 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9225 // If we are just checking for a icmp eq of a single bit and zext'ing it
9226 // to an integer, then shift the bit to the appropriate place and then
9227 // cast to integer to avoid the comparison.
9228 const APInt &Op1CV = CI->getValue();
9229
9230 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9231 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9232 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009233 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009234 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009235 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009236 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009237 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009238 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009239 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009240 if (In->getType() != SI.getType())
9241 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009242 true/*SExt*/, "tmp", ICI);
9243
9244 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009245 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009246 In->getName()+".not"), *ICI);
9247
9248 return ReplaceInstUsesWith(SI, In);
9249 }
9250 }
9251 }
9252
Dan Gohman58c09632008-09-16 18:46:06 +00009253 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9254 // Transform (X == Y) ? X : Y -> Y
9255 if (Pred == ICmpInst::ICMP_EQ)
9256 return ReplaceInstUsesWith(SI, FalseVal);
9257 // Transform (X != Y) ? X : Y -> X
9258 if (Pred == ICmpInst::ICMP_NE)
9259 return ReplaceInstUsesWith(SI, TrueVal);
9260 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9261
9262 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9263 // Transform (X == Y) ? Y : X -> X
9264 if (Pred == ICmpInst::ICMP_EQ)
9265 return ReplaceInstUsesWith(SI, FalseVal);
9266 // Transform (X != Y) ? Y : X -> Y
9267 if (Pred == ICmpInst::ICMP_NE)
9268 return ReplaceInstUsesWith(SI, TrueVal);
9269 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9270 }
9271
9272 /// NOTE: if we wanted to, this is where to detect integer ABS
9273
9274 return Changed ? &SI : 0;
9275}
9276
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009277/// isDefinedInBB - Return true if the value is an instruction defined in the
9278/// specified basicblock.
9279static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9280 const Instruction *I = dyn_cast<Instruction>(V);
9281 return I != 0 && I->getParent() == BB;
9282}
9283
9284
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009285Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9286 Value *CondVal = SI.getCondition();
9287 Value *TrueVal = SI.getTrueValue();
9288 Value *FalseVal = SI.getFalseValue();
9289
9290 // select true, X, Y -> X
9291 // select false, X, Y -> Y
9292 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9293 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9294
9295 // select C, X, X -> X
9296 if (TrueVal == FalseVal)
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298
9299 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9300 return ReplaceInstUsesWith(SI, FalseVal);
9301 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9302 return ReplaceInstUsesWith(SI, TrueVal);
9303 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9304 if (isa<Constant>(TrueVal))
9305 return ReplaceInstUsesWith(SI, TrueVal);
9306 else
9307 return ReplaceInstUsesWith(SI, FalseVal);
9308 }
9309
Owen Anderson35b47072009-08-13 21:58:54 +00009310 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009311 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9312 if (C->getZExtValue()) {
9313 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009314 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009315 } else {
9316 // Change: A = select B, false, C --> A = and !B, C
9317 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009318 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009319 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009320 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009321 }
9322 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9323 if (C->getZExtValue() == false) {
9324 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009325 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009326 } else {
9327 // Change: A = select B, C, true --> A = or !B, C
9328 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009329 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009330 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009331 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009332 }
9333 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009334
9335 // select a, b, a -> a&b
9336 // select a, a, b -> a|b
9337 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009338 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009339 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009340 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009341 }
9342
9343 // Selecting between two integer constants?
9344 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9345 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9346 // select C, 1, 0 -> zext C to int
9347 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009348 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009349 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9350 // select C, 0, 1 -> zext !C to int
9351 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009352 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009353 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009354 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009355 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009356
9357 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009358 // If one of the constants is zero (we know they can't both be) and we
9359 // have an icmp instruction with zero, and we have an 'and' with the
9360 // non-constant value, eliminate this whole mess. This corresponds to
9361 // cases like this: ((X & 27) ? 27 : 0)
9362 if (TrueValC->isZero() || FalseValC->isZero())
9363 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9364 cast<Constant>(IC->getOperand(1))->isNullValue())
9365 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9366 if (ICA->getOpcode() == Instruction::And &&
9367 isa<ConstantInt>(ICA->getOperand(1)) &&
9368 (ICA->getOperand(1) == TrueValC ||
9369 ICA->getOperand(1) == FalseValC) &&
9370 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9371 // Okay, now we know that everything is set up, we just don't
9372 // know whether we have a icmp_ne or icmp_eq and whether the
9373 // true or false val is the zero.
9374 bool ShouldNotVal = !TrueValC->isZero();
9375 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9376 Value *V = ICA;
9377 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009378 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009379 Instruction::Xor, V, ICA->getOperand(1)), SI);
9380 return ReplaceInstUsesWith(SI, V);
9381 }
9382 }
9383 }
9384
9385 // See if we are selecting two values based on a comparison of the two values.
9386 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9387 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9388 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009389 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9390 // This is not safe in general for floating point:
9391 // consider X== -0, Y== +0.
9392 // It becomes safe if either operand is a nonzero constant.
9393 ConstantFP *CFPt, *CFPf;
9394 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9395 !CFPt->getValueAPF().isZero()) ||
9396 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9397 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009398 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009399 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009400 // Transform (X != Y) ? X : Y -> X
9401 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9402 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009403 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009404
9405 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9406 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009407 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9408 // This is not safe in general for floating point:
9409 // consider X== -0, Y== +0.
9410 // It becomes safe if either operand is a nonzero constant.
9411 ConstantFP *CFPt, *CFPf;
9412 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9413 !CFPt->getValueAPF().isZero()) ||
9414 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9415 !CFPf->getValueAPF().isZero()))
9416 return ReplaceInstUsesWith(SI, FalseVal);
9417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009418 // Transform (X != Y) ? Y : X -> Y
9419 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9420 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009421 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009422 }
Dan Gohman58c09632008-09-16 18:46:06 +00009423 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009424 }
9425
9426 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009427 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9428 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9429 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009430
9431 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9432 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9433 if (TI->hasOneUse() && FI->hasOneUse()) {
9434 Instruction *AddOp = 0, *SubOp = 0;
9435
9436 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9437 if (TI->getOpcode() == FI->getOpcode())
9438 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9439 return IV;
9440
9441 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9442 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009443 if ((TI->getOpcode() == Instruction::Sub &&
9444 FI->getOpcode() == Instruction::Add) ||
9445 (TI->getOpcode() == Instruction::FSub &&
9446 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009447 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009448 } else if ((FI->getOpcode() == Instruction::Sub &&
9449 TI->getOpcode() == Instruction::Add) ||
9450 (FI->getOpcode() == Instruction::FSub &&
9451 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009452 AddOp = TI; SubOp = FI;
9453 }
9454
9455 if (AddOp) {
9456 Value *OtherAddOp = 0;
9457 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9458 OtherAddOp = AddOp->getOperand(1);
9459 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9460 OtherAddOp = AddOp->getOperand(0);
9461 }
9462
9463 if (OtherAddOp) {
9464 // So at this point we know we have (Y -> OtherAddOp):
9465 // select C, (add X, Y), (sub X, Z)
9466 Value *NegVal; // Compute -Z
9467 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009468 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009469 } else {
9470 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009471 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009472 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009473 }
9474
9475 Value *NewTrueOp = OtherAddOp;
9476 Value *NewFalseOp = NegVal;
9477 if (AddOp != TI)
9478 std::swap(NewTrueOp, NewFalseOp);
9479 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009480 SelectInst::Create(CondVal, NewTrueOp,
9481 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009482
9483 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009484 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009485 }
9486 }
9487 }
9488
9489 // See if we can fold the select into one of our operands.
9490 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009491 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9492 if (FoldI)
9493 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009494 }
9495
Chris Lattnerf7843b72009-09-27 19:57:57 +00009496 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009497 // to be live in the predecessor blocks. If they are instructions in SI's
9498 // block, we can't map to the predecessor.
Chris Lattnerf7843b72009-09-27 19:57:57 +00009499 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009500 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9501 isa<PHINode>(SI.getTrueValue())) &&
9502 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9503 isa<PHINode>(SI.getFalseValue())))
Chris Lattnerf7843b72009-09-27 19:57:57 +00009504 if (Instruction *NV = FoldOpIntoPhi(SI))
9505 return NV;
9506
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009507 if (BinaryOperator::isNot(CondVal)) {
9508 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9509 SI.setOperand(1, FalseVal);
9510 SI.setOperand(2, TrueVal);
9511 return &SI;
9512 }
9513
9514 return 0;
9515}
9516
Dan Gohman2d648bb2008-04-10 18:43:06 +00009517/// EnforceKnownAlignment - If the specified pointer points to an object that
9518/// we control, modify the object's alignment to PrefAlign. This isn't
9519/// often possible though. If alignment is important, a more reliable approach
9520/// is to simply align all global variables and allocation instructions to
9521/// their preferred alignment from the beginning.
9522///
9523static unsigned EnforceKnownAlignment(Value *V,
9524 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009525
Dan Gohman2d648bb2008-04-10 18:43:06 +00009526 User *U = dyn_cast<User>(V);
9527 if (!U) return Align;
9528
Dan Gohman9545fb02009-07-17 20:47:02 +00009529 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009530 default: break;
9531 case Instruction::BitCast:
9532 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9533 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009534 // If all indexes are zero, it is just the alignment of the base pointer.
9535 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009536 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009537 if (!isa<Constant>(*i) ||
9538 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009539 AllZeroOperands = false;
9540 break;
9541 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009542
9543 if (AllZeroOperands) {
9544 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009545 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009546 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009547 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009549 }
9550
9551 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9552 // If there is a large requested alignment and we can, bump up the alignment
9553 // of the global.
9554 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009555 if (GV->getAlignment() >= PrefAlign)
9556 Align = GV->getAlignment();
9557 else {
9558 GV->setAlignment(PrefAlign);
9559 Align = PrefAlign;
9560 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009561 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009562 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9563 // If there is a requested alignment and if this is an alloca, round up.
9564 if (AI->getAlignment() >= PrefAlign)
9565 Align = AI->getAlignment();
9566 else {
9567 AI->setAlignment(PrefAlign);
9568 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009569 }
9570 }
9571
9572 return Align;
9573}
9574
9575/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9576/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9577/// and it is more than the alignment of the ultimate object, see if we can
9578/// increase the alignment of the ultimate object, making this check succeed.
9579unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9580 unsigned PrefAlign) {
9581 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9582 sizeof(PrefAlign) * CHAR_BIT;
9583 APInt Mask = APInt::getAllOnesValue(BitWidth);
9584 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9585 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9586 unsigned TrailZ = KnownZero.countTrailingOnes();
9587 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9588
9589 if (PrefAlign > Align)
9590 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9591
9592 // We don't need to make any adjustment.
9593 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009594}
9595
Chris Lattner00ae5132008-01-13 23:50:23 +00009596Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009597 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009598 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009599 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009600 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009601
9602 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009603 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009604 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009605 return MI;
9606 }
9607
9608 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9609 // load/store.
9610 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9611 if (MemOpLength == 0) return 0;
9612
Chris Lattnerc669fb62008-01-14 00:28:35 +00009613 // Source and destination pointer types are always "i8*" for intrinsic. See
9614 // if the size is something we can handle with a single primitive load/store.
9615 // A single load+store correctly handles overlapping memory in the memmove
9616 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009617 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009618 if (Size == 0) return MI; // Delete this mem transfer.
9619
9620 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009621 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009622
Chris Lattnerc669fb62008-01-14 00:28:35 +00009623 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009624 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009625 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009626
9627 // Memcpy forces the use of i8* for the source and destination. That means
9628 // that if you're using memcpy to move one double around, you'll get a cast
9629 // from double* to i8*. We'd much rather use a double load+store rather than
9630 // an i64 load+store, here because this improves the odds that the source or
9631 // dest address will be promotable. See if we can find a better type than the
9632 // integer datatype.
9633 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9634 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009635 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009636 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9637 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009638 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009639 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9640 if (STy->getNumElements() == 1)
9641 SrcETy = STy->getElementType(0);
9642 else
9643 break;
9644 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9645 if (ATy->getNumElements() == 1)
9646 SrcETy = ATy->getElementType();
9647 else
9648 break;
9649 } else
9650 break;
9651 }
9652
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009653 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009654 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009655 }
9656 }
9657
9658
Chris Lattner00ae5132008-01-13 23:50:23 +00009659 // If the memcpy/memmove provides better alignment info than we can
9660 // infer, use it.
9661 SrcAlign = std::max(SrcAlign, CopyAlign);
9662 DstAlign = std::max(DstAlign, CopyAlign);
9663
Chris Lattner78628292009-08-30 19:47:22 +00009664 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9665 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009666 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9667 InsertNewInstBefore(L, *MI);
9668 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9669
9670 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009671 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009672 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009673}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009674
Chris Lattner5af8a912008-04-30 06:39:11 +00009675Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9676 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009677 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009678 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009679 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009680 return MI;
9681 }
9682
9683 // Extract the length and alignment and fill if they are constant.
9684 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9685 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009686 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009687 return 0;
9688 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009689 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009690
9691 // If the length is zero, this is a no-op
9692 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9693
9694 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9695 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009696 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009697
9698 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009699 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009700
9701 // Alignment 0 is identity for alignment 1 for memset, but not store.
9702 if (Alignment == 0) Alignment = 1;
9703
9704 // Extract the fill value and store.
9705 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009706 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009707 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009708
9709 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009710 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009711 return MI;
9712 }
9713
9714 return 0;
9715}
9716
9717
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009718/// visitCallInst - CallInst simplification. This mostly only handles folding
9719/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9720/// the heavy lifting.
9721///
9722Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009723 // If the caller function is nounwind, mark the call as nounwind, even if the
9724 // callee isn't.
9725 if (CI.getParent()->getParent()->doesNotThrow() &&
9726 !CI.doesNotThrow()) {
9727 CI.setDoesNotThrow();
9728 return &CI;
9729 }
9730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009731 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9732 if (!II) return visitCallSite(&CI);
9733
9734 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9735 // visitCallSite.
9736 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9737 bool Changed = false;
9738
9739 // memmove/cpy/set of zero bytes is a noop.
9740 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9741 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9742
9743 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9744 if (CI->getZExtValue() == 1) {
9745 // Replace the instruction with just byte operations. We would
9746 // transform other cases to loads/stores, but we don't know if
9747 // alignment is sufficient.
9748 }
9749 }
9750
9751 // If we have a memmove and the source operation is a constant global,
9752 // then the source and dest pointers can't alias, so we can change this
9753 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009754 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009755 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9756 if (GVSrc->isConstant()) {
9757 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009758 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9759 const Type *Tys[1];
9760 Tys[0] = CI.getOperand(3)->getType();
9761 CI.setOperand(0,
9762 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009763 Changed = true;
9764 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009765
9766 // memmove(x,x,size) -> noop.
9767 if (MMI->getSource() == MMI->getDest())
9768 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009769 }
9770
9771 // If we can determine a pointer alignment that is bigger than currently
9772 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009773 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009774 if (Instruction *I = SimplifyMemTransfer(MI))
9775 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009776 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9777 if (Instruction *I = SimplifyMemSet(MSI))
9778 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009779 }
9780
9781 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009782 }
9783
9784 switch (II->getIntrinsicID()) {
9785 default: break;
9786 case Intrinsic::bswap:
9787 // bswap(bswap(x)) -> x
9788 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9789 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9790 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9791 break;
9792 case Intrinsic::ppc_altivec_lvx:
9793 case Intrinsic::ppc_altivec_lvxl:
9794 case Intrinsic::x86_sse_loadu_ps:
9795 case Intrinsic::x86_sse2_loadu_pd:
9796 case Intrinsic::x86_sse2_loadu_dq:
9797 // Turn PPC lvx -> load if the pointer is known aligned.
9798 // Turn X86 loadups -> load if the pointer is known aligned.
9799 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009800 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9801 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009802 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009803 }
Chris Lattner989ba312008-06-18 04:33:20 +00009804 break;
9805 case Intrinsic::ppc_altivec_stvx:
9806 case Intrinsic::ppc_altivec_stvxl:
9807 // Turn stvx -> store if the pointer is known aligned.
9808 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9809 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009810 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009811 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009812 return new StoreInst(II->getOperand(1), Ptr);
9813 }
9814 break;
9815 case Intrinsic::x86_sse_storeu_ps:
9816 case Intrinsic::x86_sse2_storeu_pd:
9817 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009818 // Turn X86 storeu -> store if the pointer is known aligned.
9819 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9820 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009821 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009822 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009823 return new StoreInst(II->getOperand(2), Ptr);
9824 }
9825 break;
9826
9827 case Intrinsic::x86_sse_cvttss2si: {
9828 // These intrinsics only demands the 0th element of its input vector. If
9829 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009830 unsigned VWidth =
9831 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9832 APInt DemandedElts(VWidth, 1);
9833 APInt UndefElts(VWidth, 0);
9834 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009835 UndefElts)) {
9836 II->setOperand(1, V);
9837 return II;
9838 }
9839 break;
9840 }
9841
9842 case Intrinsic::ppc_altivec_vperm:
9843 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9844 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9845 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009846
Chris Lattner989ba312008-06-18 04:33:20 +00009847 // Check that all of the elements are integer constants or undefs.
9848 bool AllEltsOk = true;
9849 for (unsigned i = 0; i != 16; ++i) {
9850 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9851 !isa<UndefValue>(Mask->getOperand(i))) {
9852 AllEltsOk = false;
9853 break;
9854 }
9855 }
9856
9857 if (AllEltsOk) {
9858 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00009859 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9860 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009861 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009862
Chris Lattner989ba312008-06-18 04:33:20 +00009863 // Only extract each element once.
9864 Value *ExtractedElts[32];
9865 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9866
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009867 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009868 if (isa<UndefValue>(Mask->getOperand(i)))
9869 continue;
9870 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9871 Idx &= 31; // Match the hardware behavior.
9872
9873 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009874 ExtractedElts[Idx] =
9875 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9876 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9877 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009878 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009879
Chris Lattner989ba312008-06-18 04:33:20 +00009880 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009881 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9882 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9883 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009884 }
Chris Lattner989ba312008-06-18 04:33:20 +00009885 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009886 }
Chris Lattner989ba312008-06-18 04:33:20 +00009887 }
9888 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009889
Chris Lattner989ba312008-06-18 04:33:20 +00009890 case Intrinsic::stackrestore: {
9891 // If the save is right next to the restore, remove the restore. This can
9892 // happen when variable allocas are DCE'd.
9893 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9894 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9895 BasicBlock::iterator BI = SS;
9896 if (&*++BI == II)
9897 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009898 }
Chris Lattner989ba312008-06-18 04:33:20 +00009899 }
9900
9901 // Scan down this block to see if there is another stack restore in the
9902 // same block without an intervening call/alloca.
9903 BasicBlock::iterator BI = II;
9904 TerminatorInst *TI = II->getParent()->getTerminator();
9905 bool CannotRemove = false;
9906 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00009907 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00009908 CannotRemove = true;
9909 break;
9910 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009911 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9912 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9913 // If there is a stackrestore below this one, remove this one.
9914 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9915 return EraseInstFromFunction(CI);
9916 // Otherwise, ignore the intrinsic.
9917 } else {
9918 // If we found a non-intrinsic call, we can't remove the stack
9919 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009920 CannotRemove = true;
9921 break;
9922 }
Chris Lattner989ba312008-06-18 04:33:20 +00009923 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009924 }
Chris Lattner989ba312008-06-18 04:33:20 +00009925
9926 // If the stack restore is in a return/unwind block and if there are no
9927 // allocas or calls between the restore and the return, nuke the restore.
9928 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9929 return EraseInstFromFunction(CI);
9930 break;
9931 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009932 }
9933
9934 return visitCallSite(II);
9935}
9936
9937// InvokeInst simplification
9938//
9939Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9940 return visitCallSite(&II);
9941}
9942
Dale Johannesen96021832008-04-25 21:16:07 +00009943/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9944/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009945static bool isSafeToEliminateVarargsCast(const CallSite CS,
9946 const CastInst * const CI,
9947 const TargetData * const TD,
9948 const int ix) {
9949 if (!CI->isLosslessCast())
9950 return false;
9951
9952 // The size of ByVal arguments is derived from the type, so we
9953 // can't change to a type with a different size. If the size were
9954 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009955 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009956 return true;
9957
9958 const Type* SrcTy =
9959 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9960 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9961 if (!SrcTy->isSized() || !DstTy->isSized())
9962 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00009963 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009964 return false;
9965 return true;
9966}
9967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009968// visitCallSite - Improvements for call and invoke instructions.
9969//
9970Instruction *InstCombiner::visitCallSite(CallSite CS) {
9971 bool Changed = false;
9972
9973 // If the callee is a constexpr cast of a function, attempt to move the cast
9974 // to the arguments of the call/invoke.
9975 if (transformConstExprCastCall(CS)) return 0;
9976
9977 Value *Callee = CS.getCalledValue();
9978
9979 if (Function *CalleeF = dyn_cast<Function>(Callee))
9980 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9981 Instruction *OldCall = CS.getInstruction();
9982 // If the call and callee calling conventions don't match, this call must
9983 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009984 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +00009985 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +00009986 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +00009987 // If OldCall dues not return void then replaceAllUsesWith undef.
9988 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00009989 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00009990 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009991 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9992 return EraseInstFromFunction(*OldCall);
9993 return 0;
9994 }
9995
9996 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9997 // This instruction is not reachable, just remove it. We insert a store to
9998 // undef so that we know that this code is not reachable, despite the fact
9999 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010000 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010001 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010002 CS.getInstruction());
10003
Devang Patele3829c82009-10-13 22:56:32 +000010004 // If CS dues not return void then replaceAllUsesWith undef.
10005 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010006 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010007 CS.getInstruction()->
10008 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010009
10010 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10011 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010012 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010013 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010014 }
10015 return EraseInstFromFunction(*CS.getInstruction());
10016 }
10017
Duncan Sands74833f22007-09-17 10:26:40 +000010018 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10019 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10020 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10021 return transformCallThroughTrampoline(CS);
10022
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010023 const PointerType *PTy = cast<PointerType>(Callee->getType());
10024 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10025 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010026 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010027 // See if we can optimize any arguments passed through the varargs area of
10028 // the call.
10029 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010030 E = CS.arg_end(); I != E; ++I, ++ix) {
10031 CastInst *CI = dyn_cast<CastInst>(*I);
10032 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10033 *I = CI->getOperand(0);
10034 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010035 }
Dale Johannesen35615462008-04-23 18:34:37 +000010036 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010037 }
10038
Duncan Sands2937e352007-12-19 21:13:37 +000010039 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010040 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010041 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010042 Changed = true;
10043 }
10044
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010045 return Changed ? CS.getInstruction() : 0;
10046}
10047
10048// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10049// attempt to move the cast to the arguments of the call/invoke.
10050//
10051bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10052 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10053 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10054 if (CE->getOpcode() != Instruction::BitCast ||
10055 !isa<Function>(CE->getOperand(0)))
10056 return false;
10057 Function *Callee = cast<Function>(CE->getOperand(0));
10058 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010059 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010060
10061 // Okay, this is a cast from a function to a different type. Unless doing so
10062 // would cause a type conversion of one of our arguments, change this call to
10063 // be a direct call with arguments casted to the appropriate types.
10064 //
10065 const FunctionType *FT = Callee->getFunctionType();
10066 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010067 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010068
Duncan Sands7901ce12008-06-01 07:38:42 +000010069 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010070 return false; // TODO: Handle multiple return values.
10071
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010072 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010073 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010074 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010075 // Conversion is ok if changing from one pointer type to another or from
10076 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010077 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010078 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010079 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010080 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010081 return false; // Cannot transform this return value.
10082
Duncan Sands5c489582008-01-06 10:12:28 +000010083 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010084 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010085 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010086 return false; // Cannot transform this return value.
10087
Chris Lattner1c8733e2008-03-12 17:45:29 +000010088 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010089 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010090 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010091 return false; // Attribute not compatible with transformed value.
10092 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010093
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010094 // If the callsite is an invoke instruction, and the return value is used by
10095 // a PHI node in a successor, we cannot change the return type of the call
10096 // because there is no place to put the cast instruction (without breaking
10097 // the critical edge). Bail out in this case.
10098 if (!Caller->use_empty())
10099 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10100 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10101 UI != E; ++UI)
10102 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10103 if (PN->getParent() == II->getNormalDest() ||
10104 PN->getParent() == II->getUnwindDest())
10105 return false;
10106 }
10107
10108 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10109 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10110
10111 CallSite::arg_iterator AI = CS.arg_begin();
10112 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10113 const Type *ParamTy = FT->getParamType(i);
10114 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010115
10116 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010117 return false; // Cannot transform this parameter value.
10118
Devang Patelf2a4a922008-09-26 22:53:05 +000010119 if (CallerPAL.getParamAttributes(i + 1)
10120 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010121 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010122
Duncan Sands7901ce12008-06-01 07:38:42 +000010123 // Converting from one pointer type to another or between a pointer and an
10124 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010125 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010126 (TD && ((isa<PointerType>(ParamTy) ||
10127 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10128 (isa<PointerType>(ActTy) ||
10129 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010130 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010131 }
10132
10133 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10134 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010135 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010136
Chris Lattner1c8733e2008-03-12 17:45:29 +000010137 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10138 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010139 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010140 // won't be dropping them. Check that these extra arguments have attributes
10141 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010142 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10143 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010144 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010145 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010146 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010147 return false;
10148 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010149
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010150 // Okay, we decided that this is a safe thing to do: go ahead and start
10151 // inserting cast instructions as necessary...
10152 std::vector<Value*> Args;
10153 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010154 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010155 attrVec.reserve(NumCommonArgs);
10156
10157 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010158 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010159
10160 // If the return value is not being used, the type may not be compatible
10161 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010162 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010163
10164 // Add the new return attributes.
10165 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010166 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010167
10168 AI = CS.arg_begin();
10169 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10170 const Type *ParamTy = FT->getParamType(i);
10171 if ((*AI)->getType() == ParamTy) {
10172 Args.push_back(*AI);
10173 } else {
10174 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10175 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010176 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010177 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010178
10179 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010180 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010181 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010182 }
10183
10184 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010185 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010186 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010187 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010188
Chris Lattnerad7516a2009-08-30 18:50:58 +000010189 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010190 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010191 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010192 errs() << "WARNING: While resolving call to function '"
10193 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010194 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010195 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010196 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10197 const Type *PTy = getPromotedType((*AI)->getType());
10198 if (PTy != (*AI)->getType()) {
10199 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010200 Instruction::CastOps opcode =
10201 CastInst::getCastOpcode(*AI, false, PTy, false);
10202 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010203 } else {
10204 Args.push_back(*AI);
10205 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010206
Duncan Sands4ced1f82008-01-13 08:02:44 +000010207 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010208 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010209 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010210 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010211 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010212 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010213
Devang Patelf2a4a922008-09-26 22:53:05 +000010214 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10215 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10216
Devang Patele9d08b82009-10-14 17:29:00 +000010217 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010218 Caller->setName(""); // Void type should not have a name.
10219
Eric Christopher3e7381f2009-07-25 02:45:27 +000010220 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10221 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010222
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010223 Instruction *NC;
10224 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010225 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010226 Args.begin(), Args.end(),
10227 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010228 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010229 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010230 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010231 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10232 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010233 CallInst *CI = cast<CallInst>(Caller);
10234 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010235 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010236 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010237 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010238 }
10239
10240 // Insert a cast of the return type as necessary.
10241 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010242 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010243 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010244 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010245 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010246 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010247
10248 // If this is an invoke instruction, we should insert it after the first
10249 // non-phi, instruction in the normal successor block.
10250 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010251 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010252 InsertNewInstBefore(NC, *I);
10253 } else {
10254 // Otherwise, it's a call, just insert cast right after the call instr
10255 InsertNewInstBefore(NC, *Caller);
10256 }
Chris Lattner4796b622009-08-30 06:22:51 +000010257 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010258 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010259 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010260 }
10261 }
10262
Devang Pateledad36f2009-10-13 21:41:20 +000010263
Chris Lattner26b7f942009-08-31 05:17:58 +000010264 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010265 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010266
10267 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010268 return true;
10269}
10270
Duncan Sands74833f22007-09-17 10:26:40 +000010271// transformCallThroughTrampoline - Turn a call to a function created by the
10272// init_trampoline intrinsic into a direct call to the underlying function.
10273//
10274Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10275 Value *Callee = CS.getCalledValue();
10276 const PointerType *PTy = cast<PointerType>(Callee->getType());
10277 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010278 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010279
10280 // If the call already has the 'nest' attribute somewhere then give up -
10281 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010282 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010283 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010284
10285 IntrinsicInst *Tramp =
10286 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10287
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010288 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010289 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10290 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10291
Devang Pateld222f862008-09-25 21:00:45 +000010292 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010293 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010294 unsigned NestIdx = 1;
10295 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010296 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010297
10298 // Look for a parameter marked with the 'nest' attribute.
10299 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10300 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010301 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010302 // Record the parameter type and any other attributes.
10303 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010304 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010305 break;
10306 }
10307
10308 if (NestTy) {
10309 Instruction *Caller = CS.getInstruction();
10310 std::vector<Value*> NewArgs;
10311 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10312
Devang Pateld222f862008-09-25 21:00:45 +000010313 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010314 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010315
Duncan Sands74833f22007-09-17 10:26:40 +000010316 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010317 // mean appending it. Likewise for attributes.
10318
Devang Patelf2a4a922008-09-26 22:53:05 +000010319 // Add any result attributes.
10320 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010321 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010322
Duncan Sands74833f22007-09-17 10:26:40 +000010323 {
10324 unsigned Idx = 1;
10325 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10326 do {
10327 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010328 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010329 Value *NestVal = Tramp->getOperand(3);
10330 if (NestVal->getType() != NestTy)
10331 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10332 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010333 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010334 }
10335
10336 if (I == E)
10337 break;
10338
Duncan Sands48b81112008-01-14 19:52:09 +000010339 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010340 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010341 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010342 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010343 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010344
10345 ++Idx, ++I;
10346 } while (1);
10347 }
10348
Devang Patelf2a4a922008-09-26 22:53:05 +000010349 // Add any function attributes.
10350 if (Attributes Attr = Attrs.getFnAttributes())
10351 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10352
Duncan Sands74833f22007-09-17 10:26:40 +000010353 // The trampoline may have been bitcast to a bogus type (FTy).
10354 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010355 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010356
Duncan Sands74833f22007-09-17 10:26:40 +000010357 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010358 NewTypes.reserve(FTy->getNumParams()+1);
10359
Duncan Sands74833f22007-09-17 10:26:40 +000010360 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010361 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010362 {
10363 unsigned Idx = 1;
10364 FunctionType::param_iterator I = FTy->param_begin(),
10365 E = FTy->param_end();
10366
10367 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010368 if (Idx == NestIdx)
10369 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010370 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010371
10372 if (I == E)
10373 break;
10374
Duncan Sands48b81112008-01-14 19:52:09 +000010375 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010376 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010377
10378 ++Idx, ++I;
10379 } while (1);
10380 }
10381
10382 // Replace the trampoline call with a direct call. Let the generic
10383 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010384 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010385 FTy->isVarArg());
10386 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010387 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010388 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010389 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010390 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10391 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010392
10393 Instruction *NewCaller;
10394 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010395 NewCaller = InvokeInst::Create(NewCallee,
10396 II->getNormalDest(), II->getUnwindDest(),
10397 NewArgs.begin(), NewArgs.end(),
10398 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010399 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010400 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010401 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010402 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10403 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010404 if (cast<CallInst>(Caller)->isTailCall())
10405 cast<CallInst>(NewCaller)->setTailCall();
10406 cast<CallInst>(NewCaller)->
10407 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010408 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010409 }
Devang Patele9d08b82009-10-14 17:29:00 +000010410 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010411 Caller->replaceAllUsesWith(NewCaller);
10412 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010413 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010414 return 0;
10415 }
10416 }
10417
10418 // Replace the trampoline call with a direct call. Since there is no 'nest'
10419 // parameter, there is no need to adjust the argument list. Let the generic
10420 // code sort out any function type mismatches.
10421 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010422 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010423 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010424 CS.setCalledFunction(NewCallee);
10425 return CS.getInstruction();
10426}
10427
Dan Gohman09cf2b62009-09-16 16:50:24 +000010428/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10429/// and if a/b/c and the add's all have a single use, turn this into a phi
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010430/// and a single binop.
10431Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10432 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010433 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010434 unsigned Opc = FirstInst->getOpcode();
10435 Value *LHSVal = FirstInst->getOperand(0);
10436 Value *RHSVal = FirstInst->getOperand(1);
10437
10438 const Type *LHSType = LHSVal->getType();
10439 const Type *RHSType = RHSVal->getType();
10440
Dan Gohman09cf2b62009-09-16 16:50:24 +000010441 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010442 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010443 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10444 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10445 // Verify type of the LHS matches so we don't fold cmp's of different
10446 // types or GEP's with different index types.
10447 I->getOperand(0)->getType() != LHSType ||
10448 I->getOperand(1)->getType() != RHSType)
10449 return 0;
10450
10451 // If they are CmpInst instructions, check their predicates
10452 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10453 if (cast<CmpInst>(I)->getPredicate() !=
10454 cast<CmpInst>(FirstInst)->getPredicate())
10455 return 0;
10456
10457 // Keep track of which operand needs a phi node.
10458 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10459 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10460 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010461
10462 // If both LHS and RHS would need a PHI, don't do this transformation,
10463 // because it would increase the number of PHIs entering the block,
10464 // which leads to higher register pressure. This is especially
10465 // bad when the PHIs are in the header of a loop.
10466 if (!LHSVal && !RHSVal)
10467 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010468
Chris Lattner30078012008-12-01 03:42:51 +000010469 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010470
10471 Value *InLHS = FirstInst->getOperand(0);
10472 Value *InRHS = FirstInst->getOperand(1);
10473 PHINode *NewLHS = 0, *NewRHS = 0;
10474 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010475 NewLHS = PHINode::Create(LHSType,
10476 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010477 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10478 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10479 InsertNewInstBefore(NewLHS, PN);
10480 LHSVal = NewLHS;
10481 }
10482
10483 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010484 NewRHS = PHINode::Create(RHSType,
10485 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010486 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10487 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10488 InsertNewInstBefore(NewRHS, PN);
10489 RHSVal = NewRHS;
10490 }
10491
10492 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010493 if (NewLHS || NewRHS) {
10494 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10495 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10496 if (NewLHS) {
10497 Value *NewInLHS = InInst->getOperand(0);
10498 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10499 }
10500 if (NewRHS) {
10501 Value *NewInRHS = InInst->getOperand(1);
10502 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10503 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010504 }
10505 }
10506
10507 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010508 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010509 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010510 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010511 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010512}
10513
Chris Lattner9e1916e2008-12-01 02:34:36 +000010514Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10515 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10516
10517 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10518 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010519 // This is true if all GEP bases are allocas and if all indices into them are
10520 // constants.
10521 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010522
10523 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010524 // more than one phi, which leads to higher register pressure. This is
10525 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010526 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010527
Dan Gohman09cf2b62009-09-16 16:50:24 +000010528 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010529 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10530 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10531 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10532 GEP->getNumOperands() != FirstInst->getNumOperands())
10533 return 0;
10534
Chris Lattneradf354b2009-02-21 00:46:50 +000010535 // Keep track of whether or not all GEPs are of alloca pointers.
10536 if (AllBasePointersAreAllocas &&
10537 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10538 !GEP->hasAllConstantIndices()))
10539 AllBasePointersAreAllocas = false;
10540
Chris Lattner9e1916e2008-12-01 02:34:36 +000010541 // Compare the operand lists.
10542 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10543 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10544 continue;
10545
10546 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10547 // if one of the PHIs has a constant for the index. The index may be
10548 // substantially cheaper to compute for the constants, so making it a
10549 // variable index could pessimize the path. This also handles the case
10550 // for struct indices, which must always be constant.
10551 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10552 isa<ConstantInt>(GEP->getOperand(op)))
10553 return 0;
10554
10555 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10556 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010557
10558 // If we already needed a PHI for an earlier operand, and another operand
10559 // also requires a PHI, we'd be introducing more PHIs than we're
10560 // eliminating, which increases register pressure on entry to the PHI's
10561 // block.
10562 if (NeededPhi)
10563 return 0;
10564
Chris Lattner9e1916e2008-12-01 02:34:36 +000010565 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010566 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010567 }
10568 }
10569
Chris Lattneradf354b2009-02-21 00:46:50 +000010570 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010571 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010572 // offset calculation, but all the predecessors will have to materialize the
10573 // stack address into a register anyway. We'd actually rather *clone* the
10574 // load up into the predecessors so that we have a load of a gep of an alloca,
10575 // which can usually all be folded into the load.
10576 if (AllBasePointersAreAllocas)
10577 return 0;
10578
Chris Lattner9e1916e2008-12-01 02:34:36 +000010579 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10580 // that is variable.
10581 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10582
10583 bool HasAnyPHIs = false;
10584 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10585 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10586 Value *FirstOp = FirstInst->getOperand(i);
10587 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10588 FirstOp->getName()+".pn");
10589 InsertNewInstBefore(NewPN, PN);
10590
10591 NewPN->reserveOperandSpace(e);
10592 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10593 OperandPhis[i] = NewPN;
10594 FixedOperands[i] = NewPN;
10595 HasAnyPHIs = true;
10596 }
10597
10598
10599 // Add all operands to the new PHIs.
10600 if (HasAnyPHIs) {
10601 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10602 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10603 BasicBlock *InBB = PN.getIncomingBlock(i);
10604
10605 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10606 if (PHINode *OpPhi = OperandPhis[op])
10607 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10608 }
10609 }
10610
10611 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010612 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10613 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10614 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010615 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10616 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010617}
10618
10619
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010620/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10621/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010622/// obvious the value of the load is not changed from the point of the load to
10623/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010624///
10625/// Finally, it is safe, but not profitable, to sink a load targetting a
10626/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10627/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010628static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010629 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10630
10631 for (++BBI; BBI != E; ++BBI)
10632 if (BBI->mayWriteToMemory())
10633 return false;
10634
10635 // Check for non-address taken alloca. If not address-taken already, it isn't
10636 // profitable to do this xform.
10637 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10638 bool isAddressTaken = false;
10639 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10640 UI != E; ++UI) {
10641 if (isa<LoadInst>(UI)) continue;
10642 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10643 // If storing TO the alloca, then the address isn't taken.
10644 if (SI->getOperand(1) == AI) continue;
10645 }
10646 isAddressTaken = true;
10647 break;
10648 }
10649
Chris Lattneradf354b2009-02-21 00:46:50 +000010650 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010651 return false;
10652 }
10653
Chris Lattneradf354b2009-02-21 00:46:50 +000010654 // If this load is a load from a GEP with a constant offset from an alloca,
10655 // then we don't want to sink it. In its present form, it will be
10656 // load [constant stack offset]. Sinking it will cause us to have to
10657 // materialize the stack addresses in each predecessor in a register only to
10658 // do a shared load from register in the successor.
10659 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10660 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10661 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10662 return false;
10663
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010664 return true;
10665}
10666
10667
10668// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10669// operator and they all are only used by the PHI, PHI together their
10670// inputs, and do the operation once, to the result of the PHI.
10671Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10672 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10673
10674 // Scan the instruction, looking for input operations that can be folded away.
10675 // If all input operands to the phi are the same instruction (e.g. a cast from
10676 // the same type or "+42") we can pull the operation through the PHI, reducing
10677 // code size and simplifying code.
10678 Constant *ConstantOp = 0;
10679 const Type *CastSrcTy = 0;
10680 bool isVolatile = false;
10681 if (isa<CastInst>(FirstInst)) {
10682 CastSrcTy = FirstInst->getOperand(0)->getType();
10683 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10684 // Can fold binop, compare or shift here if the RHS is a constant,
10685 // otherwise call FoldPHIArgBinOpIntoPHI.
10686 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10687 if (ConstantOp == 0)
10688 return FoldPHIArgBinOpIntoPHI(PN);
10689 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10690 isVolatile = LI->isVolatile();
10691 // We can't sink the load if the loaded value could be modified between the
10692 // load and the PHI.
10693 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010694 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010695 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010696
10697 // If the PHI is of volatile loads and the load block has multiple
10698 // successors, sinking it would remove a load of the volatile value from
10699 // the path through the other successor.
10700 if (isVolatile &&
10701 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10702 return 0;
10703
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010704 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010705 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010706 } else {
10707 return 0; // Cannot fold this operation.
10708 }
10709
10710 // Check to see if all arguments are the same operation.
10711 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10712 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10713 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10714 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10715 return 0;
10716 if (CastSrcTy) {
10717 if (I->getOperand(0)->getType() != CastSrcTy)
10718 return 0; // Cast operation must match.
10719 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10720 // We can't sink the load if the loaded value could be modified between
10721 // the load and the PHI.
10722 if (LI->isVolatile() != isVolatile ||
10723 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010724 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010725 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010726
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010727 // If the PHI is of volatile loads and the load block has multiple
10728 // successors, sinking it would remove a load of the volatile value from
10729 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010730 if (isVolatile &&
10731 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10732 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010733
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010734 } else if (I->getOperand(1) != ConstantOp) {
10735 return 0;
10736 }
10737 }
10738
10739 // Okay, they are all the same operation. Create a new PHI node of the
10740 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010741 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10742 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010743 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10744
10745 Value *InVal = FirstInst->getOperand(0);
10746 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10747
10748 // Add all operands to the new PHI.
10749 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10750 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10751 if (NewInVal != InVal)
10752 InVal = 0;
10753 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10754 }
10755
10756 Value *PhiVal;
10757 if (InVal) {
10758 // The new PHI unions all of the same values together. This is really
10759 // common, so we handle it intelligently here for compile-time speed.
10760 PhiVal = InVal;
10761 delete NewPN;
10762 } else {
10763 InsertNewInstBefore(NewPN, PN);
10764 PhiVal = NewPN;
10765 }
10766
10767 // Insert and return the new operation.
10768 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010769 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010770 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010771 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010772 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohmane6803b82009-08-25 23:17:54 +000010773 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010774 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010775 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10776
10777 // If this was a volatile load that we are merging, make sure to loop through
10778 // and mark all the input loads as non-volatile. If we don't do this, we will
10779 // insert a new volatile load and the old ones will not be deletable.
10780 if (isVolatile)
10781 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10782 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10783
10784 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010785}
10786
10787/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10788/// that is dead.
10789static bool DeadPHICycle(PHINode *PN,
10790 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10791 if (PN->use_empty()) return true;
10792 if (!PN->hasOneUse()) return false;
10793
10794 // Remember this node, and if we find the cycle, return.
10795 if (!PotentiallyDeadPHIs.insert(PN))
10796 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010797
10798 // Don't scan crazily complex things.
10799 if (PotentiallyDeadPHIs.size() == 16)
10800 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010801
10802 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10803 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10804
10805 return false;
10806}
10807
Chris Lattner27b695d2007-11-06 21:52:06 +000010808/// PHIsEqualValue - Return true if this phi node is always equal to
10809/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10810/// z = some value; x = phi (y, z); y = phi (x, z)
10811static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10812 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10813 // See if we already saw this PHI node.
10814 if (!ValueEqualPHIs.insert(PN))
10815 return true;
10816
10817 // Don't scan crazily complex things.
10818 if (ValueEqualPHIs.size() == 16)
10819 return false;
10820
10821 // Scan the operands to see if they are either phi nodes or are equal to
10822 // the value.
10823 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10824 Value *Op = PN->getIncomingValue(i);
10825 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10826 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10827 return false;
10828 } else if (Op != NonPhiInVal)
10829 return false;
10830 }
10831
10832 return true;
10833}
10834
10835
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010836// PHINode simplification
10837//
10838Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10839 // If LCSSA is around, don't mess with Phi nodes
10840 if (MustPreserveLCSSA) return 0;
10841
10842 if (Value *V = PN.hasConstantValue())
10843 return ReplaceInstUsesWith(PN, V);
10844
10845 // If all PHI operands are the same operation, pull them through the PHI,
10846 // reducing code size.
10847 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010848 isa<Instruction>(PN.getIncomingValue(1)) &&
10849 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10850 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10851 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10852 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010853 PN.getIncomingValue(0)->hasOneUse())
10854 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10855 return Result;
10856
10857 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10858 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10859 // PHI)... break the cycle.
10860 if (PN.hasOneUse()) {
10861 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10862 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10863 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10864 PotentiallyDeadPHIs.insert(&PN);
10865 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010866 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010867 }
10868
10869 // If this phi has a single use, and if that use just computes a value for
10870 // the next iteration of a loop, delete the phi. This occurs with unused
10871 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10872 // common case here is good because the only other things that catch this
10873 // are induction variable analysis (sometimes) and ADCE, which is only run
10874 // late.
10875 if (PHIUser->hasOneUse() &&
10876 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10877 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010878 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010879 }
10880 }
10881
Chris Lattner27b695d2007-11-06 21:52:06 +000010882 // We sometimes end up with phi cycles that non-obviously end up being the
10883 // same value, for example:
10884 // z = some value; x = phi (y, z); y = phi (x, z)
10885 // where the phi nodes don't necessarily need to be in the same block. Do a
10886 // quick check to see if the PHI node only contains a single non-phi value, if
10887 // so, scan to see if the phi cycle is actually equal to that value.
10888 {
10889 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10890 // Scan for the first non-phi operand.
10891 while (InValNo != NumOperandVals &&
10892 isa<PHINode>(PN.getIncomingValue(InValNo)))
10893 ++InValNo;
10894
10895 if (InValNo != NumOperandVals) {
10896 Value *NonPhiInVal = PN.getOperand(InValNo);
10897
10898 // Scan the rest of the operands to see if there are any conflicts, if so
10899 // there is no need to recursively scan other phis.
10900 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10901 Value *OpVal = PN.getIncomingValue(InValNo);
10902 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10903 break;
10904 }
10905
10906 // If we scanned over all operands, then we have one unique value plus
10907 // phi values. Scan PHI nodes to see if they all merge in each other or
10908 // the value.
10909 if (InValNo == NumOperandVals) {
10910 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10911 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10912 return ReplaceInstUsesWith(PN, NonPhiInVal);
10913 }
10914 }
10915 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010916 return 0;
10917}
10918
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010919Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10920 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerf3a23592009-08-30 20:36:46 +000010921 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010922 if (GEP.getNumOperands() == 1)
10923 return ReplaceInstUsesWith(GEP, PtrOp);
10924
10925 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010926 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010927
10928 bool HasZeroPointerIndex = false;
10929 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10930 HasZeroPointerIndex = C->isNullValue();
10931
10932 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10933 return ReplaceInstUsesWith(GEP, PtrOp);
10934
10935 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010936 if (TD) {
10937 bool MadeChange = false;
10938 unsigned PtrSize = TD->getPointerSizeInBits();
10939
10940 gep_type_iterator GTI = gep_type_begin(GEP);
10941 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10942 I != E; ++I, ++GTI) {
10943 if (!isa<SequentialType>(*GTI)) continue;
10944
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010945 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010946 // to what we need. If narrower, sign-extend it to what we need. This
10947 // explicit cast can make subsequent optimizations more obvious.
10948 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010949 if (OpBits == PtrSize)
10950 continue;
10951
Chris Lattnerd6164c22009-08-30 20:01:10 +000010952 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010953 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010954 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010955 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010956 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010957
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010958 // Combine Indices - If the source pointer to this getelementptr instruction
10959 // is a getelementptr instruction, combine the indices of the two
10960 // getelementptr instructions into a single instruction.
10961 //
Dan Gohman17f46f72009-07-28 01:40:03 +000010962 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010963 // Note that if our source is a gep chain itself that we wait for that
10964 // chain to be resolved before we perform this transformation. This
10965 // avoids us creating a TON of code in some cases.
10966 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010967 if (GetElementPtrInst *SrcGEP =
10968 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10969 if (SrcGEP->getNumOperands() == 2)
10970 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010971
10972 SmallVector<Value*, 8> Indices;
10973
10974 // Find out whether the last index in the source GEP is a sequential idx.
10975 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000010976 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10977 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010978 EndsWithSequential = !isa<StructType>(*I);
10979
10980 // Can we combine the two pointer arithmetics offsets?
10981 if (EndsWithSequential) {
10982 // Replace: gep (gep %P, long B), long A, ...
10983 // With: T = long A+B; gep %P, T, ...
10984 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010985 Value *Sum;
10986 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10987 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000010988 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010989 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000010990 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010991 Sum = SO1;
10992 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000010993 // If they aren't the same type, then the input hasn't been processed
10994 // by the loop above yet (which canonicalizes sequential index types to
10995 // intptr_t). Just avoid transforming this until the input has been
10996 // normalized.
10997 if (SO1->getType() != GO1->getType())
10998 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000010999 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011000 }
11001
Chris Lattner1c641fc2009-08-30 05:30:55 +000011002 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011003 if (Src->getNumOperands() == 2) {
11004 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011005 GEP.setOperand(1, Sum);
11006 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011007 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011008 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011009 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011010 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011011 } else if (isa<Constant>(*GEP.idx_begin()) &&
11012 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011013 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011014 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011015 Indices.append(Src->op_begin()+1, Src->op_end());
11016 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011017 }
11018
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011019 if (!Indices.empty())
11020 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11021 Src->isInBounds()) ?
11022 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11023 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011024 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011025 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011026 }
11027
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011028 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11029 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011030 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011031
Chris Lattner83288fa2009-08-30 20:38:21 +000011032 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11033 // want to change the gep until the bitcasts are eliminated.
11034 if (getBitCastOperand(X)) {
11035 Worklist.AddValue(PtrOp);
11036 return 0;
11037 }
11038
Chris Lattnerf3a23592009-08-30 20:36:46 +000011039 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11040 // into : GEP [10 x i8]* X, i32 0, ...
11041 //
11042 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11043 // into : GEP i8* X, ...
11044 //
11045 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011046 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011047 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11048 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011049 if (const ArrayType *CATy =
11050 dyn_cast<ArrayType>(CPTy->getElementType())) {
11051 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11052 if (CATy->getElementType() == XTy->getElementType()) {
11053 // -> GEP i8* X, ...
11054 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011055 return cast<GEPOperator>(&GEP)->isInBounds() ?
11056 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11057 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011058 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11059 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011060 }
11061
11062 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011063 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011064 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011065 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011066 // At this point, we know that the cast source type is a pointer
11067 // to an array of the same type as the destination pointer
11068 // array. Because the array type is never stepped over (there
11069 // is a leading zero) we can fold the cast into this GEP.
11070 GEP.setOperand(0, X);
11071 return &GEP;
11072 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011073 }
11074 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011075 } else if (GEP.getNumOperands() == 2) {
11076 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011077 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11078 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011079 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11080 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011081 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011082 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11083 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011084 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011085 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011086 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011087 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11088 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011089 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011090 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011091 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011092 }
11093
11094 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011095 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011096 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011097 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011098
Owen Anderson35b47072009-08-13 21:58:54 +000011099 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011100 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011101 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011102
11103 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11104 // allow either a mul, shift, or constant here.
11105 Value *NewIdx = 0;
11106 ConstantInt *Scale = 0;
11107 if (ArrayEltSize == 1) {
11108 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011109 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011110 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011111 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011112 Scale = CI;
11113 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11114 if (Inst->getOpcode() == Instruction::Shl &&
11115 isa<ConstantInt>(Inst->getOperand(1))) {
11116 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11117 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011118 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011119 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011120 NewIdx = Inst->getOperand(0);
11121 } else if (Inst->getOpcode() == Instruction::Mul &&
11122 isa<ConstantInt>(Inst->getOperand(1))) {
11123 Scale = cast<ConstantInt>(Inst->getOperand(1));
11124 NewIdx = Inst->getOperand(0);
11125 }
11126 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011127
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011128 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011129 // out, perform the transformation. Note, we don't know whether Scale is
11130 // signed or not. We'll use unsigned version of division/modulo
11131 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011132 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011133 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011134 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011135 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011136 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011137 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11138 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011139 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011140 }
11141
11142 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011143 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011144 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011145 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011146 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11147 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11148 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011149 // The NewGEP must be pointer typed, so must the old one -> BitCast
11150 return new BitCastInst(NewGEP, GEP.getType());
11151 }
11152 }
11153 }
11154 }
Chris Lattner111ea772009-01-09 04:53:57 +000011155
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011156 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011157 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011158 /// Y = gep X, <...constant indices...>
11159 /// into a gep of the original struct. This is important for SROA and alias
11160 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011161 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011162 if (TD &&
11163 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011164 // Determine how much the GEP moves the pointer. We are guaranteed to get
11165 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011166 ConstantInt *OffsetV =
11167 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011168 int64_t Offset = OffsetV->getSExtValue();
11169
11170 // If this GEP instruction doesn't move the pointer, just replace the GEP
11171 // with a bitcast of the real input to the dest type.
11172 if (Offset == 0) {
11173 // If the bitcast is of an allocation, and the allocation will be
11174 // converted to match the type of the cast, don't touch this.
Victor Hernandez48c3c542009-09-18 22:35:49 +000011175 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11176 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011177 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11178 if (Instruction *I = visitBitCast(*BCI)) {
11179 if (I != BCI) {
11180 I->takeName(BCI);
11181 BCI->getParent()->getInstList().insert(BCI, I);
11182 ReplaceInstUsesWith(*BCI, I);
11183 }
11184 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011185 }
Chris Lattner111ea772009-01-09 04:53:57 +000011186 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011187 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011188 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011189
11190 // Otherwise, if the offset is non-zero, we need to find out if there is a
11191 // field at Offset in 'A's type. If so, we can pull the cast through the
11192 // GEP.
11193 SmallVector<Value*, 8> NewIndices;
11194 const Type *InTy =
11195 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011196 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011197 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11198 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11199 NewIndices.end()) :
11200 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11201 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011202
11203 if (NGEP->getType() == GEP.getType())
11204 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011205 NGEP->takeName(&GEP);
11206 return new BitCastInst(NGEP, GEP.getType());
11207 }
Chris Lattner111ea772009-01-09 04:53:57 +000011208 }
11209 }
11210
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011211 return 0;
11212}
11213
11214Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11215 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011216 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011217 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11218 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011219 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000011220 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11221 AllocationInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011222 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011223
11224 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011225 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011226 //
11227 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011228 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011229
11230 // Now that I is pointing to the first non-allocation-inst in the block,
11231 // insert our getelementptr instruction...
11232 //
Owen Anderson35b47072009-08-13 21:58:54 +000011233 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011234 Value *Idx[2];
11235 Idx[0] = NullIdx;
11236 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011237 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11238 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011239
11240 // Now make everything use the getelementptr instead of the original
11241 // allocation.
11242 return ReplaceInstUsesWith(AI, V);
11243 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011244 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011245 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011246 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011247
Dan Gohmana80e2712009-07-21 23:21:54 +000011248 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011249 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011250 // Note that we only do this for alloca's, because malloc should allocate
11251 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011252 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011253 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011254
11255 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11256 if (AI.getAlignment() == 0)
11257 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11258 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011259
11260 return 0;
11261}
11262
11263Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11264 Value *Op = FI.getOperand(0);
11265
11266 // free undef -> unreachable.
11267 if (isa<UndefValue>(Op)) {
11268 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011269 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000011270 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 return EraseInstFromFunction(FI);
11272 }
11273
11274 // If we have 'free null' delete the instruction. This can happen in stl code
11275 // when lots of inlining happens.
11276 if (isa<ConstantPointerNull>(Op))
11277 return EraseInstFromFunction(FI);
11278
11279 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11280 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11281 FI.setOperand(0, CI->getOperand(0));
11282 return &FI;
11283 }
11284
11285 // Change free (gep X, 0,0,0,0) into free(X)
11286 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11287 if (GEPI->hasAllZeroIndices()) {
Chris Lattner3183fb62009-08-30 06:13:40 +000011288 Worklist.Add(GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011289 FI.setOperand(0, GEPI->getOperand(0));
11290 return &FI;
11291 }
11292 }
11293
Victor Hernandez48c3c542009-09-18 22:35:49 +000011294 if (isMalloc(Op)) {
11295 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11296 if (Op->hasOneUse() && CI->hasOneUse()) {
11297 EraseInstFromFunction(FI);
11298 EraseInstFromFunction(*CI);
11299 return EraseInstFromFunction(*cast<Instruction>(Op));
11300 }
11301 } else {
11302 // Op is a call to malloc
11303 if (Op->hasOneUse()) {
11304 EraseInstFromFunction(FI);
11305 return EraseInstFromFunction(*cast<Instruction>(Op));
11306 }
11307 }
11308 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011309
11310 return 0;
11311}
11312
11313
11314/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011315static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011316 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011317 User *CI = cast<User>(LI.getOperand(0));
11318 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011319 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011320
Nick Lewycky291c5942009-05-08 06:47:37 +000011321 if (TD) {
11322 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11323 // Instead of loading constant c string, use corresponding integer value
11324 // directly if string length is small enough.
11325 std::string Str;
11326 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11327 unsigned len = Str.length();
11328 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11329 unsigned numBits = Ty->getPrimitiveSizeInBits();
11330 // Replace LI with immediate integer store.
11331 if ((numBits >> 3) == len + 1) {
11332 APInt StrVal(numBits, 0);
11333 APInt SingleChar(numBits, 0);
11334 if (TD->isLittleEndian()) {
11335 for (signed i = len-1; i >= 0; i--) {
11336 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11337 StrVal = (StrVal << 8) | SingleChar;
11338 }
11339 } else {
11340 for (unsigned i = 0; i < len; i++) {
11341 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11342 StrVal = (StrVal << 8) | SingleChar;
11343 }
11344 // Append NULL at the end.
11345 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011346 StrVal = (StrVal << 8) | SingleChar;
11347 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011348 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011349 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011350 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011351 }
11352 }
11353 }
11354
Mon P Wangbd05ed82009-02-07 22:19:29 +000011355 const PointerType *DestTy = cast<PointerType>(CI->getType());
11356 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011357 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011358
11359 // If the address spaces don't match, don't eliminate the cast.
11360 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11361 return 0;
11362
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011363 const Type *SrcPTy = SrcTy->getElementType();
11364
11365 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11366 isa<VectorType>(DestPTy)) {
11367 // If the source is an array, the code below will not succeed. Check to
11368 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11369 // constants.
11370 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11371 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11372 if (ASrcTy->getNumElements() != 0) {
11373 Value *Idxs[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011374 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Anderson02b48c32009-07-29 18:55:55 +000011375 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011376 SrcTy = cast<PointerType>(CastOp->getType());
11377 SrcPTy = SrcTy->getElementType();
11378 }
11379
Dan Gohmana80e2712009-07-21 23:21:54 +000011380 if (IC.getTargetData() &&
11381 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011382 isa<VectorType>(SrcPTy)) &&
11383 // Do not allow turning this into a load of an integer, which is then
11384 // casted to a pointer, this pessimizes pointer analysis a lot.
11385 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011386 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11387 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011388
11389 // Okay, we are casting from one integer or pointer type to another of
11390 // the same size. Instead of casting the pointer before the load, cast
11391 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011392 Value *NewLoad =
11393 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011394 // Now cast the result of the load.
11395 return new BitCastInst(NewLoad, LI.getType());
11396 }
11397 }
11398 }
11399 return 0;
11400}
11401
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011402Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11403 Value *Op = LI.getOperand(0);
11404
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011405 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011406 if (TD) {
11407 unsigned KnownAlign =
11408 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11409 if (KnownAlign >
11410 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11411 LI.getAlignment()))
11412 LI.setAlignment(KnownAlign);
11413 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011414
Chris Lattnerf3a23592009-08-30 20:36:46 +000011415 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011416 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011417 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011418 return Res;
11419
11420 // None of the following transforms are legal for volatile loads.
11421 if (LI.isVolatile()) return 0;
11422
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011423 // Do really simple store-to-load forwarding and load CSE, to catch cases
11424 // where there are several consequtive memory accesses to the same location,
11425 // separated by a few arithmetic operations.
11426 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011427 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11428 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011429
Christopher Lamb2c175392007-12-29 07:56:53 +000011430 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11431 const Value *GEPI0 = GEPI->getOperand(0);
11432 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011433 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011434 // Insert a new store to null instruction before the load to indicate
11435 // that this code is not reachable. We do this instead of inserting
11436 // an unreachable instruction directly because we cannot modify the
11437 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011438 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011439 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011440 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011441 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011442 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011443
11444 if (Constant *C = dyn_cast<Constant>(Op)) {
11445 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011446 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011447 if (isa<UndefValue>(C) ||
11448 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011449 // Insert a new store to null instruction before the load to indicate that
11450 // this code is not reachable. We do this instead of inserting an
11451 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011452 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011453 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011454 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011455 }
11456
11457 // Instcombine load (constant global) into the value loaded.
11458 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011459 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011460 return ReplaceInstUsesWith(LI, GV->getInitializer());
11461
11462 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011463 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011464 if (CE->getOpcode() == Instruction::GetElementPtr) {
11465 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011466 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011467 if (Constant *V =
Dan Gohmanf49f7b02009-10-05 16:36:26 +000011468 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011469 return ReplaceInstUsesWith(LI, V);
11470 if (CE->getOperand(0)->isNullValue()) {
11471 // Insert a new store to null instruction before the load to indicate
11472 // that this code is not reachable. We do this instead of inserting
11473 // an unreachable instruction directly because we cannot modify the
11474 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011475 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011476 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011477 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011478 }
11479
11480 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011481 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011482 return Res;
11483 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011484 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011485 }
Chris Lattner0270a112007-08-11 18:48:48 +000011486
11487 // If this load comes from anywhere in a constant global, and if the global
11488 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011489 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011490 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011491 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011492 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011493 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011494 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011495 }
11496 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011497
11498 if (Op->hasOneUse()) {
11499 // Change select and PHI nodes to select values instead of addresses: this
11500 // helps alias analysis out a lot, allows many others simplifications, and
11501 // exposes redundancy in the code.
11502 //
11503 // Note that we cannot do the transformation unless we know that the
11504 // introduced loads cannot trap! Something like this is valid as long as
11505 // the condition is always false: load (select bool %C, int* null, int* %G),
11506 // but it would not be valid if we transformed it to load from null
11507 // unconditionally.
11508 //
11509 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11510 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11511 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11512 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011513 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11514 SI->getOperand(1)->getName()+".val");
11515 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11516 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011517 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011518 }
11519
11520 // load (select (cond, null, P)) -> load P
11521 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11522 if (C->isNullValue()) {
11523 LI.setOperand(0, SI->getOperand(2));
11524 return &LI;
11525 }
11526
11527 // load (select (cond, P, null)) -> load P
11528 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11529 if (C->isNullValue()) {
11530 LI.setOperand(0, SI->getOperand(1));
11531 return &LI;
11532 }
11533 }
11534 }
11535 return 0;
11536}
11537
11538/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011539/// when possible. This makes it generally easy to do alias analysis and/or
11540/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011541static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11542 User *CI = cast<User>(SI.getOperand(1));
11543 Value *CastOp = CI->getOperand(0);
11544
11545 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011546 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11547 if (SrcTy == 0) return 0;
11548
11549 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011550
Chris Lattnera032c0e2009-01-16 20:08:59 +000011551 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11552 return 0;
11553
Chris Lattner54dddc72009-01-24 01:00:13 +000011554 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11555 /// to its first element. This allows us to handle things like:
11556 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11557 /// on 32-bit hosts.
11558 SmallVector<Value*, 4> NewGEPIndices;
11559
Chris Lattnera032c0e2009-01-16 20:08:59 +000011560 // If the source is an array, the code below will not succeed. Check to
11561 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11562 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011563 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11564 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011565 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011566 NewGEPIndices.push_back(Zero);
11567
11568 while (1) {
11569 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011570 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011571 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011572 NewGEPIndices.push_back(Zero);
11573 SrcPTy = STy->getElementType(0);
11574 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11575 NewGEPIndices.push_back(Zero);
11576 SrcPTy = ATy->getElementType();
11577 } else {
11578 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011579 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011580 }
11581
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011582 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011583 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011584
11585 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11586 return 0;
11587
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011588 // If the pointers point into different address spaces or if they point to
11589 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011590 if (!IC.getTargetData() ||
11591 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011592 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011593 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11594 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011595 return 0;
11596
11597 // Okay, we are casting from one integer or pointer type to another of
11598 // the same size. Instead of casting the pointer before
11599 // the store, cast the value to be stored.
11600 Value *NewCast;
11601 Value *SIOp0 = SI.getOperand(0);
11602 Instruction::CastOps opcode = Instruction::BitCast;
11603 const Type* CastSrcTy = SIOp0->getType();
11604 const Type* CastDstTy = SrcPTy;
11605 if (isa<PointerType>(CastDstTy)) {
11606 if (CastSrcTy->isInteger())
11607 opcode = Instruction::IntToPtr;
11608 } else if (isa<IntegerType>(CastDstTy)) {
11609 if (isa<PointerType>(SIOp0->getType()))
11610 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011611 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011612
11613 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11614 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011615 if (!NewGEPIndices.empty())
11616 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11617 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000011618
Chris Lattnerad7516a2009-08-30 18:50:58 +000011619 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11620 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000011621 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011622}
11623
Chris Lattner6fd8c802008-11-27 08:56:30 +000011624/// equivalentAddressValues - Test if A and B will obviously have the same
11625/// value. This includes recognizing that %t0 and %t1 will have the same
11626/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011627/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011628/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011629/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011630/// %t2 = load i32* %t1
11631///
11632static bool equivalentAddressValues(Value *A, Value *B) {
11633 // Test if the values are trivially equivalent.
11634 if (A == B) return true;
11635
11636 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011637 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11638 // its only used to compare two uses within the same basic block, which
11639 // means that they'll always either have the same value or one of them
11640 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000011641 if (isa<BinaryOperator>(A) ||
11642 isa<CastInst>(A) ||
11643 isa<PHINode>(A) ||
11644 isa<GetElementPtrInst>(A))
11645 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011646 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000011647 return true;
11648
11649 // Otherwise they may not be equivalent.
11650 return false;
11651}
11652
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011653// If this instruction has two uses, one of which is a llvm.dbg.declare,
11654// return the llvm.dbg.declare.
11655DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11656 if (!V->hasNUses(2))
11657 return 0;
11658 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11659 UI != E; ++UI) {
11660 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11661 return DI;
11662 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11663 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11664 return DI;
11665 }
11666 }
11667 return 0;
11668}
11669
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011670Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11671 Value *Val = SI.getOperand(0);
11672 Value *Ptr = SI.getOperand(1);
11673
11674 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11675 EraseInstFromFunction(SI);
11676 ++NumCombined;
11677 return 0;
11678 }
11679
11680 // If the RHS is an alloca with a single use, zapify the store, making the
11681 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011682 // If the RHS is an alloca with a two uses, the other one being a
11683 // llvm.dbg.declare, zapify the store and the declare, making the
11684 // alloca dead. We must do this to prevent declare's from affecting
11685 // codegen.
11686 if (!SI.isVolatile()) {
11687 if (Ptr->hasOneUse()) {
11688 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011689 EraseInstFromFunction(SI);
11690 ++NumCombined;
11691 return 0;
11692 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011693 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11694 if (isa<AllocaInst>(GEP->getOperand(0))) {
11695 if (GEP->getOperand(0)->hasOneUse()) {
11696 EraseInstFromFunction(SI);
11697 ++NumCombined;
11698 return 0;
11699 }
11700 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11701 EraseInstFromFunction(*DI);
11702 EraseInstFromFunction(SI);
11703 ++NumCombined;
11704 return 0;
11705 }
11706 }
11707 }
11708 }
11709 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11710 EraseInstFromFunction(*DI);
11711 EraseInstFromFunction(SI);
11712 ++NumCombined;
11713 return 0;
11714 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011715 }
11716
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011717 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011718 if (TD) {
11719 unsigned KnownAlign =
11720 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11721 if (KnownAlign >
11722 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11723 SI.getAlignment()))
11724 SI.setAlignment(KnownAlign);
11725 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011726
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011727 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011728 // stores to the same location, separated by a few arithmetic operations. This
11729 // situation often occurs with bitfield accesses.
11730 BasicBlock::iterator BBI = &SI;
11731 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11732 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011733 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011734 // Don't count debug info directives, lest they affect codegen,
11735 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11736 // It is necessary for correctness to skip those that feed into a
11737 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011738 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011739 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011740 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011741 continue;
11742 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011743
11744 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11745 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011746 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11747 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011748 ++NumDeadStore;
11749 ++BBI;
11750 EraseInstFromFunction(*PrevSI);
11751 continue;
11752 }
11753 break;
11754 }
11755
11756 // If this is a load, we have to stop. However, if the loaded value is from
11757 // the pointer we're loading and is producing the pointer we're storing,
11758 // then *this* store is dead (X = load P; store X -> P).
11759 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011760 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11761 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011762 EraseInstFromFunction(SI);
11763 ++NumCombined;
11764 return 0;
11765 }
11766 // Otherwise, this is a load from some other location. Stores before it
11767 // may not be dead.
11768 break;
11769 }
11770
11771 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011772 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011773 break;
11774 }
11775
11776
11777 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11778
11779 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000011780 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011781 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011782 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011783 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000011784 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011785 ++NumCombined;
11786 }
11787 return 0; // Do not modify these!
11788 }
11789
11790 // store undef, Ptr -> noop
11791 if (isa<UndefValue>(Val)) {
11792 EraseInstFromFunction(SI);
11793 ++NumCombined;
11794 return 0;
11795 }
11796
11797 // If the pointer destination is a cast, see if we can fold the cast into the
11798 // source instead.
11799 if (isa<CastInst>(Ptr))
11800 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11801 return Res;
11802 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11803 if (CE->isCast())
11804 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11805 return Res;
11806
11807
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011808 // If this store is the last instruction in the basic block (possibly
11809 // excepting debug info instructions and the pointer bitcasts that feed
11810 // into them), and if the block ends with an unconditional branch, try
11811 // to move it to the successor block.
11812 BBI = &SI;
11813 do {
11814 ++BBI;
11815 } while (isa<DbgInfoIntrinsic>(BBI) ||
11816 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011817 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11818 if (BI->isUnconditional())
11819 if (SimplifyStoreAtEndOfBlock(SI))
11820 return 0; // xform done!
11821
11822 return 0;
11823}
11824
11825/// SimplifyStoreAtEndOfBlock - Turn things like:
11826/// if () { *P = v1; } else { *P = v2 }
11827/// into a phi node with a store in the successor.
11828///
11829/// Simplify things like:
11830/// *P = v1; if () { *P = v2; }
11831/// into a phi node with a store in the successor.
11832///
11833bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11834 BasicBlock *StoreBB = SI.getParent();
11835
11836 // Check to see if the successor block has exactly two incoming edges. If
11837 // so, see if the other predecessor contains a store to the same location.
11838 // if so, insert a PHI node (if needed) and move the stores down.
11839 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11840
11841 // Determine whether Dest has exactly two predecessors and, if so, compute
11842 // the other predecessor.
11843 pred_iterator PI = pred_begin(DestBB);
11844 BasicBlock *OtherBB = 0;
11845 if (*PI != StoreBB)
11846 OtherBB = *PI;
11847 ++PI;
11848 if (PI == pred_end(DestBB))
11849 return false;
11850
11851 if (*PI != StoreBB) {
11852 if (OtherBB)
11853 return false;
11854 OtherBB = *PI;
11855 }
11856 if (++PI != pred_end(DestBB))
11857 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011858
11859 // Bail out if all the relevant blocks aren't distinct (this can happen,
11860 // for example, if SI is in an infinite loop)
11861 if (StoreBB == DestBB || OtherBB == DestBB)
11862 return false;
11863
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011864 // Verify that the other block ends in a branch and is not otherwise empty.
11865 BasicBlock::iterator BBI = OtherBB->getTerminator();
11866 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11867 if (!OtherBr || BBI == OtherBB->begin())
11868 return false;
11869
11870 // If the other block ends in an unconditional branch, check for the 'if then
11871 // else' case. there is an instruction before the branch.
11872 StoreInst *OtherStore = 0;
11873 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011874 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011875 // Skip over debugging info.
11876 while (isa<DbgInfoIntrinsic>(BBI) ||
11877 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11878 if (BBI==OtherBB->begin())
11879 return false;
11880 --BBI;
11881 }
11882 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011883 OtherStore = dyn_cast<StoreInst>(BBI);
11884 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11885 return false;
11886 } else {
11887 // Otherwise, the other block ended with a conditional branch. If one of the
11888 // destinations is StoreBB, then we have the if/then case.
11889 if (OtherBr->getSuccessor(0) != StoreBB &&
11890 OtherBr->getSuccessor(1) != StoreBB)
11891 return false;
11892
11893 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11894 // if/then triangle. See if there is a store to the same ptr as SI that
11895 // lives in OtherBB.
11896 for (;; --BBI) {
11897 // Check to see if we find the matching store.
11898 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11899 if (OtherStore->getOperand(1) != SI.getOperand(1))
11900 return false;
11901 break;
11902 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011903 // If we find something that may be using or overwriting the stored
11904 // value, or if we run out of instructions, we can't do the xform.
11905 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011906 BBI == OtherBB->begin())
11907 return false;
11908 }
11909
11910 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011911 // make sure nothing reads or overwrites the stored value in
11912 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011913 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11914 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011915 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011916 return false;
11917 }
11918 }
11919
11920 // Insert a PHI node now if we need it.
11921 Value *MergedVal = OtherStore->getOperand(0);
11922 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011923 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011924 PN->reserveOperandSpace(2);
11925 PN->addIncoming(SI.getOperand(0), SI.getParent());
11926 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11927 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11928 }
11929
11930 // Advance to a place where it is safe to insert the new store and
11931 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011932 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011933 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11934 OtherStore->isVolatile()), *BBI);
11935
11936 // Nuke the old stores.
11937 EraseInstFromFunction(SI);
11938 EraseInstFromFunction(*OtherStore);
11939 ++NumCombined;
11940 return true;
11941}
11942
11943
11944Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11945 // Change br (not X), label True, label False to: br X, label False, True
11946 Value *X = 0;
11947 BasicBlock *TrueDest;
11948 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000011949 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011950 !isa<Constant>(X)) {
11951 // Swap Destinations and condition...
11952 BI.setCondition(X);
11953 BI.setSuccessor(0, FalseDest);
11954 BI.setSuccessor(1, TrueDest);
11955 return &BI;
11956 }
11957
11958 // Cannonicalize fcmp_one -> fcmp_oeq
11959 FCmpInst::Predicate FPred; Value *Y;
11960 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011961 TrueDest, FalseDest)) &&
11962 BI.getCondition()->hasOneUse())
11963 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11964 FPred == FCmpInst::FCMP_OGE) {
11965 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11966 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11967
11968 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011969 BI.setSuccessor(0, FalseDest);
11970 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011971 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011972 return &BI;
11973 }
11974
11975 // Cannonicalize icmp_ne -> icmp_eq
11976 ICmpInst::Predicate IPred;
11977 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011978 TrueDest, FalseDest)) &&
11979 BI.getCondition()->hasOneUse())
11980 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11981 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11982 IPred == ICmpInst::ICMP_SGE) {
11983 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11984 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11985 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011986 BI.setSuccessor(0, FalseDest);
11987 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011988 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011989 return &BI;
11990 }
11991
11992 return 0;
11993}
11994
11995Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11996 Value *Cond = SI.getCondition();
11997 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11998 if (I->getOpcode() == Instruction::Add)
11999 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12000 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12001 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012002 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012003 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012004 AddRHS));
12005 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012006 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012007 return &SI;
12008 }
12009 }
12010 return 0;
12011}
12012
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012013Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012014 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012015
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012016 if (!EV.hasIndices())
12017 return ReplaceInstUsesWith(EV, Agg);
12018
12019 if (Constant *C = dyn_cast<Constant>(Agg)) {
12020 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012021 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012022
12023 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012024 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012025
12026 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12027 // Extract the element indexed by the first index out of the constant
12028 Value *V = C->getOperand(*EV.idx_begin());
12029 if (EV.getNumIndices() > 1)
12030 // Extract the remaining indices out of the constant indexed by the
12031 // first index
12032 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12033 else
12034 return ReplaceInstUsesWith(EV, V);
12035 }
12036 return 0; // Can't handle other constants
12037 }
12038 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12039 // We're extracting from an insertvalue instruction, compare the indices
12040 const unsigned *exti, *exte, *insi, *inse;
12041 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12042 exte = EV.idx_end(), inse = IV->idx_end();
12043 exti != exte && insi != inse;
12044 ++exti, ++insi) {
12045 if (*insi != *exti)
12046 // The insert and extract both reference distinctly different elements.
12047 // This means the extract is not influenced by the insert, and we can
12048 // replace the aggregate operand of the extract with the aggregate
12049 // operand of the insert. i.e., replace
12050 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12051 // %E = extractvalue { i32, { i32 } } %I, 0
12052 // with
12053 // %E = extractvalue { i32, { i32 } } %A, 0
12054 return ExtractValueInst::Create(IV->getAggregateOperand(),
12055 EV.idx_begin(), EV.idx_end());
12056 }
12057 if (exti == exte && insi == inse)
12058 // Both iterators are at the end: Index lists are identical. Replace
12059 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12060 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12061 // with "i32 42"
12062 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12063 if (exti == exte) {
12064 // The extract list is a prefix of the insert list. i.e. replace
12065 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12066 // %E = extractvalue { i32, { i32 } } %I, 1
12067 // with
12068 // %X = extractvalue { i32, { i32 } } %A, 1
12069 // %E = insertvalue { i32 } %X, i32 42, 0
12070 // by switching the order of the insert and extract (though the
12071 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012072 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12073 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012074 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12075 insi, inse);
12076 }
12077 if (insi == inse)
12078 // The insert list is a prefix of the extract list
12079 // We can simply remove the common indices from the extract and make it
12080 // operate on the inserted value instead of the insertvalue result.
12081 // i.e., replace
12082 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12083 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12084 // with
12085 // %E extractvalue { i32 } { i32 42 }, 0
12086 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12087 exti, exte);
12088 }
12089 // Can't simplify extracts from other values. Note that nested extracts are
12090 // already simplified implicitely by the above (extract ( extract (insert) )
12091 // will be translated into extract ( insert ( extract ) ) first and then just
12092 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012093 return 0;
12094}
12095
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012096/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12097/// is to leave as a vector operation.
12098static bool CheapToScalarize(Value *V, bool isConstant) {
12099 if (isa<ConstantAggregateZero>(V))
12100 return true;
12101 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12102 if (isConstant) return true;
12103 // If all elts are the same, we can extract.
12104 Constant *Op0 = C->getOperand(0);
12105 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12106 if (C->getOperand(i) != Op0)
12107 return false;
12108 return true;
12109 }
12110 Instruction *I = dyn_cast<Instruction>(V);
12111 if (!I) return false;
12112
12113 // Insert element gets simplified to the inserted element or is deleted if
12114 // this is constant idx extract element and its a constant idx insertelt.
12115 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12116 isa<ConstantInt>(I->getOperand(2)))
12117 return true;
12118 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12119 return true;
12120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12121 if (BO->hasOneUse() &&
12122 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12123 CheapToScalarize(BO->getOperand(1), isConstant)))
12124 return true;
12125 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12126 if (CI->hasOneUse() &&
12127 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12128 CheapToScalarize(CI->getOperand(1), isConstant)))
12129 return true;
12130
12131 return false;
12132}
12133
12134/// Read and decode a shufflevector mask.
12135///
12136/// It turns undef elements into values that are larger than the number of
12137/// elements in the input.
12138static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12139 unsigned NElts = SVI->getType()->getNumElements();
12140 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12141 return std::vector<unsigned>(NElts, 0);
12142 if (isa<UndefValue>(SVI->getOperand(2)))
12143 return std::vector<unsigned>(NElts, 2*NElts);
12144
12145 std::vector<unsigned> Result;
12146 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012147 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12148 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012149 Result.push_back(NElts*2); // undef -> 8
12150 else
Gabor Greif17396002008-06-12 21:37:33 +000012151 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012152 return Result;
12153}
12154
12155/// FindScalarElement - Given a vector and an element number, see if the scalar
12156/// value is already around as a register, for example if it were inserted then
12157/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012158static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012159 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012160 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12161 const VectorType *PTy = cast<VectorType>(V->getType());
12162 unsigned Width = PTy->getNumElements();
12163 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012164 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012165
12166 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012167 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012168 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012169 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012170 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12171 return CP->getOperand(EltNo);
12172 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12173 // If this is an insert to a variable element, we don't know what it is.
12174 if (!isa<ConstantInt>(III->getOperand(2)))
12175 return 0;
12176 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12177
12178 // If this is an insert to the element we are looking for, return the
12179 // inserted value.
12180 if (EltNo == IIElt)
12181 return III->getOperand(1);
12182
12183 // Otherwise, the insertelement doesn't modify the value, recurse on its
12184 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012185 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012186 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012187 unsigned LHSWidth =
12188 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012189 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012190 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012191 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012192 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012193 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012194 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012195 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012196 }
12197
12198 // Otherwise, we don't know.
12199 return 0;
12200}
12201
12202Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012203 // If vector val is undef, replace extract with scalar undef.
12204 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012205 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012206
12207 // If vector val is constant 0, replace extract with scalar 0.
12208 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012209 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012210
12211 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012212 // If vector val is constant with all elements the same, replace EI with
12213 // that element. When the elements are not identical, we cannot replace yet
12214 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012215 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012216 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012217 if (C->getOperand(i) != op0) {
12218 op0 = 0;
12219 break;
12220 }
12221 if (op0)
12222 return ReplaceInstUsesWith(EI, op0);
12223 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012224
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012225 // If extracting a specified index from the vector, see if we can recursively
12226 // find a previously computed scalar that was inserted into the vector.
12227 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12228 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012229 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012230
12231 // If this is extracting an invalid index, turn this into undef, to avoid
12232 // crashing the code below.
12233 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012234 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012235
12236 // This instruction only demands the single element from the input vector.
12237 // If the input vector has a single use, simplify it based on this use
12238 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012239 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012240 APInt UndefElts(VectorWidth, 0);
12241 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012242 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012243 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012244 EI.setOperand(0, V);
12245 return &EI;
12246 }
12247 }
12248
Owen Anderson24be4c12009-07-03 00:17:18 +000012249 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012250 return ReplaceInstUsesWith(EI, Elt);
12251
12252 // If the this extractelement is directly using a bitcast from a vector of
12253 // the same number of elements, see if we can find the source element from
12254 // it. In this case, we will end up needing to bitcast the scalars.
12255 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12256 if (const VectorType *VT =
12257 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12258 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012259 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12260 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012261 return new BitCastInst(Elt, EI.getType());
12262 }
12263 }
12264
12265 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012266 // Push extractelement into predecessor operation if legal and
12267 // profitable to do so
12268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12269 if (I->hasOneUse() &&
12270 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12271 Value *newEI0 =
12272 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12273 EI.getName()+".lhs");
12274 Value *newEI1 =
12275 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12276 EI.getName()+".rhs");
12277 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012278 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012279 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012280 // Extracting the inserted element?
12281 if (IE->getOperand(2) == EI.getOperand(1))
12282 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12283 // If the inserted and extracted elements are constants, they must not
12284 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012285 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012286 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012287 EI.setOperand(0, IE->getOperand(0));
12288 return &EI;
12289 }
12290 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12291 // If this is extracting an element from a shufflevector, figure out where
12292 // it came from and extract from the appropriate input element instead.
12293 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12294 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12295 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012296 unsigned LHSWidth =
12297 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12298
12299 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012300 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012301 else if (SrcIdx < LHSWidth*2) {
12302 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012303 Src = SVI->getOperand(1);
12304 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012305 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012306 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012307 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012308 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12309 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012310 }
12311 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012312 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012313 }
12314 return 0;
12315}
12316
12317/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12318/// elements from either LHS or RHS, return the shuffle mask and true.
12319/// Otherwise, return false.
12320static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012321 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012322 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012323 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12324 "Invalid CollectSingleShuffleElements");
12325 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12326
12327 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012328 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012329 return true;
12330 } else if (V == LHS) {
12331 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012332 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012333 return true;
12334 } else if (V == RHS) {
12335 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012336 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012337 return true;
12338 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12339 // If this is an insert of an extract from some other vector, include it.
12340 Value *VecOp = IEI->getOperand(0);
12341 Value *ScalarOp = IEI->getOperand(1);
12342 Value *IdxOp = IEI->getOperand(2);
12343
12344 if (!isa<ConstantInt>(IdxOp))
12345 return false;
12346 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12347
12348 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12349 // Okay, we can handle this if the vector we are insertinting into is
12350 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012351 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012352 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012353 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012354 return true;
12355 }
12356 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12357 if (isa<ConstantInt>(EI->getOperand(1)) &&
12358 EI->getOperand(0)->getType() == V->getType()) {
12359 unsigned ExtractedIdx =
12360 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12361
12362 // This must be extracting from either LHS or RHS.
12363 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12364 // Okay, we can handle this if the vector we are insertinting into is
12365 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012366 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012367 // If so, update the mask to reflect the inserted value.
12368 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012369 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012370 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012371 } else {
12372 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012373 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012374 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012375
12376 }
12377 return true;
12378 }
12379 }
12380 }
12381 }
12382 }
12383 // TODO: Handle shufflevector here!
12384
12385 return false;
12386}
12387
12388/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12389/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12390/// that computes V and the LHS value of the shuffle.
12391static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012392 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012393 assert(isa<VectorType>(V->getType()) &&
12394 (RHS == 0 || V->getType() == RHS->getType()) &&
12395 "Invalid shuffle!");
12396 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12397
12398 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012399 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012400 return V;
12401 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012402 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012403 return V;
12404 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12405 // If this is an insert of an extract from some other vector, include it.
12406 Value *VecOp = IEI->getOperand(0);
12407 Value *ScalarOp = IEI->getOperand(1);
12408 Value *IdxOp = IEI->getOperand(2);
12409
12410 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12411 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12412 EI->getOperand(0)->getType() == V->getType()) {
12413 unsigned ExtractedIdx =
12414 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12415 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12416
12417 // Either the extracted from or inserted into vector must be RHSVec,
12418 // otherwise we'd end up with a shuffle of three inputs.
12419 if (EI->getOperand(0) == RHS || RHS == 0) {
12420 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012421 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012422 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012423 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012424 return V;
12425 }
12426
12427 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012428 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12429 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012430 // Everything but the extracted element is replaced with the RHS.
12431 for (unsigned i = 0; i != NumElts; ++i) {
12432 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012433 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012434 }
12435 return V;
12436 }
12437
12438 // If this insertelement is a chain that comes from exactly these two
12439 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012440 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12441 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012442 return EI->getOperand(0);
12443
12444 }
12445 }
12446 }
12447 // TODO: Handle shufflevector here!
12448
12449 // Otherwise, can't do anything fancy. Return an identity vector.
12450 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012451 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012452 return V;
12453}
12454
12455Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12456 Value *VecOp = IE.getOperand(0);
12457 Value *ScalarOp = IE.getOperand(1);
12458 Value *IdxOp = IE.getOperand(2);
12459
12460 // Inserting an undef or into an undefined place, remove this.
12461 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12462 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012463
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012464 // If the inserted element was extracted from some other vector, and if the
12465 // indexes are constant, try to turn this into a shufflevector operation.
12466 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12467 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12468 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012469 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012470 unsigned ExtractedIdx =
12471 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12472 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12473
12474 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12475 return ReplaceInstUsesWith(IE, VecOp);
12476
12477 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012478 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012479
12480 // If we are extracting a value from a vector, then inserting it right
12481 // back into the same place, just use the input vector.
12482 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12483 return ReplaceInstUsesWith(IE, VecOp);
12484
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012485 // If this insertelement isn't used by some other insertelement, turn it
12486 // (and any insertelements it points to), into one big shuffle.
12487 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12488 std::vector<Constant*> Mask;
12489 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012490 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012491 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012492 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012493 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012494 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012495 }
12496 }
12497 }
12498
Eli Friedmanbefee262009-06-06 20:08:03 +000012499 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12500 APInt UndefElts(VWidth, 0);
12501 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12502 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12503 return &IE;
12504
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012505 return 0;
12506}
12507
12508
12509Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12510 Value *LHS = SVI.getOperand(0);
12511 Value *RHS = SVI.getOperand(1);
12512 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12513
12514 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012515
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012516 // Undefined shuffle mask -> undefined value.
12517 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012518 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012519
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012520 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012521
12522 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12523 return 0;
12524
Evan Cheng63295ab2009-02-03 10:05:09 +000012525 APInt UndefElts(VWidth, 0);
12526 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12527 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012528 LHS = SVI.getOperand(0);
12529 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012530 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012532
12533 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12534 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12535 if (LHS == RHS || isa<UndefValue>(LHS)) {
12536 if (isa<UndefValue>(LHS) && LHS == RHS) {
12537 // shuffle(undef,undef,mask) -> undef.
12538 return ReplaceInstUsesWith(SVI, LHS);
12539 }
12540
12541 // Remap any references to RHS to use LHS.
12542 std::vector<Constant*> Elts;
12543 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12544 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012545 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012546 else {
12547 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012548 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012549 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012550 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012551 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012552 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012553 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012554 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012555 }
12556 }
12557 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012558 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012559 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012560 LHS = SVI.getOperand(0);
12561 RHS = SVI.getOperand(1);
12562 MadeChange = true;
12563 }
12564
12565 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12566 bool isLHSID = true, isRHSID = true;
12567
12568 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12569 if (Mask[i] >= e*2) continue; // Ignore undef values.
12570 // Is this an identity shuffle of the LHS value?
12571 isLHSID &= (Mask[i] == i);
12572
12573 // Is this an identity shuffle of the RHS value?
12574 isRHSID &= (Mask[i]-e == i);
12575 }
12576
12577 // Eliminate identity shuffles.
12578 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12579 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12580
12581 // If the LHS is a shufflevector itself, see if we can combine it with this
12582 // one without producing an unusual shuffle. Here we are really conservative:
12583 // we are absolutely afraid of producing a shuffle mask not in the input
12584 // program, because the code gen may not be smart enough to turn a merged
12585 // shuffle into two specific shuffles: it may produce worse code. As such,
12586 // we only merge two shuffles if the result is one of the two input shuffle
12587 // masks. In this case, merging the shuffles just removes one instruction,
12588 // which we know is safe. This is good for things like turning:
12589 // (splat(splat)) -> splat.
12590 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12591 if (isa<UndefValue>(RHS)) {
12592 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12593
12594 std::vector<unsigned> NewMask;
12595 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12596 if (Mask[i] >= 2*e)
12597 NewMask.push_back(2*e);
12598 else
12599 NewMask.push_back(LHSMask[Mask[i]]);
12600
12601 // If the result mask is equal to the src shuffle or this shuffle mask, do
12602 // the replacement.
12603 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012604 unsigned LHSInNElts =
12605 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012606 std::vector<Constant*> Elts;
12607 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012608 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000012609 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012610 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000012611 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012612 }
12613 }
12614 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12615 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012616 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012617 }
12618 }
12619 }
12620
12621 return MadeChange ? &SVI : 0;
12622}
12623
12624
12625
12626
12627/// TryToSinkInstruction - Try to move the specified instruction from its
12628/// current block into the beginning of DestBlock, which can only happen if it's
12629/// safe to move the instruction past all of the instructions between it and the
12630/// end of its block.
12631static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12632 assert(I->hasOneUse() && "Invariants didn't hold!");
12633
12634 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012635 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012636 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012637
12638 // Do not sink alloca instructions out of the entry block.
12639 if (isa<AllocaInst>(I) && I->getParent() ==
12640 &DestBlock->getParent()->getEntryBlock())
12641 return false;
12642
12643 // We can only sink load instructions if there is nothing between the load and
12644 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012645 if (I->mayReadFromMemory()) {
12646 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012647 Scan != E; ++Scan)
12648 if (Scan->mayWriteToMemory())
12649 return false;
12650 }
12651
Dan Gohman514277c2008-05-23 21:05:58 +000012652 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012653
Dale Johannesen24339f12009-03-03 01:09:07 +000012654 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012655 I->moveBefore(InsertPos);
12656 ++NumSunkInst;
12657 return true;
12658}
12659
12660
12661/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12662/// all reachable code to the worklist.
12663///
12664/// This has a couple of tricks to make the code faster and more powerful. In
12665/// particular, we constant fold and DCE instructions as we go, to avoid adding
12666/// them to the worklist (this significantly speeds up instcombine on code where
12667/// many instructions are dead or constant). Additionally, if we find a branch
12668/// whose condition is a known constant, we only visit the reachable successors.
12669///
Chris Lattnerc4269e52009-10-15 04:59:28 +000012670static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012671 SmallPtrSet<BasicBlock*, 64> &Visited,
12672 InstCombiner &IC,
12673 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000012674 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000012675 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012676 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000012677
12678 std::vector<Instruction*> InstrsForInstCombineWorklist;
12679 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012680
Chris Lattnerc4269e52009-10-15 04:59:28 +000012681 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12682
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012683 while (!Worklist.empty()) {
12684 BB = Worklist.back();
12685 Worklist.pop_back();
12686
12687 // We have now visited this block! If we've already been here, ignore it.
12688 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012689
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012690 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12691 Instruction *Inst = BBI++;
12692
12693 // DCE instruction if trivially dead.
12694 if (isInstructionTriviallyDead(Inst)) {
12695 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000012696 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012697 Inst->eraseFromParent();
12698 continue;
12699 }
12700
12701 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000012702 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12703 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12704 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12705 << *Inst << '\n');
12706 Inst->replaceAllUsesWith(C);
12707 ++NumConstProp;
12708 Inst->eraseFromParent();
12709 continue;
12710 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000012711
12712
12713
12714 if (TD) {
12715 // See if we can constant fold its operands.
12716 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12717 i != e; ++i) {
12718 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12719 if (CE == 0) continue;
12720
12721 // If we already folded this constant, don't try again.
12722 if (!FoldedConstants.insert(CE))
12723 continue;
12724
12725 Constant *NewC =
12726 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12727 if (NewC && NewC != CE) {
12728 *i = NewC;
12729 MadeIRChange = true;
12730 }
12731 }
12732 }
12733
Devang Patel794140c2008-11-19 18:56:50 +000012734
Chris Lattnerb5663c72009-10-12 03:58:40 +000012735 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012736 }
12737
12738 // Recursively visit successors. If this is a branch or switch on a
12739 // constant, only visit the reachable successor.
12740 TerminatorInst *TI = BB->getTerminator();
12741 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12742 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12743 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012744 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012745 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012746 continue;
12747 }
12748 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12749 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12750 // See if this is an explicit destination.
12751 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12752 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012753 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012754 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012755 continue;
12756 }
12757
12758 // Otherwise it is the default destination.
12759 Worklist.push_back(SI->getSuccessor(0));
12760 continue;
12761 }
12762 }
12763
12764 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12765 Worklist.push_back(TI->getSuccessor(i));
12766 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000012767
12768 // Once we've found all of the instructions to add to instcombine's worklist,
12769 // add them in reverse order. This way instcombine will visit from the top
12770 // of the function down. This jives well with the way that it adds all uses
12771 // of instructions to the worklist after doing a transformation, thus avoiding
12772 // some N^2 behavior in pathological cases.
12773 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12774 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000012775
12776 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012777}
12778
12779bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000012780 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012781
Daniel Dunbar005975c2009-07-25 00:23:56 +000012782 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12783 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012784
12785 {
12786 // Do a depth-first traversal of the function, populate the worklist with
12787 // the reachable instructions. Ignore blocks that are not reachable. Keep
12788 // track of which blocks we visit.
12789 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000012790 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012791
12792 // Do a quick scan over the function. If we find any blocks that are
12793 // unreachable, remove any instructions inside of them. This prevents
12794 // the instcombine code from having to deal with some bad special cases.
12795 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12796 if (!Visited.count(BB)) {
12797 Instruction *Term = BB->getTerminator();
12798 while (Term != BB->begin()) { // Remove instrs bottom-up
12799 BasicBlock::iterator I = Term; --I;
12800
Chris Lattner8a6411c2009-08-23 04:37:46 +000012801 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000012802 // A debug intrinsic shouldn't force another iteration if we weren't
12803 // going to do one without it.
12804 if (!isa<DbgInfoIntrinsic>(I)) {
12805 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012806 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000012807 }
Devang Patele3829c82009-10-13 22:56:32 +000012808
Devang Patele3829c82009-10-13 22:56:32 +000012809 // If I is not void type then replaceAllUsesWith undef.
12810 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000012811 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000012812 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012813 I->eraseFromParent();
12814 }
12815 }
12816 }
12817
Chris Lattner5119c702009-08-30 05:55:36 +000012818 while (!Worklist.isEmpty()) {
12819 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012820 if (I == 0) continue; // skip null values.
12821
12822 // Check to see if we can DCE the instruction.
12823 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012824 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000012825 EraseInstFromFunction(*I);
12826 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012827 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012828 continue;
12829 }
12830
12831 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000012832 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12833 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12834 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012835
Chris Lattneree5839b2009-10-15 04:13:44 +000012836 // Add operands to the worklist.
12837 ReplaceInstUsesWith(*I, C);
12838 ++NumConstProp;
12839 EraseInstFromFunction(*I);
12840 MadeIRChange = true;
12841 continue;
12842 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012843
12844 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012845 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012846 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000012847 Instruction *UserInst = cast<Instruction>(I->use_back());
12848 BasicBlock *UserParent;
12849
12850 // Get the block the use occurs in.
12851 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12852 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12853 else
12854 UserParent = UserInst->getParent();
12855
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012856 if (UserParent != BB) {
12857 bool UserIsSuccessor = false;
12858 // See if the user is one of our successors.
12859 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12860 if (*SI == UserParent) {
12861 UserIsSuccessor = true;
12862 break;
12863 }
12864
12865 // If the user is one of our immediate successors, and if that successor
12866 // only has us as a predecessors (we'd have to split the critical edge
12867 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000012868 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012869 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000012870 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012871 }
12872 }
12873
Chris Lattnerc7694852009-08-30 07:44:24 +000012874 // Now that we have an instruction, try combining it to simplify it.
12875 Builder->SetInsertPoint(I->getParent(), I);
12876
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012877#ifndef NDEBUG
12878 std::string OrigI;
12879#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000012880 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000012881 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12882
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012883 if (Instruction *Result = visit(*I)) {
12884 ++NumCombined;
12885 // Should we replace the old instruction with a new one?
12886 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012887 DEBUG(errs() << "IC: Old = " << *I << '\n'
12888 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012889
12890 // Everything uses the new instruction now.
12891 I->replaceAllUsesWith(Result);
12892
12893 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000012894 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000012895 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012896
12897 // Move the name to the new instruction first.
12898 Result->takeName(I);
12899
12900 // Insert the new instruction into the basic block...
12901 BasicBlock *InstParent = I->getParent();
12902 BasicBlock::iterator InsertPos = I;
12903
12904 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12905 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12906 ++InsertPos;
12907
12908 InstParent->getInstList().insert(InsertPos, Result);
12909
Chris Lattner3183fb62009-08-30 06:13:40 +000012910 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012911 } else {
12912#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000012913 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12914 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012915#endif
12916
12917 // If the instruction was modified, it's possible that it is now dead.
12918 // if so, remove it.
12919 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012920 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012921 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000012922 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000012923 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012924 }
12925 }
Chris Lattner21d79e22009-08-31 06:57:37 +000012926 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012927 }
12928 }
12929
Chris Lattner5119c702009-08-30 05:55:36 +000012930 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000012931 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012932}
12933
12934
12935bool InstCombiner::runOnFunction(Function &F) {
12936 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000012937 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000012938 TD = getAnalysisIfAvailable<TargetData>();
12939
Chris Lattnerc7694852009-08-30 07:44:24 +000012940
12941 /// Builder - This is an IRBuilder that automatically inserts new
12942 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000012943 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12944 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattnerc7694852009-08-30 07:44:24 +000012945 InstCombineIRInserter(Worklist));
12946 Builder = &TheBuilder;
12947
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012948 bool EverMadeChange = false;
12949
12950 // Iterate while there is work to do.
12951 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012952 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012953 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000012954
12955 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012956 return EverMadeChange;
12957}
12958
12959FunctionPass *llvm::createInstructionCombiningPass() {
12960 return new InstCombiner();
12961}