blob: 6c5a16c361559c3438a3dda85eaecb36a5dfc614 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera9333562009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
51#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
56#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058#include "llvm/Support/MathExtras.h"
59#include "llvm/Support/PatternMatch.h"
Chris Lattneree5839b2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include "llvm/ADT/DenseMap.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/STLExtras.h"
67#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000068#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069using namespace llvm;
70using namespace llvm::PatternMatch;
71
72STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
77
Chris Lattner78500cb2009-12-21 06:03:05 +000078/// SelectPatternFlavor - We can match a variety of different patterns for
79/// select operations.
80enum SelectPatternFlavor {
81 SPF_UNKNOWN = 0,
82 SPF_SMIN, SPF_UMIN,
83 SPF_SMAX, SPF_UMAX
84 //SPF_ABS - TODO.
85};
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000088 /// InstCombineWorklist - This is the worklist management logic for
89 /// InstCombine.
90 class InstCombineWorklist {
91 SmallVector<Instruction*, 256> Worklist;
92 DenseMap<Instruction*, unsigned> WorklistMap;
93
94 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
95 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96 public:
97 InstCombineWorklist() {}
98
99 bool isEmpty() const { return Worklist.empty(); }
100
101 /// Add - Add the specified instruction to the worklist if it isn't already
102 /// in it.
103 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +0000104 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +0000106 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +0000107 }
Chris Lattner5119c702009-08-30 05:55:36 +0000108 }
109
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000110 void AddValue(Value *V) {
111 if (Instruction *I = dyn_cast<Instruction>(V))
112 Add(I);
113 }
114
Chris Lattnerb5663c72009-10-12 03:58:40 +0000115 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116 /// which should only be done when the worklist is empty and when the group
117 /// has no duplicates.
118 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119 assert(Worklist.empty() && "Worklist must be empty to add initial group");
120 Worklist.reserve(NumEntries+16);
121 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122 for (; NumEntries; --NumEntries) {
123 Instruction *I = List[NumEntries-1];
124 WorklistMap.insert(std::make_pair(I, Worklist.size()));
125 Worklist.push_back(I);
126 }
127 }
128
Chris Lattner3183fb62009-08-30 06:13:40 +0000129 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000130 void Remove(Instruction *I) {
131 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132 if (It == WorklistMap.end()) return; // Not in worklist.
133
134 // Don't bother moving everything down, just null out the slot.
135 Worklist[It->second] = 0;
136
137 WorklistMap.erase(It);
138 }
139
140 Instruction *RemoveOne() {
141 Instruction *I = Worklist.back();
142 Worklist.pop_back();
143 WorklistMap.erase(I);
144 return I;
145 }
146
Chris Lattner4796b622009-08-30 06:22:51 +0000147 /// AddUsersToWorkList - When an instruction is simplified, add all users of
148 /// the instruction to the work lists because they might get more simplified
149 /// now.
150 ///
151 void AddUsersToWorkList(Instruction &I) {
152 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153 UI != UE; ++UI)
154 Add(cast<Instruction>(*UI));
155 }
156
Chris Lattner5119c702009-08-30 05:55:36 +0000157
158 /// Zap - check that the worklist is empty and nuke the backing store for
159 /// the map if it is large.
160 void Zap() {
161 assert(WorklistMap.empty() && "Worklist empty, but map not?");
162
163 // Do an explicit clear, this shrinks the map if needed.
164 WorklistMap.clear();
165 }
166 };
167} // end anonymous namespace.
168
169
170namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000171 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172 /// just like the normal insertion helper, but also adds any new instructions
173 /// to the instcombine worklist.
174 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175 InstCombineWorklist &Worklist;
176 public:
177 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178
179 void InsertHelper(Instruction *I, const Twine &Name,
180 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182 Worklist.Add(I);
183 }
184 };
185} // end anonymous namespace
186
187
188namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000189 class InstCombiner : public FunctionPass,
190 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 TargetData *TD;
192 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000193 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000195 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000196 InstCombineWorklist Worklist;
197
Chris Lattnerc7694852009-08-30 07:44:24 +0000198 /// Builder - This is an IRBuilder that automatically inserts new
199 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +0000200 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000201 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000202
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000204 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205
Owen Anderson175b6542009-07-22 00:24:57 +0000206 LLVMContext *Context;
207 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000208
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 public:
210 virtual bool runOnFunction(Function &F);
211
212 bool DoOneIteration(Function &F, unsigned ItNum);
213
214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 AU.addPreservedID(LCSSAID);
216 AU.setPreservesCFG();
217 }
218
Dan Gohmana80e2712009-07-21 23:21:54 +0000219 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220
221 // Visitation implementation - Implement instruction combining for different
222 // instruction types. The semantics are as follows:
223 // Return Value:
224 // null - No change was made
225 // I - Change was made, I is still valid, I may be dead though
226 // otherwise - Change was made, replace I with returned instruction
227 //
228 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000229 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner93e6ff92009-11-04 08:05:20 +0000230 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000232 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000234 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 Instruction *visitURem(BinaryOperator &I);
236 Instruction *visitSRem(BinaryOperator &I);
237 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000238 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 Instruction *commonRemTransforms(BinaryOperator &I);
240 Instruction *commonIRemTransforms(BinaryOperator &I);
241 Instruction *commonDivTransforms(BinaryOperator &I);
242 Instruction *commonIDivTransforms(BinaryOperator &I);
243 Instruction *visitUDiv(BinaryOperator &I);
244 Instruction *visitSDiv(BinaryOperator &I);
245 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000246 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000247 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000249 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000250 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000251 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000252 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 Instruction *visitOr (BinaryOperator &I);
254 Instruction *visitXor(BinaryOperator &I);
255 Instruction *visitShl(BinaryOperator &I);
256 Instruction *visitAShr(BinaryOperator &I);
257 Instruction *visitLShr(BinaryOperator &I);
258 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000259 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 Instruction *visitFCmpInst(FCmpInst &I);
262 Instruction *visitICmpInst(ICmpInst &I);
263 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
264 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
265 Instruction *LHS,
266 ConstantInt *RHS);
267 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
268 ConstantInt *DivRHS);
Chris Lattner258a2ffb2009-12-21 03:19:28 +0000269 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattnera54b96b2009-12-21 04:04:05 +0000270 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohman17f46f72009-07-28 01:40:03 +0000271 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 ICmpInst::Predicate Cond, Instruction &I);
273 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
274 BinaryOperator &I);
275 Instruction *commonCastTransforms(CastInst &CI);
276 Instruction *commonIntCastTransforms(CastInst &CI);
277 Instruction *commonPointerCastTransforms(CastInst &CI);
278 Instruction *visitTrunc(TruncInst &CI);
279 Instruction *visitZExt(ZExtInst &CI);
280 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000281 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000283 Instruction *visitFPToUI(FPToUIInst &FI);
284 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 Instruction *visitUIToFP(CastInst &CI);
286 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000287 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000288 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 Instruction *visitBitCast(BitCastInst &CI);
290 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
291 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000292 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattner78500cb2009-12-21 06:03:05 +0000293 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
294 Value *A, Value *B, Instruction &Outer,
295 SelectPatternFlavor SPF2, Value *C);
Dan Gohman58c09632008-09-16 18:46:06 +0000296 Instruction *visitSelectInst(SelectInst &SI);
297 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 Instruction *visitCallInst(CallInst &CI);
299 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner1cd526b2009-11-08 19:23:30 +0000300
301 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 Instruction *visitPHINode(PHINode &PN);
303 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandezb1687302009-10-23 21:09:37 +0000304 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez93946082009-10-24 04:23:03 +0000305 Instruction *visitFree(Instruction &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 Instruction *visitLoadInst(LoadInst &LI);
307 Instruction *visitStoreInst(StoreInst &SI);
308 Instruction *visitBranchInst(BranchInst &BI);
309 Instruction *visitSwitchInst(SwitchInst &SI);
310 Instruction *visitInsertElementInst(InsertElementInst &IE);
311 Instruction *visitExtractElementInst(ExtractElementInst &EI);
312 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000313 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314
315 // visitInstruction - Specify what to return for unhandled instructions...
316 Instruction *visitInstruction(Instruction &I) { return 0; }
317
318 private:
319 Instruction *visitCallSite(CallSite CS);
320 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000321 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000322 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
323 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000324 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000325 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327
328 public:
329 // InsertNewInstBefore - insert an instruction New before instruction Old
330 // in the program. Add the new instruction to the worklist.
331 //
332 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
333 assert(New && New->getParent() == 0 &&
334 "New instruction already inserted into a basic block!");
335 BasicBlock *BB = Old.getParent();
336 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000337 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 return New;
339 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000340
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 // ReplaceInstUsesWith - This method is to be used when an instruction is
342 // found to be dead, replacable with another preexisting expression. Here
343 // we add all uses of I to the worklist, replace all uses of I with the new
344 // value, then return I, so that the inst combiner will know that I was
345 // modified.
346 //
347 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000348 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000349
350 // If we are replacing the instruction with itself, this must be in a
351 // segment of unreachable code, so just clobber the instruction.
352 if (&I == V)
353 V = UndefValue::get(I.getType());
354
355 I.replaceAllUsesWith(V);
356 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 }
358
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 // EraseInstFromFunction - When dealing with an instruction that has side
360 // effects or produces a void value, we can't rely on DCE to delete the
361 // instruction. Instead, visit methods should return the value returned by
362 // this function.
363 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000364 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000365
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000367 // Make sure that we reprocess all operands now that we reduced their
368 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000369 if (I.getNumOperands() < 8) {
370 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
371 if (Instruction *Op = dyn_cast<Instruction>(*i))
372 Worklist.Add(Op);
373 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000374 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000376 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 return 0; // Don't do anything with FI
378 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
381 APInt &KnownOne, unsigned Depth = 0) const {
382 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
383 }
384
385 bool MaskedValueIsZero(Value *V, const APInt &Mask,
386 unsigned Depth = 0) const {
387 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
388 }
389 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
390 return llvm::ComputeNumSignBits(Op, TD, Depth);
391 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392
393 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394
395 /// SimplifyCommutative - This performs a few simplifications for
396 /// commutative operators.
397 bool SimplifyCommutative(BinaryOperator &I);
398
Chris Lattner676c78e2009-01-31 08:15:18 +0000399 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
400 /// based on the demanded bits.
401 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
402 APInt& KnownZero, APInt& KnownOne,
403 unsigned Depth);
404 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000406 unsigned Depth=0);
407
408 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
409 /// SimplifyDemandedBits knows about. See if the instruction has any
410 /// properties that allow us to simplify its operands.
411 bool SimplifyDemandedInstructionBits(Instruction &Inst);
412
Evan Cheng63295ab2009-02-03 10:05:09 +0000413 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
414 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415
Chris Lattnerf7843b72009-09-27 19:57:57 +0000416 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
417 // which has a PHI node as operand #0, see if we can fold the instruction
418 // into the PHI (which is only possible if all operands to the PHI are
419 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000420 //
421 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
422 // that would normally be unprofitable because they strongly encourage jump
423 // threading.
424 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425
426 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
427 // operator and they all are only used by the PHI, PHI together their
428 // inputs, and do the operation once, to the result of the PHI.
429 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
430 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000431 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner38751f82009-11-01 20:04:24 +0000432 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434
435 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
436 ConstantInt *AndRHS, BinaryOperator &TheAnd);
437
438 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
439 bool isSub, Instruction &I);
440 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
441 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandezb1687302009-10-23 21:09:37 +0000442 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 Instruction *MatchBSwap(BinaryOperator &I);
444 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000445 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000446 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000447
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448
449 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000450
Dan Gohman8fd520a2009-06-15 22:12:54 +0000451 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000452 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000453 unsigned GetOrEnforceKnownAlignment(Value *V,
454 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000455
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456 };
Chris Lattner5119c702009-08-30 05:55:36 +0000457} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458
Dan Gohman089efff2008-05-13 00:00:25 +0000459char InstCombiner::ID = 0;
460static RegisterPass<InstCombiner>
461X("instcombine", "Combine redundant instructions");
462
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463// getComplexity: Assign a complexity or rank value to LLVM Values...
464// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000465static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000467 if (BinaryOperator::isNeg(V) ||
468 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000469 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 return 3;
471 return 4;
472 }
473 if (isa<Argument>(V)) return 3;
474 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
475}
476
477// isOnlyUse - Return true if this instruction will be deleted if we stop using
478// it.
479static bool isOnlyUse(Value *V) {
480 return V->hasOneUse() || isa<Constant>(V);
481}
482
483// getPromotedType - Return the specified type promoted as it would be to pass
484// though a va_arg area...
485static const Type *getPromotedType(const Type *Ty) {
486 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
487 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000488 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 }
490 return Ty;
491}
492
Chris Lattnerd0011092009-11-10 07:23:37 +0000493/// ShouldChangeType - Return true if it is desirable to convert a computation
494/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
495/// type for example, or from a smaller to a larger illegal type.
496static bool ShouldChangeType(const Type *From, const Type *To,
497 const TargetData *TD) {
498 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
499
500 // If we don't have TD, we don't know if the source/dest are legal.
501 if (!TD) return false;
502
503 unsigned FromWidth = From->getPrimitiveSizeInBits();
504 unsigned ToWidth = To->getPrimitiveSizeInBits();
505 bool FromLegal = TD->isLegalInteger(FromWidth);
506 bool ToLegal = TD->isLegalInteger(ToWidth);
507
508 // If this is a legal integer from type, and the result would be an illegal
509 // type, don't do the transformation.
510 if (FromLegal && !ToLegal)
511 return false;
512
513 // Otherwise, if both are illegal, do not increase the size of the result. We
514 // do allow things like i160 -> i64, but not i64 -> i160.
515 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
516 return false;
517
518 return true;
519}
520
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000521/// getBitCastOperand - If the specified operand is a CastInst, a constant
522/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
523/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000525 if (Operator *O = dyn_cast<Operator>(V)) {
526 if (O->getOpcode() == Instruction::BitCast)
527 return O->getOperand(0);
528 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
529 if (GEP->hasAllZeroIndices())
530 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 return 0;
533}
534
535/// This function is a wrapper around CastInst::isEliminableCastPair. It
536/// simply extracts arguments and returns what that function returns.
537static Instruction::CastOps
538isEliminableCastPair(
539 const CastInst *CI, ///< The first cast instruction
540 unsigned opcode, ///< The opcode of the second cast instruction
541 const Type *DstTy, ///< The target type for the second cast instruction
542 TargetData *TD ///< The target data for pointer size
543) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000544
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
546 const Type *MidTy = CI->getType(); // B from above
547
548 // Get the opcodes of the two Cast instructions
549 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
550 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
551
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000552 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000553 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000554 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000555
556 // We don't want to form an inttoptr or ptrtoint that converts to an integer
557 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000558 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000559 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000560 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000561 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000562 Res = 0;
563
564 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565}
566
567/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
568/// in any code being generated. It does not require codegen if V is simple
569/// enough or if the cast can be folded into other casts.
570static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
571 const Type *Ty, TargetData *TD) {
572 if (V->getType() == Ty || isa<Constant>(V)) return false;
573
574 // If this is another cast that can be eliminated, it isn't codegen either.
575 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000576 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 return false;
578 return true;
579}
580
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581// SimplifyCommutative - This performs a few simplifications for commutative
582// operators:
583//
584// 1. Order operands such that they are listed from right (least complex) to
585// left (most complex). This puts constants before unary operators before
586// binary operators.
587//
588// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
589// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
590//
591bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
592 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000593 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 Changed = !I.swapOperands();
595
596 if (!I.isAssociative()) return Changed;
597 Instruction::BinaryOps Opcode = I.getOpcode();
598 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
599 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
600 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000601 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 cast<Constant>(I.getOperand(1)),
603 cast<Constant>(Op->getOperand(1)));
604 I.setOperand(0, Op->getOperand(0));
605 I.setOperand(1, Folded);
606 return true;
607 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
608 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
609 isOnlyUse(Op) && isOnlyUse(Op1)) {
610 Constant *C1 = cast<Constant>(Op->getOperand(1));
611 Constant *C2 = cast<Constant>(Op1->getOperand(1));
612
613 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000614 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000615 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 Op1->getOperand(0),
617 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000618 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 I.setOperand(0, New);
620 I.setOperand(1, Folded);
621 return true;
622 }
623 }
624 return Changed;
625}
626
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
628// if the LHS is a constant zero (which is the 'negate' form).
629//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000630static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000631 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 return BinaryOperator::getNegArgument(V);
633
634 // Constants can be considered to be negated values if they can be folded.
635 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000636 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000637
638 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
639 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000640 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000641
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 return 0;
643}
644
Dan Gohman7ce405e2009-06-04 22:49:04 +0000645// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
646// instruction if the LHS is a constant negative zero (which is the 'negate'
647// form).
648//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000649static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000650 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000651 return BinaryOperator::getFNegArgument(V);
652
653 // Constants can be considered to be negated values if they can be folded.
654 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000655 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000656
657 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
658 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000659 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000660
661 return 0;
662}
663
Chris Lattner78500cb2009-12-21 06:03:05 +0000664/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
665/// returning the kind and providing the out parameter results if we
666/// successfully match.
667static SelectPatternFlavor
668MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
669 SelectInst *SI = dyn_cast<SelectInst>(V);
670 if (SI == 0) return SPF_UNKNOWN;
671
672 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
673 if (ICI == 0) return SPF_UNKNOWN;
674
675 LHS = ICI->getOperand(0);
676 RHS = ICI->getOperand(1);
677
678 // (icmp X, Y) ? X : Y
679 if (SI->getTrueValue() == ICI->getOperand(0) &&
680 SI->getFalseValue() == ICI->getOperand(1)) {
681 switch (ICI->getPredicate()) {
682 default: return SPF_UNKNOWN; // Equality.
683 case ICmpInst::ICMP_UGT:
684 case ICmpInst::ICMP_UGE: return SPF_UMAX;
685 case ICmpInst::ICMP_SGT:
686 case ICmpInst::ICMP_SGE: return SPF_SMAX;
687 case ICmpInst::ICMP_ULT:
688 case ICmpInst::ICMP_ULE: return SPF_UMIN;
689 case ICmpInst::ICMP_SLT:
690 case ICmpInst::ICMP_SLE: return SPF_SMIN;
691 }
692 }
693
694 // (icmp X, Y) ? Y : X
695 if (SI->getTrueValue() == ICI->getOperand(1) &&
696 SI->getFalseValue() == ICI->getOperand(0)) {
697 switch (ICI->getPredicate()) {
698 default: return SPF_UNKNOWN; // Equality.
699 case ICmpInst::ICMP_UGT:
700 case ICmpInst::ICMP_UGE: return SPF_UMIN;
701 case ICmpInst::ICMP_SGT:
702 case ICmpInst::ICMP_SGE: return SPF_SMIN;
703 case ICmpInst::ICMP_ULT:
704 case ICmpInst::ICMP_ULE: return SPF_UMAX;
705 case ICmpInst::ICMP_SLT:
706 case ICmpInst::ICMP_SLE: return SPF_SMAX;
707 }
708 }
709
710 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
711
712 return SPF_UNKNOWN;
713}
714
Chris Lattner6e060db2009-10-26 15:40:07 +0000715/// isFreeToInvert - Return true if the specified value is free to invert (apply
716/// ~ to). This happens in cases where the ~ can be eliminated.
717static inline bool isFreeToInvert(Value *V) {
718 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000719 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000720 return true;
721
722 // Constants can be considered to be not'ed values.
723 if (isa<ConstantInt>(V))
724 return true;
725
726 // Compares can be inverted if they have a single use.
727 if (CmpInst *CI = dyn_cast<CmpInst>(V))
728 return CI->hasOneUse();
729
730 return false;
731}
732
733static inline Value *dyn_castNotVal(Value *V) {
734 // If this is not(not(x)) don't return that this is a not: we want the two
735 // not's to be folded first.
736 if (BinaryOperator::isNot(V)) {
737 Value *Operand = BinaryOperator::getNotArgument(V);
738 if (!isFreeToInvert(Operand))
739 return Operand;
740 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741
742 // Constants can be considered to be not'ed values...
743 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000744 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 return 0;
746}
747
Chris Lattner6e060db2009-10-26 15:40:07 +0000748
749
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750// dyn_castFoldableMul - If this value is a multiply that can be folded into
751// other computations (because it has a constant operand), return the
752// non-constant operand of the multiply, and set CST to point to the multiplier.
753// Otherwise, return null.
754//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000755static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 if (V->hasOneUse() && V->getType()->isInteger())
757 if (Instruction *I = dyn_cast<Instruction>(V)) {
758 if (I->getOpcode() == Instruction::Mul)
759 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
760 return I->getOperand(0);
761 if (I->getOpcode() == Instruction::Shl)
762 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
763 // The multiplier is really 1 << CST.
764 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
765 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000766 CST = ConstantInt::get(V->getType()->getContext(),
767 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 return I->getOperand(0);
769 }
770 }
771 return 0;
772}
773
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000775static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000776 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000777 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778}
779/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000780static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000781 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000782 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000784/// MultiplyOverflows - True if the multiply can not be expressed in an int
785/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000786static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000787 uint32_t W = C1->getBitWidth();
788 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
789 if (sign) {
790 LHSExt.sext(W * 2);
791 RHSExt.sext(W * 2);
792 } else {
793 LHSExt.zext(W * 2);
794 RHSExt.zext(W * 2);
795 }
796
797 APInt MulExt = LHSExt * RHSExt;
798
Chris Lattner78500cb2009-12-21 06:03:05 +0000799 if (!sign)
Nick Lewycky9d798f92008-02-18 22:48:05 +0000800 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattner78500cb2009-12-21 06:03:05 +0000801
802 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
803 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
804 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewycky9d798f92008-02-18 22:48:05 +0000805}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807
808/// ShrinkDemandedConstant - Check to see if the specified operand of the
809/// specified instruction is a constant integer. If so, check to see if there
810/// are any bits set in the constant that are not demanded. If so, shrink the
811/// constant and return true.
812static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000813 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 assert(I && "No instruction?");
815 assert(OpNo < I->getNumOperands() && "Operand index too large");
816
817 // If the operand is not a constant integer, nothing to do.
818 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
819 if (!OpC) return false;
820
821 // If there are no bits set that aren't demanded, nothing to do.
822 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
823 if ((~Demanded & OpC->getValue()) == 0)
824 return false;
825
826 // This instruction is producing bits that are not demanded. Shrink the RHS.
827 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000828 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 return true;
830}
831
832// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
833// set of known zero and one bits, compute the maximum and minimum values that
834// could have the specified known zero and known one bits, returning them in
835// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000836static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 const APInt& KnownOne,
838 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000839 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
840 KnownZero.getBitWidth() == Min.getBitWidth() &&
841 KnownZero.getBitWidth() == Max.getBitWidth() &&
842 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 APInt UnknownBits = ~(KnownZero|KnownOne);
844
845 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
846 // bit if it is unknown.
847 Min = KnownOne;
848 Max = KnownOne|UnknownBits;
849
Dan Gohman7934d592009-04-25 17:12:48 +0000850 if (UnknownBits.isNegative()) { // Sign bit is unknown
851 Min.set(Min.getBitWidth()-1);
852 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 }
854}
855
856// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
857// a set of known zero and one bits, compute the maximum and minimum values that
858// could have the specified known zero and known one bits, returning them in
859// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000860static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000861 const APInt &KnownOne,
862 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000863 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
864 KnownZero.getBitWidth() == Min.getBitWidth() &&
865 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
867 APInt UnknownBits = ~(KnownZero|KnownOne);
868
869 // The minimum value is when the unknown bits are all zeros.
870 Min = KnownOne;
871 // The maximum value is when the unknown bits are all ones.
872 Max = KnownOne|UnknownBits;
873}
874
Chris Lattner676c78e2009-01-31 08:15:18 +0000875/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
876/// SimplifyDemandedBits knows about. See if the instruction has any
877/// properties that allow us to simplify its operands.
878bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000879 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000880 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
881 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
882
883 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
884 KnownZero, KnownOne, 0);
885 if (V == 0) return false;
886 if (V == &Inst) return true;
887 ReplaceInstUsesWith(Inst, V);
888 return true;
889}
890
891/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
892/// specified instruction operand if possible, updating it in place. It returns
893/// true if it made any change and false otherwise.
894bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
895 APInt &KnownZero, APInt &KnownOne,
896 unsigned Depth) {
897 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
898 KnownZero, KnownOne, Depth);
899 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000900 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000901 return true;
902}
903
904
905/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
906/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907/// that only the bits set in DemandedMask of the result of V are ever used
908/// downstream. Consequently, depending on the mask and V, it may be possible
909/// to replace V with a constant or one of its operands. In such cases, this
910/// function does the replacement and returns true. In all other cases, it
911/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000912/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913/// to be zero in the expression. These are provided to potentially allow the
914/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
915/// the expression. KnownOne and KnownZero always follow the invariant that
916/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
917/// the bits in KnownOne and KnownZero may only be accurate for those bits set
918/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
919/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000920///
921/// This returns null if it did not change anything and it permits no
922/// simplification. This returns V itself if it did some simplification of V's
923/// operands based on the information about what bits are demanded. This returns
924/// some other non-null value if it found out that V is equal to another value
925/// in the context where the specified bits are demanded, but not for all users.
926Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
927 APInt &KnownZero, APInt &KnownOne,
928 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 assert(V != 0 && "Null pointer of Value???");
930 assert(Depth <= 6 && "Limit Search Depth");
931 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000932 const Type *VTy = V->getType();
933 assert((TD || !isa<PointerType>(VTy)) &&
934 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000935 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
936 (!VTy->isIntOrIntVector() ||
937 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000938 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000940 "Value *V, DemandedMask, KnownZero and KnownOne "
941 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
943 // We know all of the bits for a constant!
944 KnownOne = CI->getValue() & DemandedMask;
945 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000946 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 }
Dan Gohman7934d592009-04-25 17:12:48 +0000948 if (isa<ConstantPointerNull>(V)) {
949 // We know all of the bits for a constant!
950 KnownOne.clear();
951 KnownZero = DemandedMask;
952 return 0;
953 }
954
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000955 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000957 if (DemandedMask == 0) { // Not demanding any bits from V.
958 if (isa<UndefValue>(V))
959 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000960 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 }
962
Chris Lattner08817332009-01-31 08:24:16 +0000963 if (Depth == 6) // Limit search depth.
964 return 0;
965
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000966 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
967 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
968
Dan Gohman7934d592009-04-25 17:12:48 +0000969 Instruction *I = dyn_cast<Instruction>(V);
970 if (!I) {
971 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
972 return 0; // Only analyze instructions.
973 }
974
Chris Lattner08817332009-01-31 08:24:16 +0000975 // If there are multiple uses of this value and we aren't at the root, then
976 // we can't do any simplifications of the operands, because DemandedMask
977 // only reflects the bits demanded by *one* of the users.
978 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000979 // Despite the fact that we can't simplify this instruction in all User's
980 // context, we can at least compute the knownzero/knownone bits, and we can
981 // do simplifications that apply to *just* the one user if we know that
982 // this instruction has a simpler value in that context.
983 if (I->getOpcode() == Instruction::And) {
984 // If either the LHS or the RHS are Zero, the result is zero.
985 ComputeMaskedBits(I->getOperand(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1);
987 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
988 LHSKnownZero, LHSKnownOne, Depth+1);
989
990 // If all of the demanded bits are known 1 on one side, return the other.
991 // These bits cannot contribute to the result of the 'and' in this
992 // context.
993 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
994 (DemandedMask & ~LHSKnownZero))
995 return I->getOperand(0);
996 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
997 (DemandedMask & ~RHSKnownZero))
998 return I->getOperand(1);
999
1000 // If all of the demanded bits in the inputs are known zeros, return zero.
1001 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +00001002 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +00001003
1004 } else if (I->getOpcode() == Instruction::Or) {
1005 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1006 // only bits from X or Y are demanded.
1007
1008 // If either the LHS or the RHS are One, the result is One.
1009 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1010 RHSKnownZero, RHSKnownOne, Depth+1);
1011 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1012 LHSKnownZero, LHSKnownOne, Depth+1);
1013
1014 // If all of the demanded bits are known zero on one side, return the
1015 // other. These bits cannot contribute to the result of the 'or' in this
1016 // context.
1017 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1018 (DemandedMask & ~LHSKnownOne))
1019 return I->getOperand(0);
1020 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1021 (DemandedMask & ~RHSKnownOne))
1022 return I->getOperand(1);
1023
1024 // If all of the potentially set bits on one side are known to be set on
1025 // the other side, just use the 'other' side.
1026 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1027 (DemandedMask & (~RHSKnownZero)))
1028 return I->getOperand(0);
1029 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1030 (DemandedMask & (~LHSKnownZero)))
1031 return I->getOperand(1);
1032 }
1033
Chris Lattner08817332009-01-31 08:24:16 +00001034 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1035 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1036 return 0;
1037 }
1038
1039 // If this is the root being simplified, allow it to have multiple uses,
1040 // just set the DemandedMask to all bits so that we can try to simplify the
1041 // operands. This allows visitTruncInst (for example) to simplify the
1042 // operand of a trunc without duplicating all the logic below.
1043 if (Depth == 0 && !V->hasOneUse())
1044 DemandedMask = APInt::getAllOnesValue(BitWidth);
1045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001047 default:
Chris Lattner676c78e2009-01-31 08:15:18 +00001048 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +00001049 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 case Instruction::And:
1051 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +00001052 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1053 RHSKnownZero, RHSKnownOne, Depth+1) ||
1054 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 return I;
1057 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1058 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
1060 // If all of the demanded bits are known 1 on one side, return the other.
1061 // These bits cannot contribute to the result of the 'and'.
1062 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1063 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001064 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1066 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001067 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
1069 // If all of the demanded bits in the inputs are known zeros, return zero.
1070 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +00001071 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072
1073 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001074 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001075 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076
1077 // Output known-1 bits are only known if set in both the LHS & RHS.
1078 RHSKnownOne &= LHSKnownOne;
1079 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1080 RHSKnownZero |= LHSKnownZero;
1081 break;
1082 case Instruction::Or:
1083 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1085 RHSKnownZero, RHSKnownOne, Depth+1) ||
1086 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001088 return I;
1089 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1090 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091
1092 // If all of the demanded bits are known zero on one side, return the other.
1093 // These bits cannot contribute to the result of the 'or'.
1094 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1095 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001096 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1098 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001099 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100
1101 // If all of the potentially set bits on one side are known to be set on
1102 // the other side, just use the 'other' side.
1103 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1104 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001105 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1107 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001108 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109
1110 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001111 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001112 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113
1114 // Output known-0 bits are only known if clear in both the LHS & RHS.
1115 RHSKnownZero &= LHSKnownZero;
1116 // Output known-1 are known to be set if set in either the LHS | RHS.
1117 RHSKnownOne |= LHSKnownOne;
1118 break;
1119 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1121 RHSKnownZero, RHSKnownOne, Depth+1) ||
1122 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001124 return I;
1125 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1126 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127
1128 // If all of the demanded bits are known zero on one side, return the other.
1129 // These bits cannot contribute to the result of the 'xor'.
1130 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001131 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001133 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134
1135 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1136 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1137 (RHSKnownOne & LHSKnownOne);
1138 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1139 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1140 (RHSKnownOne & LHSKnownZero);
1141
1142 // If all of the demanded bits are known to be zero on one side or the
1143 // other, turn this into an *inclusive* or.
1144 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001145 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1146 Instruction *Or =
1147 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1148 I->getName());
1149 return InsertNewInstBefore(Or, *I);
1150 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151
1152 // If all of the demanded bits on one side are known, and all of the set
1153 // bits on that side are also known to be set on the other side, turn this
1154 // into an AND, as we know the bits will be cleared.
1155 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1156 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1157 // all known
1158 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001159 Constant *AndC = Constant::getIntegerValue(VTy,
1160 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001162 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001163 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 }
1165 }
1166
1167 // If the RHS is a constant, see if we can simplify it.
1168 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001169 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001170 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171
Chris Lattnereefa89c2009-10-11 22:22:13 +00001172 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1173 // are flipping are known to be set, then the xor is just resetting those
1174 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1175 // simplifying both of them.
1176 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1177 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1178 isa<ConstantInt>(I->getOperand(1)) &&
1179 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1180 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1181 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1182 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1183 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1184
1185 Constant *AndC =
1186 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1187 Instruction *NewAnd =
1188 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1189 InsertNewInstBefore(NewAnd, *I);
1190
1191 Constant *XorC =
1192 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1193 Instruction *NewXor =
1194 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1195 return InsertNewInstBefore(NewXor, *I);
1196 }
1197
1198
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001199 RHSKnownZero = KnownZeroOut;
1200 RHSKnownOne = KnownOneOut;
1201 break;
1202 }
1203 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001204 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1205 RHSKnownZero, RHSKnownOne, Depth+1) ||
1206 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001208 return I;
1209 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1210 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211
1212 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001213 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1214 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001215 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216
1217 // Only known if known in both the LHS and RHS.
1218 RHSKnownOne &= LHSKnownOne;
1219 RHSKnownZero &= LHSKnownZero;
1220 break;
1221 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001222 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 DemandedMask.zext(truncBf);
1224 RHSKnownZero.zext(truncBf);
1225 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001226 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001228 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 DemandedMask.trunc(BitWidth);
1230 RHSKnownZero.trunc(BitWidth);
1231 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001232 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 break;
1234 }
1235 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001236 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001237 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001238
1239 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1240 if (const VectorType *SrcVTy =
1241 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1242 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1243 // Don't touch a bitcast between vectors of different element counts.
1244 return false;
1245 } else
1246 // Don't touch a scalar-to-vector bitcast.
1247 return false;
1248 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1249 // Don't touch a vector-to-scalar bitcast.
1250 return false;
1251
Chris Lattner676c78e2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001254 return I;
1255 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 break;
1257 case Instruction::ZExt: {
1258 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001259 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260
1261 DemandedMask.trunc(SrcBitWidth);
1262 RHSKnownZero.trunc(SrcBitWidth);
1263 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001266 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 DemandedMask.zext(BitWidth);
1268 RHSKnownZero.zext(BitWidth);
1269 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001270 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 // The top bits are known to be zero.
1272 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1273 break;
1274 }
1275 case Instruction::SExt: {
1276 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001277 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278
1279 APInt InputDemandedBits = DemandedMask &
1280 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1281
1282 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1283 // If any of the sign extended bits are demanded, we know that the sign
1284 // bit is demanded.
1285 if ((NewBits & DemandedMask) != 0)
1286 InputDemandedBits.set(SrcBitWidth-1);
1287
1288 InputDemandedBits.trunc(SrcBitWidth);
1289 RHSKnownZero.trunc(SrcBitWidth);
1290 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001293 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 InputDemandedBits.zext(BitWidth);
1295 RHSKnownZero.zext(BitWidth);
1296 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298
1299 // If the sign bit of the input is known set or clear, then we know the
1300 // top bits of the result.
1301
1302 // If the input sign bit is known zero, or if the NewBits are not demanded
1303 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001304 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001306 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1307 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1309 RHSKnownOne |= NewBits;
1310 }
1311 break;
1312 }
1313 case Instruction::Add: {
1314 // Figure out what the input bits are. If the top bits of the and result
1315 // are not demanded, then the add doesn't demand them from its input
1316 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001317 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318
1319 // If there is a constant on the RHS, there are a variety of xformations
1320 // we can do.
1321 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322 // If null, this should be simplified elsewhere. Some of the xforms here
1323 // won't work if the RHS is zero.
1324 if (RHS->isZero())
1325 break;
1326
1327 // If the top bit of the output is demanded, demand everything from the
1328 // input. Otherwise, we demand all the input bits except NLZ top bits.
1329 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1330
1331 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001332 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001334 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335
1336 // If the RHS of the add has bits set that can't affect the input, reduce
1337 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001338 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001339 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340
1341 // Avoid excess work.
1342 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1343 break;
1344
1345 // Turn it into OR if input bits are zero.
1346 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1347 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001348 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001350 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 }
1352
1353 // We can say something about the output known-zero and known-one bits,
1354 // depending on potential carries from the input constant and the
1355 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1356 // bits set and the RHS constant is 0x01001, then we know we have a known
1357 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1358
1359 // To compute this, we first compute the potential carry bits. These are
1360 // the bits which may be modified. I'm not aware of a better way to do
1361 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001362 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1364
1365 // Now that we know which bits have carries, compute the known-1/0 sets.
1366
1367 // Bits are known one if they are known zero in one operand and one in the
1368 // other, and there is no input carry.
1369 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1370 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1371
1372 // Bits are known zero if they are known zero in both operands and there
1373 // is no input carry.
1374 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1375 } else {
1376 // If the high-bits of this ADD are not demanded, then it does not demand
1377 // the high bits of its LHS or RHS.
1378 if (DemandedMask[BitWidth-1] == 0) {
1379 // Right fill the mask of bits for this ADD to demand the most
1380 // significant bit and all those below it.
1381 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001382 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1383 LHSKnownZero, LHSKnownOne, Depth+1) ||
1384 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001386 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 }
1388 }
1389 break;
1390 }
1391 case Instruction::Sub:
1392 // If the high-bits of this SUB are not demanded, then it does not demand
1393 // the high bits of its LHS or RHS.
1394 if (DemandedMask[BitWidth-1] == 0) {
1395 // Right fill the mask of bits for this SUB to demand the most
1396 // significant bit and all those below it.
1397 uint32_t NLZ = DemandedMask.countLeadingZeros();
1398 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001399 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1400 LHSKnownZero, LHSKnownOne, Depth+1) ||
1401 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001403 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001405 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1406 // the known zeros and ones.
1407 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 break;
1409 case Instruction::Shl:
1410 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1411 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1412 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001413 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001415 return I;
1416 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 RHSKnownZero <<= ShiftAmt;
1418 RHSKnownOne <<= ShiftAmt;
1419 // low bits known zero.
1420 if (ShiftAmt)
1421 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1422 }
1423 break;
1424 case Instruction::LShr:
1425 // For a logical shift right
1426 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1427 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1428
1429 // Unsigned shift right.
1430 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001431 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001433 return I;
1434 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1436 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1437 if (ShiftAmt) {
1438 // Compute the new bits that are at the top now.
1439 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1440 RHSKnownZero |= HighBits; // high bits known zero.
1441 }
1442 }
1443 break;
1444 case Instruction::AShr:
1445 // If this is an arithmetic shift right and only the low-bit is set, we can
1446 // always convert this into a logical shr, even if the shift amount is
1447 // variable. The low bit of the shift cannot be an input sign bit unless
1448 // the shift amount is >= the size of the datatype, which is undefined.
1449 if (DemandedMask == 1) {
1450 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001451 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001453 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 }
1455
1456 // If the sign bit is the only bit demanded by this ashr, then there is no
1457 // need to do it, the shift doesn't change the high bit.
1458 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001459 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460
1461 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1462 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1463
1464 // Signed shift right.
1465 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1466 // If any of the "high bits" are demanded, we should set the sign bit as
1467 // demanded.
1468 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1469 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001470 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001472 return I;
1473 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 // Compute the new bits that are at the top now.
1475 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1476 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1477 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1478
1479 // Handle the sign bits.
1480 APInt SignBit(APInt::getSignBit(BitWidth));
1481 // Adjust to where it is now in the mask.
1482 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1483
1484 // If the input sign bit is known to be zero, or if none of the top bits
1485 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001486 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 (HighBits & ~DemandedMask) == HighBits) {
1488 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001489 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001491 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1493 RHSKnownOne |= HighBits;
1494 }
1495 }
1496 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001497 case Instruction::SRem:
1498 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001499 APInt RA = Rem->getValue().abs();
1500 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001501 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001502 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001503
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001504 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001505 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001506 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001507 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001508 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001509
1510 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1511 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001512
1513 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001514
Chris Lattner676c78e2009-01-31 08:15:18 +00001515 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001516 }
1517 }
1518 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001519 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001520 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1521 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001522 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1523 KnownZero2, KnownOne2, Depth+1) ||
1524 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001525 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001526 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001527
Chris Lattneree5417c2009-01-21 18:09:24 +00001528 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001529 Leaders = std::max(Leaders,
1530 KnownZero2.countLeadingOnes());
1531 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001532 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 }
Chris Lattner989ba312008-06-18 04:33:20 +00001534 case Instruction::Call:
1535 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1536 switch (II->getIntrinsicID()) {
1537 default: break;
1538 case Intrinsic::bswap: {
1539 // If the only bits demanded come from one byte of the bswap result,
1540 // just shift the input byte into position to eliminate the bswap.
1541 unsigned NLZ = DemandedMask.countLeadingZeros();
1542 unsigned NTZ = DemandedMask.countTrailingZeros();
1543
1544 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1545 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1546 // have 14 leading zeros, round to 8.
1547 NLZ &= ~7;
1548 NTZ &= ~7;
1549 // If we need exactly one byte, we can do this transformation.
1550 if (BitWidth-NLZ-NTZ == 8) {
1551 unsigned ResultBit = NTZ;
1552 unsigned InputBit = BitWidth-NTZ-8;
1553
1554 // Replace this with either a left or right shift to get the byte into
1555 // the right place.
1556 Instruction *NewVal;
1557 if (InputBit > ResultBit)
1558 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001559 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001560 else
1561 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001562 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001563 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001564 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001565 }
1566
1567 // TODO: Could compute known zero/one bits based on the input.
1568 break;
1569 }
1570 }
1571 }
Chris Lattner4946e222008-06-18 18:11:55 +00001572 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001573 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001574 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575
1576 // If the client is only demanding bits that we know, return the known
1577 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001578 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1579 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 return false;
1581}
1582
1583
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001584/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001585/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586/// actually used by the caller. This method analyzes which elements of the
1587/// operand are undef and returns that information in UndefElts.
1588///
1589/// If the information about demanded elements can be used to simplify the
1590/// operation, the operation is simplified, then the resultant value is
1591/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001592Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1593 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594 unsigned Depth) {
1595 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001596 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001597 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598
1599 if (isa<UndefValue>(V)) {
1600 // If the entire vector is undefined, just return this info.
1601 UndefElts = EltMask;
1602 return 0;
1603 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1604 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001605 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001607
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 UndefElts = 0;
1609 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1610 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001611 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612
1613 std::vector<Constant*> Elts;
1614 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001615 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001617 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1619 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001620 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001621 } else { // Otherwise, defined.
1622 Elts.push_back(CP->getOperand(i));
1623 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001624
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001626 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 return NewCP != CP ? NewCP : 0;
1628 } else if (isa<ConstantAggregateZero>(V)) {
1629 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1630 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001631
1632 // Check if this is identity. If so, return 0 since we are not simplifying
1633 // anything.
1634 if (DemandedElts == ((1ULL << VWidth) -1))
1635 return 0;
1636
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001638 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001639 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001641 for (unsigned i = 0; i != VWidth; ++i) {
1642 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1643 Elts.push_back(Elt);
1644 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001646 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647 }
1648
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001649 // Limit search depth.
1650 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001651 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001652
1653 // If multiple users are using the root value, procede with
1654 // simplification conservatively assuming that all elements
1655 // are needed.
1656 if (!V->hasOneUse()) {
1657 // Quit if we find multiple users of a non-root value though.
1658 // They'll be handled when it's their turn to be visited by
1659 // the main instcombine process.
1660 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001661 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001662 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001663
1664 // Conservatively assume that all elements are needed.
1665 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 }
1667
1668 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001669 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670
1671 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001672 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 Value *TmpV;
1674 switch (I->getOpcode()) {
1675 default: break;
1676
1677 case Instruction::InsertElement: {
1678 // If this is a variable index, we don't know which element it overwrites.
1679 // demand exactly the same input as we produce.
1680 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1681 if (Idx == 0) {
1682 // Note that we can't propagate undef elt info, because we don't know
1683 // which elt is getting updated.
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685 UndefElts2, Depth+1);
1686 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687 break;
1688 }
1689
1690 // If this is inserting an element that isn't demanded, remove this
1691 // insertelement.
1692 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001693 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1694 Worklist.Add(I);
1695 return I->getOperand(0);
1696 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697
1698 // Otherwise, the element inserted overwrites whatever was there, so the
1699 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001700 APInt DemandedElts2 = DemandedElts;
1701 DemandedElts2.clear(IdxNo);
1702 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 UndefElts, Depth+1);
1704 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705
1706 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001707 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001708 break;
1709 }
1710 case Instruction::ShuffleVector: {
1711 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001712 uint64_t LHSVWidth =
1713 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001714 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001715 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001716 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001717 unsigned MaskVal = Shuffle->getMaskValue(i);
1718 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001719 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001720 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001721 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001722 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001723 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001724 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001725 }
1726 }
1727 }
1728
Nate Begemanb4d176f2009-02-11 22:36:25 +00001729 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001730 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001731 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001732 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1733
Nate Begemanb4d176f2009-02-11 22:36:25 +00001734 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001735 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1736 UndefElts3, Depth+1);
1737 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1738
1739 bool NewUndefElts = false;
1740 for (unsigned i = 0; i < VWidth; i++) {
1741 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001742 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001743 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001744 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001745 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001746 NewUndefElts = true;
1747 UndefElts.set(i);
1748 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001749 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001750 if (UndefElts3[MaskVal - LHSVWidth]) {
1751 NewUndefElts = true;
1752 UndefElts.set(i);
1753 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001754 }
1755 }
1756
1757 if (NewUndefElts) {
1758 // Add additional discovered undefs.
1759 std::vector<Constant*> Elts;
1760 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001761 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001762 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001763 else
Owen Anderson35b47072009-08-13 21:58:54 +00001764 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001765 Shuffle->getMaskValue(i)));
1766 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001767 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001768 MadeChange = true;
1769 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770 break;
1771 }
1772 case Instruction::BitCast: {
1773 // Vector->vector casts only.
1774 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1775 if (!VTy) break;
1776 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001777 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778 unsigned Ratio;
1779
1780 if (VWidth == InVWidth) {
1781 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1782 // elements as are demanded of us.
1783 Ratio = 1;
1784 InputDemandedElts = DemandedElts;
1785 } else if (VWidth > InVWidth) {
1786 // Untested so far.
1787 break;
1788
1789 // If there are more elements in the result than there are in the source,
1790 // then an input element is live if any of the corresponding output
1791 // elements are live.
1792 Ratio = VWidth/InVWidth;
1793 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001794 if (DemandedElts[OutIdx])
1795 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 }
1797 } else {
1798 // Untested so far.
1799 break;
1800
1801 // If there are more elements in the source than there are in the result,
1802 // then an input element is live if the corresponding output element is
1803 // live.
1804 Ratio = InVWidth/VWidth;
1805 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001806 if (DemandedElts[InIdx/Ratio])
1807 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808 }
1809
1810 // div/rem demand all inputs, because they don't want divide by zero.
1811 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1812 UndefElts2, Depth+1);
1813 if (TmpV) {
1814 I->setOperand(0, TmpV);
1815 MadeChange = true;
1816 }
1817
1818 UndefElts = UndefElts2;
1819 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001820 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821 // If there are more elements in the result than there are in the source,
1822 // then an output element is undef if the corresponding input element is
1823 // undef.
1824 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001825 if (UndefElts2[OutIdx/Ratio])
1826 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001828 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 // If there are more elements in the source than there are in the result,
1830 // then a result element is undef if all of the corresponding input
1831 // elements are undef.
1832 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1833 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001834 if (!UndefElts2[InIdx]) // Not undef?
1835 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001836 }
1837 break;
1838 }
1839 case Instruction::And:
1840 case Instruction::Or:
1841 case Instruction::Xor:
1842 case Instruction::Add:
1843 case Instruction::Sub:
1844 case Instruction::Mul:
1845 // div/rem demand all inputs, because they don't want divide by zero.
1846 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1847 UndefElts, Depth+1);
1848 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1849 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1850 UndefElts2, Depth+1);
1851 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1852
1853 // Output elements are undefined if both are undefined. Consider things
1854 // like undef&0. The result is known zero, not undef.
1855 UndefElts &= UndefElts2;
1856 break;
1857
1858 case Instruction::Call: {
1859 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1860 if (!II) break;
1861 switch (II->getIntrinsicID()) {
1862 default: break;
1863
1864 // Binary vector operations that work column-wise. A dest element is a
1865 // function of the corresponding input elements from the two inputs.
1866 case Intrinsic::x86_sse_sub_ss:
1867 case Intrinsic::x86_sse_mul_ss:
1868 case Intrinsic::x86_sse_min_ss:
1869 case Intrinsic::x86_sse_max_ss:
1870 case Intrinsic::x86_sse2_sub_sd:
1871 case Intrinsic::x86_sse2_mul_sd:
1872 case Intrinsic::x86_sse2_min_sd:
1873 case Intrinsic::x86_sse2_max_sd:
1874 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1875 UndefElts, Depth+1);
1876 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1877 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1880
1881 // If only the low elt is demanded and this is a scalarizable intrinsic,
1882 // scalarize it now.
1883 if (DemandedElts == 1) {
1884 switch (II->getIntrinsicID()) {
1885 default: break;
1886 case Intrinsic::x86_sse_sub_ss:
1887 case Intrinsic::x86_sse_mul_ss:
1888 case Intrinsic::x86_sse2_sub_sd:
1889 case Intrinsic::x86_sse2_mul_sd:
1890 // TODO: Lower MIN/MAX/ABS/etc
1891 Value *LHS = II->getOperand(1);
1892 Value *RHS = II->getOperand(2);
1893 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001894 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001895 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001896 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001897 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898
1899 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001900 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 case Intrinsic::x86_sse_sub_ss:
1902 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001903 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001904 II->getName()), *II);
1905 break;
1906 case Intrinsic::x86_sse_mul_ss:
1907 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001908 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909 II->getName()), *II);
1910 break;
1911 }
1912
1913 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001914 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001915 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001916 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001917 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001918 return New;
1919 }
1920 }
1921
1922 // Output elements are undefined if both are undefined. Consider things
1923 // like undef&0. The result is known zero, not undef.
1924 UndefElts &= UndefElts2;
1925 break;
1926 }
1927 break;
1928 }
1929 }
1930 return MadeChange ? I : 0;
1931}
1932
Dan Gohman5d56fd42008-05-19 22:14:15 +00001933
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001934/// AssociativeOpt - Perform an optimization on an associative operator. This
1935/// function is designed to check a chain of associative operators for a
1936/// potential to apply a certain optimization. Since the optimization may be
1937/// applicable if the expression was reassociated, this checks the chain, then
1938/// reassociates the expression as necessary to expose the optimization
1939/// opportunity. This makes use of a special Functor, which must define
1940/// 'shouldApply' and 'apply' methods.
1941///
1942template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001943static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001944 unsigned Opcode = Root.getOpcode();
1945 Value *LHS = Root.getOperand(0);
1946
1947 // Quick check, see if the immediate LHS matches...
1948 if (F.shouldApply(LHS))
1949 return F.apply(Root);
1950
1951 // Otherwise, if the LHS is not of the same opcode as the root, return.
1952 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1953 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1954 // Should we apply this transform to the RHS?
1955 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1956
1957 // If not to the RHS, check to see if we should apply to the LHS...
1958 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1959 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1960 ShouldApply = true;
1961 }
1962
1963 // If the functor wants to apply the optimization to the RHS of LHSI,
1964 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1965 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966 // Now all of the instructions are in the current basic block, go ahead
1967 // and perform the reassociation.
1968 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1969
1970 // First move the selected RHS to the LHS of the root...
1971 Root.setOperand(0, LHSI->getOperand(1));
1972
1973 // Make what used to be the LHS of the root be the user of the root...
1974 Value *ExtraOperand = TmpLHSI->getOperand(1);
1975 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001976 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 return 0;
1978 }
1979 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1980 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001981 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001982 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001983 ARI = Root;
1984
1985 // Now propagate the ExtraOperand down the chain of instructions until we
1986 // get to LHSI.
1987 while (TmpLHSI != LHSI) {
1988 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1989 // Move the instruction to immediately before the chain we are
1990 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001991 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 ARI = NextLHSI;
1993
1994 Value *NextOp = NextLHSI->getOperand(1);
1995 NextLHSI->setOperand(1, ExtraOperand);
1996 TmpLHSI = NextLHSI;
1997 ExtraOperand = NextOp;
1998 }
1999
2000 // Now that the instructions are reassociated, have the functor perform
2001 // the transformation...
2002 return F.apply(Root);
2003 }
2004
2005 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2006 }
2007 return 0;
2008}
2009
Dan Gohman089efff2008-05-13 00:00:25 +00002010namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002011
Nick Lewycky27f6c132008-05-23 04:34:58 +00002012// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013struct AddRHS {
2014 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00002015 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002016 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2017 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00002018 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00002019 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020 }
2021};
2022
2023// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2024// iff C1&C2 == 0
2025struct AddMaskingAnd {
2026 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00002027 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028 bool shouldApply(Value *LHS) const {
2029 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00002030 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002031 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032 }
2033 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002034 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002035 }
2036};
2037
Dan Gohman089efff2008-05-13 00:00:25 +00002038}
2039
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002040static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2041 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00002042 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00002043 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044
2045 // Figure out if the constant is the left or the right argument.
2046 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2047 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2048
2049 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2050 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00002051 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2052 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 }
2054
2055 Value *Op0 = SO, *Op1 = ConstOperand;
2056 if (!ConstIsRHS)
2057 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00002058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00002060 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2061 SO->getName()+".op");
2062 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2063 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2064 SO->getName()+".cmp");
2065 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2066 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067 SO->getName()+".cmp");
2068 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069}
2070
2071// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2072// constant as the other operand, try to fold the binary operator into the
2073// select arguments. This also works for Cast instructions, which obviously do
2074// not have a second operand.
2075static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2076 InstCombiner *IC) {
2077 // Don't modify shared select instructions
2078 if (!SI->hasOneUse()) return 0;
2079 Value *TV = SI->getOperand(1);
2080 Value *FV = SI->getOperand(2);
2081
2082 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2083 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00002084 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085
2086 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2087 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2088
Gabor Greifd6da1d02008-04-06 20:25:17 +00002089 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2090 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002091 }
2092 return 0;
2093}
2094
2095
Chris Lattnerf7843b72009-09-27 19:57:57 +00002096/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2097/// has a PHI node as operand #0, see if we can fold the instruction into the
2098/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00002099///
2100/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2101/// that would normally be unprofitable because they strongly encourage jump
2102/// threading.
2103Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2104 bool AllowAggressive) {
2105 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106 PHINode *PN = cast<PHINode>(I.getOperand(0));
2107 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002108 if (NumPHIValues == 0 ||
2109 // We normally only transform phis with a single use, unless we're trying
2110 // hard to make jump threading happen.
2111 (!PN->hasOneUse() && !AllowAggressive))
2112 return 0;
2113
2114
Chris Lattnerf7843b72009-09-27 19:57:57 +00002115 // Check to see if all of the operands of the PHI are simple constants
2116 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002117 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2118 // bail out. We don't do arbitrary constant expressions here because moving
2119 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002120 BasicBlock *NonConstBB = 0;
2121 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002122 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2123 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002124 if (NonConstBB) return 0; // More than one non-const value.
2125 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2126 NonConstBB = PN->getIncomingBlock(i);
2127
2128 // If the incoming non-constant value is in I's block, we have an infinite
2129 // loop.
2130 if (NonConstBB == I.getParent())
2131 return 0;
2132 }
2133
2134 // If there is exactly one non-constant value, we can insert a copy of the
2135 // operation in that block. However, if this is a critical edge, we would be
2136 // inserting the computation one some other paths (e.g. inside a loop). Only
2137 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002138 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002139 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2140 if (!BI || !BI->isUnconditional()) return 0;
2141 }
2142
2143 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002144 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002145 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002146 InsertNewInstBefore(NewPN, *PN);
2147 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148
2149 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002150 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2151 // We only currently try to fold the condition of a select when it is a phi,
2152 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002153 Value *TrueV = SI->getTrueValue();
2154 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002155 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002156 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002157 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002158 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2159 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002160 Value *InV = 0;
2161 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002162 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002163 } else {
2164 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002165 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2166 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002167 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002168 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002169 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002170 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002171 }
2172 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002173 Constant *C = cast<Constant>(I.getOperand(1));
2174 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002175 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2177 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002178 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002180 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 } else {
2182 assert(PN->getIncomingBlock(i) == NonConstBB);
2183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002184 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185 PN->getIncomingValue(i), C, "phitmp",
2186 NonConstBB->getTerminator());
2187 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002188 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 CI->getPredicate(),
2190 PN->getIncomingValue(i), C, "phitmp",
2191 NonConstBB->getTerminator());
2192 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002193 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002194
2195 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 }
2197 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2198 }
2199 } else {
2200 CastInst *CI = cast<CastInst>(&I);
2201 const Type *RetTy = CI->getType();
2202 for (unsigned i = 0; i != NumPHIValues; ++i) {
2203 Value *InV;
2204 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002205 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206 } else {
2207 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002208 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 I.getType(), "phitmp",
2210 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002211 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002212 }
2213 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2214 }
2215 }
2216 return ReplaceInstUsesWith(I, NewPN);
2217}
2218
Chris Lattner55476162008-01-29 06:52:45 +00002219
Chris Lattner3554f972008-05-20 05:46:13 +00002220/// WillNotOverflowSignedAdd - Return true if we can prove that:
2221/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2222/// This basically requires proving that the add in the original type would not
2223/// overflow to change the sign bit or have a carry out.
2224bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2225 // There are different heuristics we can use for this. Here are some simple
2226 // ones.
2227
2228 // Add has the property that adding any two 2's complement numbers can only
2229 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner96076f72009-11-27 17:42:22 +00002230 // have at least two sign bits, we know that the addition of the two values
2231 // will sign extend fine.
Chris Lattner3554f972008-05-20 05:46:13 +00002232 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2233 return true;
2234
2235
2236 // If one of the operands only has one non-zero bit, and if the other operand
2237 // has a known-zero bit in a more significant place than it (not including the
2238 // sign bit) the ripple may go up to and fill the zero, but won't change the
2239 // sign. For example, (X & ~4) + 1.
2240
2241 // TODO: Implement.
2242
2243 return false;
2244}
2245
Chris Lattner55476162008-01-29 06:52:45 +00002246
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2248 bool Changed = SimplifyCommutative(I);
2249 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2250
Chris Lattner96076f72009-11-27 17:42:22 +00002251 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2252 I.hasNoUnsignedWrap(), TD))
2253 return ReplaceInstUsesWith(I, V);
2254
2255
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2258 // X + (signbit) --> X ^ signbit
2259 const APInt& Val = CI->getValue();
2260 uint32_t BitWidth = Val.getBitWidth();
2261 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002262 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263
2264 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2265 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002266 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002267 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002268
Eli Friedmana21526d2009-07-13 22:27:52 +00002269 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002270 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002271 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002272 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002273 }
2274
2275 if (isa<PHINode>(LHS))
2276 if (Instruction *NV = FoldOpIntoPhi(I))
2277 return NV;
2278
2279 ConstantInt *XorRHS = 0;
2280 Value *XorLHS = 0;
2281 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002282 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002283 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2285
2286 uint32_t Size = TySizeBits / 2;
2287 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2288 APInt CFF80Val(-C0080Val);
2289 do {
2290 if (TySizeBits > Size) {
2291 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2292 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2293 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2294 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2295 // This is a sign extend if the top bits are known zero.
2296 if (!MaskedValueIsZero(XorLHS,
2297 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2298 Size = 0; // Not a sign ext, but can't be any others either.
2299 break;
2300 }
2301 }
2302 Size >>= 1;
2303 C0080Val = APIntOps::lshr(C0080Val, Size);
2304 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2305 } while (Size >= 1);
2306
2307 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002308 // with funny bit widths then this switch statement should be removed. It
2309 // is just here to get the size of the "middle" type back up to something
2310 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311 const Type *MiddleType = 0;
2312 switch (Size) {
2313 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002314 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2315 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2316 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002317 }
2318 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002319 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320 return new SExtInst(NewTrunc, I.getType(), I.getName());
2321 }
2322 }
2323 }
2324
Owen Anderson35b47072009-08-13 21:58:54 +00002325 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002326 return BinaryOperator::CreateXor(LHS, RHS);
2327
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002328 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002329 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002330 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002331 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332
2333 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2334 if (RHSI->getOpcode() == Instruction::Sub)
2335 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2336 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2337 }
2338 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2339 if (LHSI->getOpcode() == Instruction::Sub)
2340 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2341 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2342 }
2343 }
2344
2345 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002346 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002347 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002348 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002349 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002350 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002351 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002352 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002353 }
2354
Gabor Greifa645dd32008-05-16 19:29:10 +00002355 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002356 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357
2358 // A + -B --> A - B
2359 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002360 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002361 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002362
2363
2364 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002365 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002367 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368
2369 // X*C1 + X*C2 --> X * (C1+C2)
2370 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002371 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002372 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002373 }
2374
2375 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002376 if (dyn_castFoldableMul(RHS, C2) == LHS)
2377 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002378
2379 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002380 if (dyn_castNotVal(LHS) == RHS ||
2381 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002382 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002383
2384
2385 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002386 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2387 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002388 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002389
2390 // A+B --> A|B iff A and B have no bits set in common.
2391 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2392 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2393 APInt LHSKnownOne(IT->getBitWidth(), 0);
2394 APInt LHSKnownZero(IT->getBitWidth(), 0);
2395 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2396 if (LHSKnownZero != 0) {
2397 APInt RHSKnownOne(IT->getBitWidth(), 0);
2398 APInt RHSKnownZero(IT->getBitWidth(), 0);
2399 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2400
2401 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002402 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002403 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002404 }
2405 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002406
Nick Lewycky83598a72008-02-03 07:42:09 +00002407 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002408 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002409 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002410 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2411 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002412 if (W != Y) {
2413 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002414 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002415 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002416 std::swap(W, X);
2417 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002418 std::swap(Y, Z);
2419 std::swap(W, X);
2420 }
2421 }
2422
2423 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002424 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002425 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002426 }
2427 }
2428 }
2429
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002430 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2431 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002432 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002433 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434
2435 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002436 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002437 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002438 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002439 if (Anded == CRHS) {
2440 // See if all bits from the first bit set in the Add RHS up are included
2441 // in the mask. First, get the rightmost bit.
2442 const APInt& AddRHSV = CRHS->getValue();
2443
2444 // Form a mask of all bits from the lowest bit added through the top.
2445 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2446
2447 // See if the and mask includes all of these bits.
2448 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2449
2450 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2451 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002452 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002453 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454 }
2455 }
2456 }
2457
2458 // Try to fold constant add into select arguments.
2459 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2460 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2461 return R;
2462 }
2463
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002464 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002465 {
2466 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002467 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002468 if (!SI) {
2469 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002470 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002471 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002472 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002473 Value *TV = SI->getTrueValue();
2474 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002475 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002476
2477 // Can we fold the add into the argument of the select?
2478 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002479 if (match(FV, m_Zero()) &&
2480 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002481 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002482 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002483 if (match(TV, m_Zero()) &&
2484 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002485 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002486 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002487 }
2488 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489
Chris Lattner3554f972008-05-20 05:46:13 +00002490 // Check for (add (sext x), y), see if we can merge this into an
2491 // integer add followed by a sext.
2492 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2493 // (add (sext x), cst) --> (sext (add x, cst'))
2494 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2495 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002496 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002497 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002498 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002499 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2500 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002501 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2502 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002503 return new SExtInst(NewAdd, I.getType());
2504 }
2505 }
2506
2507 // (add (sext x), (sext y)) --> (sext (add int x, y))
2508 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2509 // Only do this if x/y have the same type, if at last one of them has a
2510 // single use (so we don't increase the number of sexts), and if the
2511 // integer add will not overflow.
2512 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2513 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2514 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2515 RHSConv->getOperand(0))) {
2516 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002517 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2518 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002519 return new SExtInst(NewAdd, I.getType());
2520 }
2521 }
2522 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002523
2524 return Changed ? &I : 0;
2525}
2526
2527Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2528 bool Changed = SimplifyCommutative(I);
2529 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2530
2531 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2532 // X + 0 --> X
2533 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002534 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002535 (I.getType())->getValueAPF()))
2536 return ReplaceInstUsesWith(I, LHS);
2537 }
2538
2539 if (isa<PHINode>(LHS))
2540 if (Instruction *NV = FoldOpIntoPhi(I))
2541 return NV;
2542 }
2543
2544 // -A + B --> B - A
2545 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002546 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002547 return BinaryOperator::CreateFSub(RHS, LHSV);
2548
2549 // A + -B --> A - B
2550 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002551 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002552 return BinaryOperator::CreateFSub(LHS, V);
2553
2554 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2555 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2556 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2557 return ReplaceInstUsesWith(I, LHS);
2558
Chris Lattner3554f972008-05-20 05:46:13 +00002559 // Check for (add double (sitofp x), y), see if we can merge this into an
2560 // integer add followed by a promotion.
2561 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2562 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2563 // ... if the constant fits in the integer value. This is useful for things
2564 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2565 // requires a constant pool load, and generally allows the add to be better
2566 // instcombined.
2567 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2568 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002569 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002570 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002571 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002572 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2573 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002574 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2575 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002576 return new SIToFPInst(NewAdd, I.getType());
2577 }
2578 }
2579
2580 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2581 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2582 // Only do this if x/y have the same type, if at last one of them has a
2583 // single use (so we don't increase the number of int->fp conversions),
2584 // and if the integer add will not overflow.
2585 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2586 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2587 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2588 RHSConv->getOperand(0))) {
2589 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002590 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +00002591 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002592 return new SIToFPInst(NewAdd, I.getType());
2593 }
2594 }
2595 }
2596
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002597 return Changed ? &I : 0;
2598}
2599
Chris Lattner93e6ff92009-11-04 08:05:20 +00002600
2601/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2602/// code necessary to compute the offset from the base pointer (without adding
2603/// in the base pointer). Return the result as a signed integer of intptr size.
2604static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2605 TargetData &TD = *IC.getTargetData();
2606 gep_type_iterator GTI = gep_type_begin(GEP);
2607 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2608 Value *Result = Constant::getNullValue(IntPtrTy);
2609
2610 // Build a mask for high order bits.
2611 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2612 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2613
2614 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2615 ++i, ++GTI) {
2616 Value *Op = *i;
2617 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2618 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2619 if (OpC->isZero()) continue;
2620
2621 // Handle a struct index, which adds its field offset to the pointer.
2622 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2623 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2624
2625 Result = IC.Builder->CreateAdd(Result,
2626 ConstantInt::get(IntPtrTy, Size),
2627 GEP->getName()+".offs");
2628 continue;
2629 }
2630
2631 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2632 Constant *OC =
2633 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2634 Scale = ConstantExpr::getMul(OC, Scale);
2635 // Emit an add instruction.
2636 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2637 continue;
2638 }
2639 // Convert to correct type.
2640 if (Op->getType() != IntPtrTy)
2641 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2642 if (Size != 1) {
2643 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2644 // We'll let instcombine(mul) convert this to a shl if possible.
2645 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2646 }
2647
2648 // Emit an add instruction.
2649 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2650 }
2651 return Result;
2652}
2653
2654
2655/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2656/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2657/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2658/// be complex, and scales are involved. The above expression would also be
2659/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2660/// This later form is less amenable to optimization though, and we are allowed
2661/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2662///
2663/// If we can't emit an optimized form for this expression, this returns null.
2664///
2665static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2666 InstCombiner &IC) {
2667 TargetData &TD = *IC.getTargetData();
2668 gep_type_iterator GTI = gep_type_begin(GEP);
2669
2670 // Check to see if this gep only has a single variable index. If so, and if
2671 // any constant indices are a multiple of its scale, then we can compute this
2672 // in terms of the scale of the variable index. For example, if the GEP
2673 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2674 // because the expression will cross zero at the same point.
2675 unsigned i, e = GEP->getNumOperands();
2676 int64_t Offset = 0;
2677 for (i = 1; i != e; ++i, ++GTI) {
2678 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2679 // Compute the aggregate offset of constant indices.
2680 if (CI->isZero()) continue;
2681
2682 // Handle a struct index, which adds its field offset to the pointer.
2683 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2684 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2685 } else {
2686 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2687 Offset += Size*CI->getSExtValue();
2688 }
2689 } else {
2690 // Found our variable index.
2691 break;
2692 }
2693 }
2694
2695 // If there are no variable indices, we must have a constant offset, just
2696 // evaluate it the general way.
2697 if (i == e) return 0;
2698
2699 Value *VariableIdx = GEP->getOperand(i);
2700 // Determine the scale factor of the variable element. For example, this is
2701 // 4 if the variable index is into an array of i32.
2702 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2703
2704 // Verify that there are no other variable indices. If so, emit the hard way.
2705 for (++i, ++GTI; i != e; ++i, ++GTI) {
2706 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2707 if (!CI) return 0;
2708
2709 // Compute the aggregate offset of constant indices.
2710 if (CI->isZero()) continue;
2711
2712 // Handle a struct index, which adds its field offset to the pointer.
2713 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2714 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2715 } else {
2716 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2717 Offset += Size*CI->getSExtValue();
2718 }
2719 }
2720
2721 // Okay, we know we have a single variable index, which must be a
2722 // pointer/array/vector index. If there is no offset, life is simple, return
2723 // the index.
2724 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2725 if (Offset == 0) {
2726 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2727 // we don't need to bother extending: the extension won't affect where the
2728 // computation crosses zero.
2729 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2730 VariableIdx = new TruncInst(VariableIdx,
2731 TD.getIntPtrType(VariableIdx->getContext()),
2732 VariableIdx->getName(), &I);
2733 return VariableIdx;
2734 }
2735
2736 // Otherwise, there is an index. The computation we will do will be modulo
2737 // the pointer size, so get it.
2738 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2739
2740 Offset &= PtrSizeMask;
2741 VariableScale &= PtrSizeMask;
2742
2743 // To do this transformation, any constant index must be a multiple of the
2744 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2745 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2746 // multiple of the variable scale.
2747 int64_t NewOffs = Offset / (int64_t)VariableScale;
2748 if (Offset != NewOffs*(int64_t)VariableScale)
2749 return 0;
2750
2751 // Okay, we can do this evaluation. Start by converting the index to intptr.
2752 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2753 if (VariableIdx->getType() != IntPtrTy)
2754 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2755 true /*SExt*/,
2756 VariableIdx->getName(), &I);
2757 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2758 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2759}
2760
2761
2762/// Optimize pointer differences into the same array into a size. Consider:
2763/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2764/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2765///
2766Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2767 const Type *Ty) {
2768 assert(TD && "Must have target data info for this");
2769
2770 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2771 // this.
2772 bool Swapped;
2773 GetElementPtrInst *GEP;
2774
2775 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2776 GEP->getOperand(0) == RHS)
2777 Swapped = false;
2778 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2779 GEP->getOperand(0) == LHS)
2780 Swapped = true;
2781 else
2782 return 0;
2783
2784 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2785
2786 // Emit the offset of the GEP and an intptr_t.
2787 Value *Result = EmitGEPOffset(GEP, *this);
2788
2789 // If we have p - gep(p, ...) then we have to negate the result.
2790 if (Swapped)
2791 Result = Builder->CreateNeg(Result, "diff.neg");
2792
2793 return Builder->CreateIntCast(Result, Ty, true);
2794}
2795
2796
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2798 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2799
Dan Gohman7ce405e2009-06-04 22:49:04 +00002800 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002801 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802
Chris Lattnera54b96b2009-12-21 04:04:05 +00002803 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2804 if (Value *V = dyn_castNegVal(Op1)) {
2805 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2806 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2807 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2808 return Res;
2809 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002810
2811 if (isa<UndefValue>(Op0))
2812 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2813 if (isa<UndefValue>(Op1))
2814 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner93e6ff92009-11-04 08:05:20 +00002815 if (I.getType() == Type::getInt1Ty(*Context))
2816 return BinaryOperator::CreateXor(Op0, Op1);
2817
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002818 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00002819 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002820 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002821 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822
2823 // C - ~X == X + (1+C)
2824 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002825 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002826 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002827
2828 // -(X >>u 31) -> (X >>s 31)
2829 // -(X >>s 31) -> (X >>u 31)
2830 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002831 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002832 if (SI->getOpcode() == Instruction::LShr) {
2833 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2834 // Check to see if we are shifting out everything but the sign bit.
2835 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2836 SI->getType()->getPrimitiveSizeInBits()-1) {
2837 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002838 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839 SI->getOperand(0), CU, SI->getName());
2840 }
2841 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002842 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002843 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2844 // Check to see if we are shifting out everything but the sign bit.
2845 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2846 SI->getType()->getPrimitiveSizeInBits()-1) {
2847 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002848 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 SI->getOperand(0), CU, SI->getName());
2850 }
2851 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002852 }
2853 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002854 }
2855
2856 // Try to fold constant sub into select arguments.
2857 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2858 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2859 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002860
2861 // C - zext(bool) -> bool ? C - 1 : C
2862 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002863 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002864 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002865 }
2866
2867 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002868 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002870 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002871 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002872 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002873 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002874 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002875 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2876 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2877 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002878 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002879 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002880 }
2881 }
2882
2883 if (Op1I->hasOneUse()) {
2884 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2885 // is not used by anyone else...
2886 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002887 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 // Swap the two operands of the subexpr...
2889 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2890 Op1I->setOperand(0, IIOp1);
2891 Op1I->setOperand(1, IIOp0);
2892
2893 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002894 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895 }
2896
2897 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2898 //
2899 if (Op1I->getOpcode() == Instruction::And &&
2900 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2901 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2902
Chris Lattnerc7694852009-08-30 07:44:24 +00002903 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002904 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 }
2906
2907 // 0 - (X sdiv C) -> (X sdiv -C)
2908 if (Op1I->getOpcode() == Instruction::SDiv)
2909 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2910 if (CSI->isZero())
2911 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002913 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002914
2915 // X - X*C --> X * (1-C)
2916 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002917 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002918 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002919 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002920 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002921 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922 }
2923 }
2924 }
2925
Dan Gohman7ce405e2009-06-04 22:49:04 +00002926 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2927 if (Op0I->getOpcode() == Instruction::Add) {
2928 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2929 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2930 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2931 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2932 } else if (Op0I->getOpcode() == Instruction::Sub) {
2933 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002934 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002935 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002936 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002937 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002938
2939 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002940 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002941 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002942 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943
2944 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002945 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002946 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002948
2949 // Optimize pointer differences into the same array into a size. Consider:
2950 // &A[10] - &A[0]: we should compile this to "10".
2951 if (TD) {
Chris Lattnerc49d68a2010-01-01 22:12:03 +00002952 Value *LHSOp, *RHSOp;
Chris Lattnerc93843f2010-01-01 22:29:12 +00002953 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2954 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattnerc49d68a2010-01-01 22:12:03 +00002955 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2956 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00002957
2958 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerc93843f2010-01-01 22:29:12 +00002959 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2960 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2961 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2962 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00002963 }
2964
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002965 return 0;
2966}
2967
Dan Gohman7ce405e2009-06-04 22:49:04 +00002968Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2970
2971 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002972 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002973 return BinaryOperator::CreateFAdd(Op0, V);
2974
2975 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2976 if (Op1I->getOpcode() == Instruction::FAdd) {
2977 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002978 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002979 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002980 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002981 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002982 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002983 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002984 }
2985
2986 return 0;
2987}
2988
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2990/// comparison only checks the sign bit. If it only checks the sign bit, set
2991/// TrueIfSigned if the result of the comparison is true when the input value is
2992/// signed.
2993static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2994 bool &TrueIfSigned) {
2995 switch (pred) {
2996 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2997 TrueIfSigned = true;
2998 return RHS->isZero();
2999 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3000 TrueIfSigned = true;
3001 return RHS->isAllOnesValue();
3002 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3003 TrueIfSigned = false;
3004 return RHS->isAllOnesValue();
3005 case ICmpInst::ICMP_UGT:
3006 // True if LHS u> RHS and RHS == high-bit-mask - 1
3007 TrueIfSigned = true;
3008 return RHS->getValue() ==
3009 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3010 case ICmpInst::ICMP_UGE:
3011 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3012 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00003013 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003014 default:
3015 return false;
3016 }
3017}
3018
3019Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3020 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022
Chris Lattner3508c5c2009-10-11 21:36:10 +00003023 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00003024 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025
Chris Lattner6438c582009-10-11 07:53:15 +00003026 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003027 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029
3030 // ((X << C1)*C2) == (X * (C2 << C1))
3031 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3032 if (SI->getOpcode() == Instruction::Shl)
3033 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003035 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036
3037 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00003038 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039 if (CI->equalsInt(1)) // X * 1 == X
3040 return ReplaceInstUsesWith(I, Op0);
3041 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00003042 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043
3044 const APInt& Val = cast<ConstantInt>(CI)->getValue();
3045 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00003046 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003047 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003048 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003049 } else if (isa<VectorType>(Op1C->getType())) {
3050 if (Op1C->isNullValue())
3051 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00003052
Chris Lattner3508c5c2009-10-11 21:36:10 +00003053 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00003054 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00003055 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00003056
3057 // As above, vector X*splat(1.0) -> X in all defined cases.
3058 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00003059 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3060 if (CI->equalsInt(1))
3061 return ReplaceInstUsesWith(I, Op0);
3062 }
3063 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003064 }
3065
3066 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3067 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003068 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003069 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003070 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3071 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003072 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003073
3074 }
3075
3076 // Try to fold constant mul into select arguments.
3077 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3078 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3079 return R;
3080
3081 if (isa<PHINode>(Op0))
3082 if (Instruction *NV = FoldOpIntoPhi(I))
3083 return NV;
3084 }
3085
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003086 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003087 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00003088 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089
Nick Lewycky1c246402008-11-21 07:33:58 +00003090 // (X / Y) * Y = X - (X % Y)
3091 // (X / Y) * -Y = (X % Y) - X
3092 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003093 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00003094 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3095 if (!BO ||
3096 (BO->getOpcode() != Instruction::UDiv &&
3097 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003098 Op1C = Op0;
3099 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00003100 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003101 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00003102 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003103 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00003104 (BO->getOpcode() == Instruction::UDiv ||
3105 BO->getOpcode() == Instruction::SDiv)) {
3106 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3107
Dan Gohman07878902009-08-12 16:33:09 +00003108 // If the division is exact, X % Y is zero.
3109 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3110 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003111 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00003112 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003113 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00003114 }
3115
Chris Lattnerc7694852009-08-30 07:44:24 +00003116 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00003117 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00003118 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003119 else
Chris Lattnerc7694852009-08-30 07:44:24 +00003120 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003121 Rem->takeName(BO);
3122
Chris Lattner3508c5c2009-10-11 21:36:10 +00003123 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00003124 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00003125 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003126 }
3127 }
3128
Chris Lattner6438c582009-10-11 07:53:15 +00003129 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00003130 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003131 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003132
Chris Lattner6438c582009-10-11 07:53:15 +00003133 // X*(1 << Y) --> X << Y
3134 // (1 << Y)*X --> X << Y
3135 {
3136 Value *Y;
3137 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003138 return BinaryOperator::CreateShl(Op1, Y);
3139 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00003140 return BinaryOperator::CreateShl(Op0, Y);
3141 }
3142
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143 // If one of the operands of the multiply is a cast from a boolean value, then
3144 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00003145 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3146 if (!isa<VectorType>(I.getType())) {
3147 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00003148 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00003149
Chris Lattner4ca76f72009-10-11 21:29:45 +00003150 Value *BoolCast = 0, *OtherOp = 0;
3151 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003152 BoolCast = Op0, OtherOp = Op1;
3153 else if (MaskedValueIsZero(Op1, Negative2))
3154 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00003155
Chris Lattner291872e2009-10-11 21:22:21 +00003156 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00003157 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3158 BoolCast, "tmp");
3159 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160 }
3161 }
3162
3163 return Changed ? &I : 0;
3164}
3165
Dan Gohman7ce405e2009-06-04 22:49:04 +00003166Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3167 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003168 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00003169
3170 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00003171 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3172 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003173 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3174 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3175 if (Op1F->isExactlyValue(1.0))
3176 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00003177 } else if (isa<VectorType>(Op1C->getType())) {
3178 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003179 // As above, vector X*splat(1.0) -> X in all defined cases.
3180 if (Constant *Splat = Op1V->getSplatValue()) {
3181 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3182 if (F->isExactlyValue(1.0))
3183 return ReplaceInstUsesWith(I, Op0);
3184 }
3185 }
3186 }
3187
3188 // Try to fold constant mul into select arguments.
3189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3191 return R;
3192
3193 if (isa<PHINode>(Op0))
3194 if (Instruction *NV = FoldOpIntoPhi(I))
3195 return NV;
3196 }
3197
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003198 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003199 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003200 return BinaryOperator::CreateFMul(Op0v, Op1v);
3201
3202 return Changed ? &I : 0;
3203}
3204
Chris Lattner76972db2008-07-14 00:15:52 +00003205/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3206/// instruction.
3207bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3208 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3209
3210 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3211 int NonNullOperand = -1;
3212 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3213 if (ST->isNullValue())
3214 NonNullOperand = 2;
3215 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3216 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3217 if (ST->isNullValue())
3218 NonNullOperand = 1;
3219
3220 if (NonNullOperand == -1)
3221 return false;
3222
3223 Value *SelectCond = SI->getOperand(0);
3224
3225 // Change the div/rem to use 'Y' instead of the select.
3226 I.setOperand(1, SI->getOperand(NonNullOperand));
3227
3228 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3229 // problem. However, the select, or the condition of the select may have
3230 // multiple uses. Based on our knowledge that the operand must be non-zero,
3231 // propagate the known value for the select into other uses of it, and
3232 // propagate a known value of the condition into its other users.
3233
3234 // If the select and condition only have a single use, don't bother with this,
3235 // early exit.
3236 if (SI->use_empty() && SelectCond->hasOneUse())
3237 return true;
3238
3239 // Scan the current block backward, looking for other uses of SI.
3240 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3241
3242 while (BBI != BBFront) {
3243 --BBI;
3244 // If we found a call to a function, we can't assume it will return, so
3245 // information from below it cannot be propagated above it.
3246 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3247 break;
3248
3249 // Replace uses of the select or its condition with the known values.
3250 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3251 I != E; ++I) {
3252 if (*I == SI) {
3253 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00003254 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003255 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00003256 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3257 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00003258 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003259 }
3260 }
3261
3262 // If we past the instruction, quit looking for it.
3263 if (&*BBI == SI)
3264 SI = 0;
3265 if (&*BBI == SelectCond)
3266 SelectCond = 0;
3267
3268 // If we ran out of things to eliminate, break out of the loop.
3269 if (SelectCond == 0 && SI == 0)
3270 break;
3271
3272 }
3273 return true;
3274}
3275
3276
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003277/// This function implements the transforms on div instructions that work
3278/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3279/// used by the visitors to those instructions.
3280/// @brief Transforms common to all three div instructions
3281Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3283
Chris Lattner653ef3c2008-02-19 06:12:18 +00003284 // undef / X -> 0 for integer.
3285 // undef / X -> undef for FP (the undef could be a snan).
3286 if (isa<UndefValue>(Op0)) {
3287 if (Op0->getType()->isFPOrFPVector())
3288 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00003289 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003291
3292 // X / undef -> undef
3293 if (isa<UndefValue>(Op1))
3294 return ReplaceInstUsesWith(I, Op1);
3295
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296 return 0;
3297}
3298
3299/// This function implements the transforms common to both integer division
3300/// instructions (udiv and sdiv). It is called by the visitors to those integer
3301/// division instructions.
3302/// @brief Common integer divide transforms
3303Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3304 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3305
Chris Lattnercefb36c2008-05-16 02:59:42 +00003306 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003307 if (Op0 == Op1) {
3308 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003309 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003310 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003311 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003312 }
3313
Owen Andersoneacb44d2009-07-24 23:12:02 +00003314 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003315 return ReplaceInstUsesWith(I, CI);
3316 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318 if (Instruction *Common = commonDivTransforms(I))
3319 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003320
3321 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3322 // This does not apply for fdiv.
3323 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3324 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003325
3326 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3327 // div X, 1 == X
3328 if (RHS->equalsInt(1))
3329 return ReplaceInstUsesWith(I, Op0);
3330
3331 // (X / C1) / C2 -> X / (C1*C2)
3332 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3333 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3334 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003335 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003336 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003338 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003339 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003340 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003341 }
3342
3343 if (!RHS->isZero()) { // avoid X udiv 0
3344 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3345 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3346 return R;
3347 if (isa<PHINode>(Op0))
3348 if (Instruction *NV = FoldOpIntoPhi(I))
3349 return NV;
3350 }
3351 }
3352
3353 // 0 / X == 0, we don't need to preserve faults!
3354 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3355 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003356 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003358 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003359 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003360 return ReplaceInstUsesWith(I, Op0);
3361
Nick Lewycky94418732008-11-27 20:21:08 +00003362 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3363 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3364 // div X, 1 == X
3365 if (X->isOne())
3366 return ReplaceInstUsesWith(I, Op0);
3367 }
3368
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369 return 0;
3370}
3371
3372Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3374
3375 // Handle the integer div common cases
3376 if (Instruction *Common = commonIDivTransforms(I))
3377 return Common;
3378
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003380 // X udiv C^2 -> X >> C
3381 // Check to see if this is an unsigned division with an exact power of 2,
3382 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003383 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003384 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003385 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003386
3387 // X udiv C, where C >= signbit
3388 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003389 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003390 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003391 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003392 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393 }
3394
3395 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3396 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3397 if (RHSI->getOpcode() == Instruction::Shl &&
3398 isa<ConstantInt>(RHSI->getOperand(0))) {
3399 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3400 if (C1.isPowerOf2()) {
3401 Value *N = RHSI->getOperand(1);
3402 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003403 if (uint32_t C2 = C1.logBase2())
3404 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003405 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 }
3407 }
3408 }
3409
3410 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3411 // where C1&C2 are powers of two.
3412 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3413 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3414 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3415 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3416 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3417 // Compute the shift amounts
3418 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3419 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003420 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003421 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422
3423 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003424 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003425 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003426
3427 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003428 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429 }
3430 }
3431 return 0;
3432}
3433
3434Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3436
3437 // Handle the integer div common cases
3438 if (Instruction *Common = commonIDivTransforms(I))
3439 return Common;
3440
3441 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3442 // sdiv X, -1 == -X
3443 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003444 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003445
Dan Gohman07878902009-08-12 16:33:09 +00003446 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003447 if (cast<SDivOperator>(&I)->isExact() &&
3448 RHS->getValue().isNonNegative() &&
3449 RHS->getValue().isPowerOf2()) {
3450 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3451 RHS->getValue().exactLogBase2());
3452 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3453 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003454
3455 // -X/C --> X/-C provided the negation doesn't overflow.
3456 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3457 if (isa<Constant>(Sub->getOperand(0)) &&
3458 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003459 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003460 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3461 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003462 }
3463
3464 // If the sign bits of both operands are zero (i.e. we can prove they are
3465 // unsigned inputs), turn this into a udiv.
3466 if (I.getType()->isInteger()) {
3467 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003468 if (MaskedValueIsZero(Op0, Mask)) {
3469 if (MaskedValueIsZero(Op1, Mask)) {
3470 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3471 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3472 }
3473 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003474 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003475 ShiftedInt->getValue().isPowerOf2()) {
3476 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3477 // Safe because the only negative value (1 << Y) can take on is
3478 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3479 // the sign bit set.
3480 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3481 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003482 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003483 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484
3485 return 0;
3486}
3487
3488Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3489 return commonDivTransforms(I);
3490}
3491
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003492/// This function implements the transforms on rem instructions that work
3493/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3494/// is used by the visitors to those instructions.
3495/// @brief Transforms common to all three rem instructions
3496Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3497 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3498
Chris Lattner653ef3c2008-02-19 06:12:18 +00003499 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3500 if (I.getType()->isFPOrFPVector())
3501 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003502 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003503 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003504 if (isa<UndefValue>(Op1))
3505 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3506
3507 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003508 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3509 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003510
3511 return 0;
3512}
3513
3514/// This function implements the transforms common to both integer remainder
3515/// instructions (urem and srem). It is called by the visitors to those integer
3516/// remainder instructions.
3517/// @brief Common integer remainder transforms
3518Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3519 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3520
3521 if (Instruction *common = commonRemTransforms(I))
3522 return common;
3523
Dale Johannesena51f7372009-01-21 00:35:19 +00003524 // 0 % X == 0 for integer, we don't need to preserve faults!
3525 if (Constant *LHS = dyn_cast<Constant>(Op0))
3526 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003527 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003528
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3530 // X % 0 == undef, we don't need to preserve faults!
3531 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003532 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533
3534 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536
3537 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3538 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3539 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3540 return R;
3541 } else if (isa<PHINode>(Op0I)) {
3542 if (Instruction *NV = FoldOpIntoPhi(I))
3543 return NV;
3544 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003545
3546 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003547 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003548 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 }
3550 }
3551
3552 return 0;
3553}
3554
3555Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3557
3558 if (Instruction *common = commonIRemTransforms(I))
3559 return common;
3560
3561 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3562 // X urem C^2 -> X and C
3563 // Check to see if this is an unsigned remainder with an exact power of 2,
3564 // if so, convert to a bitwise and.
3565 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3566 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003567 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003568 }
3569
3570 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3571 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3572 if (RHSI->getOpcode() == Instruction::Shl &&
3573 isa<ConstantInt>(RHSI->getOperand(0))) {
3574 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003575 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003576 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003577 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 }
3579 }
3580 }
3581
3582 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3583 // where C1&C2 are powers of two.
3584 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3585 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3586 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3587 // STO == 0 and SFO == 0 handled above.
3588 if ((STO->getValue().isPowerOf2()) &&
3589 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003590 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3591 SI->getName()+".t");
3592 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3593 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003594 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003595 }
3596 }
3597 }
3598
3599 return 0;
3600}
3601
3602Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3603 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3604
Dan Gohmandb3dd962007-11-05 23:16:33 +00003605 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003606 if (Instruction *Common = commonIRemTransforms(I))
3607 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003609 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003610 if (!isa<Constant>(RHSNeg) ||
3611 (isa<ConstantInt>(RHSNeg) &&
3612 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003613 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003614 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003615 I.setOperand(1, RHSNeg);
3616 return &I;
3617 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003618
Dan Gohmandb3dd962007-11-05 23:16:33 +00003619 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003620 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003621 if (I.getType()->isInteger()) {
3622 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3623 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3624 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003625 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003626 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003627 }
3628
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003629 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003630 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3631 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003632
Nick Lewyckyfd746832008-12-20 16:48:00 +00003633 bool hasNegative = false;
3634 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3635 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3636 if (RHS->getValue().isNegative())
3637 hasNegative = true;
3638
3639 if (hasNegative) {
3640 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003641 for (unsigned i = 0; i != VWidth; ++i) {
3642 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3643 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003644 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003645 else
3646 Elts[i] = RHS;
3647 }
3648 }
3649
Owen Anderson2f422e02009-07-28 21:19:26 +00003650 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003651 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003652 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003653 I.setOperand(1, NewRHSV);
3654 return &I;
3655 }
3656 }
3657 }
3658
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659 return 0;
3660}
3661
3662Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3663 return commonRemTransforms(I);
3664}
3665
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003666// isOneBitSet - Return true if there is exactly one bit set in the specified
3667// constant.
3668static bool isOneBitSet(const ConstantInt *CI) {
3669 return CI->getValue().isPowerOf2();
3670}
3671
3672// isHighOnes - Return true if the constant is of the form 1+0+.
3673// This is the same as lowones(~X).
3674static bool isHighOnes(const ConstantInt *CI) {
3675 return (~CI->getValue() + 1).isPowerOf2();
3676}
3677
3678/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3679/// are carefully arranged to allow folding of expressions such as:
3680///
3681/// (A < B) | (A > B) --> (A != B)
3682///
3683/// Note that this is only valid if the first and second predicates have the
3684/// same sign. Is illegal to do: (A u< B) | (A s> B)
3685///
3686/// Three bits are used to represent the condition, as follows:
3687/// 0 A > B
3688/// 1 A == B
3689/// 2 A < B
3690///
3691/// <=> Value Definition
3692/// 000 0 Always false
3693/// 001 1 A > B
3694/// 010 2 A == B
3695/// 011 3 A >= B
3696/// 100 4 A < B
3697/// 101 5 A != B
3698/// 110 6 A <= B
3699/// 111 7 Always true
3700///
3701static unsigned getICmpCode(const ICmpInst *ICI) {
3702 switch (ICI->getPredicate()) {
3703 // False -> 0
3704 case ICmpInst::ICMP_UGT: return 1; // 001
3705 case ICmpInst::ICMP_SGT: return 1; // 001
3706 case ICmpInst::ICMP_EQ: return 2; // 010
3707 case ICmpInst::ICMP_UGE: return 3; // 011
3708 case ICmpInst::ICMP_SGE: return 3; // 011
3709 case ICmpInst::ICMP_ULT: return 4; // 100
3710 case ICmpInst::ICMP_SLT: return 4; // 100
3711 case ICmpInst::ICMP_NE: return 5; // 101
3712 case ICmpInst::ICMP_ULE: return 6; // 110
3713 case ICmpInst::ICMP_SLE: return 6; // 110
3714 // True -> 7
3715 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003716 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003717 return 0;
3718 }
3719}
3720
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003721/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3722/// predicate into a three bit mask. It also returns whether it is an ordered
3723/// predicate by reference.
3724static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3725 isOrdered = false;
3726 switch (CC) {
3727 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3728 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003729 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3730 case FCmpInst::FCMP_UGT: return 1; // 001
3731 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3732 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003733 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3734 case FCmpInst::FCMP_UGE: return 3; // 011
3735 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3736 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003737 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3738 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003739 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3740 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003741 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003742 default:
3743 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003744 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003745 return 0;
3746 }
3747}
3748
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749/// getICmpValue - This is the complement of getICmpCode, which turns an
3750/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003751/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003752/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003753static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003754 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003756 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003757 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003758 case 1:
3759 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003760 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003761 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003762 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3763 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003764 case 3:
3765 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003766 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003767 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003768 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 case 4:
3770 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003771 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003772 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003773 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3774 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 case 6:
3776 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003777 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003778 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003779 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003780 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781 }
3782}
3783
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003784/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3785/// opcode and two operands into either a FCmp instruction. isordered is passed
3786/// in to determine which kind of predicate to use in the new fcmp instruction.
3787static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003788 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003789 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003790 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003791 case 0:
3792 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003793 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003794 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003795 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003796 case 1:
3797 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003798 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003799 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003800 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003801 case 2:
3802 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003803 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003804 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003805 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003806 case 3:
3807 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003808 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003809 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003810 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003811 case 4:
3812 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003813 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003814 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003815 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003816 case 5:
3817 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003818 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003819 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003820 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003821 case 6:
3822 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003823 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003824 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003825 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003826 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003827 }
3828}
3829
Chris Lattner2972b822008-11-16 04:55:20 +00003830/// PredicatesFoldable - Return true if both predicates match sign or if at
3831/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003833 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3834 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3835 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003836}
3837
3838namespace {
3839// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3840struct FoldICmpLogical {
3841 InstCombiner &IC;
3842 Value *LHS, *RHS;
3843 ICmpInst::Predicate pred;
3844 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3845 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3846 pred(ICI->getPredicate()) {}
3847 bool shouldApply(Value *V) const {
3848 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3849 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003850 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3851 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003852 return false;
3853 }
3854 Instruction *apply(Instruction &Log) const {
3855 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3856 if (ICI->getOperand(0) != LHS) {
3857 assert(ICI->getOperand(1) == LHS);
3858 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3859 }
3860
3861 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3862 unsigned LHSCode = getICmpCode(ICI);
3863 unsigned RHSCode = getICmpCode(RHSICI);
3864 unsigned Code;
3865 switch (Log.getOpcode()) {
3866 case Instruction::And: Code = LHSCode & RHSCode; break;
3867 case Instruction::Or: Code = LHSCode | RHSCode; break;
3868 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003869 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003870 }
3871
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003872 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003873 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003874 if (Instruction *I = dyn_cast<Instruction>(RV))
3875 return I;
3876 // Otherwise, it's a constant boolean value...
3877 return IC.ReplaceInstUsesWith(Log, RV);
3878 }
3879};
3880} // end anonymous namespace
3881
3882// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3883// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3884// guaranteed to be a binary operator.
3885Instruction *InstCombiner::OptAndOp(Instruction *Op,
3886 ConstantInt *OpRHS,
3887 ConstantInt *AndRHS,
3888 BinaryOperator &TheAnd) {
3889 Value *X = Op->getOperand(0);
3890 Constant *Together = 0;
3891 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003892 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003893
3894 switch (Op->getOpcode()) {
3895 case Instruction::Xor:
3896 if (Op->hasOneUse()) {
3897 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003898 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003900 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003901 }
3902 break;
3903 case Instruction::Or:
3904 if (Together == AndRHS) // (X | C) & C --> C
3905 return ReplaceInstUsesWith(TheAnd, AndRHS);
3906
3907 if (Op->hasOneUse() && Together != OpRHS) {
3908 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003909 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003910 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003911 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003912 }
3913 break;
3914 case Instruction::Add:
3915 if (Op->hasOneUse()) {
3916 // Adding a one to a single bit bit-field should be turned into an XOR
3917 // of the bit. First thing to check is to see if this AND is with a
3918 // single bit constant.
3919 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3920
3921 // If there is only one bit set...
3922 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3923 // Ok, at this point, we know that we are masking the result of the
3924 // ADD down to exactly one bit. If the constant we are adding has
3925 // no bits set below this bit, then we can eliminate the ADD.
3926 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3927
3928 // Check to see if any bits below the one bit set in AndRHSV are set.
3929 if ((AddRHS & (AndRHSV-1)) == 0) {
3930 // If not, the only thing that can effect the output of the AND is
3931 // the bit specified by AndRHSV. If that bit is set, the effect of
3932 // the XOR is to toggle the bit. If it is clear, then the ADD has
3933 // no effect.
3934 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3935 TheAnd.setOperand(0, X);
3936 return &TheAnd;
3937 } else {
3938 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003939 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003940 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003941 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003942 }
3943 }
3944 }
3945 }
3946 break;
3947
3948 case Instruction::Shl: {
3949 // We know that the AND will not produce any of the bits shifted in, so if
3950 // the anded constant includes them, clear them now!
3951 //
3952 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3953 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3954 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003955 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003956
3957 if (CI->getValue() == ShlMask) {
3958 // Masking out bits that the shift already masks
3959 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3960 } else if (CI != AndRHS) { // Reducing bits set in and.
3961 TheAnd.setOperand(1, CI);
3962 return &TheAnd;
3963 }
3964 break;
3965 }
3966 case Instruction::LShr:
3967 {
3968 // We know that the AND will not produce any of the bits shifted in, so if
3969 // the anded constant includes them, clear them now! This only applies to
3970 // unsigned shifts, because a signed shr may bring in set bits!
3971 //
3972 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3973 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3974 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003975 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003976
3977 if (CI->getValue() == ShrMask) {
3978 // Masking out bits that the shift already masks.
3979 return ReplaceInstUsesWith(TheAnd, Op);
3980 } else if (CI != AndRHS) {
3981 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3982 return &TheAnd;
3983 }
3984 break;
3985 }
3986 case Instruction::AShr:
3987 // Signed shr.
3988 // See if this is shifting in some sign extension, then masking it out
3989 // with an and.
3990 if (Op->hasOneUse()) {
3991 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3992 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3993 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003994 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003995 if (C == AndRHS) { // Masking out bits shifted in.
3996 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3997 // Make the argument unsigned.
3998 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003999 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004000 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004001 }
4002 }
4003 break;
4004 }
4005 return 0;
4006}
4007
4008
4009/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4010/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
4011/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4012/// whether to treat the V, Lo and HI as signed or not. IB is the location to
4013/// insert new instructions.
4014Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
4015 bool isSigned, bool Inside,
4016 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00004017 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004018 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
4019 "Lo is not <= Hi in range emission code!");
4020
4021 if (Inside) {
4022 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00004023 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024
4025 // V >= Min && V < Hi --> V < Hi
4026 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4027 ICmpInst::Predicate pred = (isSigned ?
4028 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00004029 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004030 }
4031
4032 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00004033 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00004034 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00004035 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00004036 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004037 }
4038
4039 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00004040 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004041
4042 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004043 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004044 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4045 ICmpInst::Predicate pred = (isSigned ?
4046 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00004047 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004048 }
4049
4050 // Emit V-Lo >u Hi-1-Lo
4051 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00004052 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00004053 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00004054 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00004055 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056}
4057
4058// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4059// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4060// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4061// not, since all 1s are not contiguous.
4062static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4063 const APInt& V = Val->getValue();
4064 uint32_t BitWidth = Val->getType()->getBitWidth();
4065 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4066
4067 // look for the first zero bit after the run of ones
4068 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4069 // look for the first non-zero bit
4070 ME = V.getActiveBits();
4071 return true;
4072}
4073
4074/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4075/// where isSub determines whether the operator is a sub. If we can fold one of
4076/// the following xforms:
4077///
4078/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4079/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4080/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4081///
4082/// return (A +/- B).
4083///
4084Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4085 ConstantInt *Mask, bool isSub,
4086 Instruction &I) {
4087 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4088 if (!LHSI || LHSI->getNumOperands() != 2 ||
4089 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4090
4091 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4092
4093 switch (LHSI->getOpcode()) {
4094 default: return 0;
4095 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00004096 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004097 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4098 if ((Mask->getValue().countLeadingZeros() +
4099 Mask->getValue().countPopulation()) ==
4100 Mask->getValue().getBitWidth())
4101 break;
4102
4103 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4104 // part, we don't need any explicit masks to take them out of A. If that
4105 // is all N is, ignore it.
4106 uint32_t MB = 0, ME = 0;
4107 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4108 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4109 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4110 if (MaskedValueIsZero(RHS, Mask))
4111 break;
4112 }
4113 }
4114 return 0;
4115 case Instruction::Or:
4116 case Instruction::Xor:
4117 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4118 if ((Mask->getValue().countLeadingZeros() +
4119 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00004120 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004121 break;
4122 return 0;
4123 }
4124
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004125 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00004126 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4127 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128}
4129
Chris Lattner0631ea72008-11-16 05:06:21 +00004130/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4131Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4132 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner163e6ab2009-11-29 00:51:17 +00004133 // (icmp eq A, null) & (icmp eq B, null) -->
4134 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4135 if (TD &&
4136 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4137 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4138 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4139 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4140 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4141 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4142 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4143 Value *NewOr = Builder->CreateOr(A, B);
4144 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4145 Constant::getNullValue(IntPtrTy));
4146 }
4147
Chris Lattnerf3803482008-11-16 05:10:52 +00004148 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00004149 ConstantInt *LHSCst, *RHSCst;
4150 ICmpInst::Predicate LHSCC, RHSCC;
4151
Chris Lattnerf3803482008-11-16 05:10:52 +00004152 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004153 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004154 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004155 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004156 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00004157 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00004158
Chris Lattner163e6ab2009-11-29 00:51:17 +00004159 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4160 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4161 // where C is a power of 2
4162 if (LHSCC == ICmpInst::ICMP_ULT &&
4163 LHSCst->getValue().isPowerOf2()) {
4164 Value *NewOr = Builder->CreateOr(Val, Val2);
4165 return new ICmpInst(LHSCC, NewOr, LHSCst);
4166 }
4167
4168 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4169 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4170 Value *NewOr = Builder->CreateOr(Val, Val2);
4171 return new ICmpInst(LHSCC, NewOr, LHSCst);
4172 }
Chris Lattnerf3803482008-11-16 05:10:52 +00004173 }
4174
4175 // From here on, we only handle:
4176 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4177 if (Val != Val2) return 0;
4178
Chris Lattner0631ea72008-11-16 05:06:21 +00004179 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4180 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4181 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4182 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4183 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4184 return 0;
4185
4186 // We can't fold (ugt x, C) & (sgt x, C2).
4187 if (!PredicatesFoldable(LHSCC, RHSCC))
4188 return 0;
4189
4190 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00004191 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004192 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00004193 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004194 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00004195 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00004196 else
Chris Lattner665298f2008-11-16 05:14:43 +00004197 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4198
4199 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00004200 std::swap(LHS, RHS);
4201 std::swap(LHSCst, RHSCst);
4202 std::swap(LHSCC, RHSCC);
4203 }
4204
4205 // At this point, we know we have have two icmp instructions
4206 // comparing a value against two constants and and'ing the result
4207 // together. Because of the above check, we know that we only have
4208 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4209 // (from the FoldICmpLogical check above), that the two constants
4210 // are not equal and that the larger constant is on the RHS
4211 assert(LHSCst != RHSCst && "Compares not folded above?");
4212
4213 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004214 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004215 case ICmpInst::ICMP_EQ:
4216 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004217 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004218 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4219 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4220 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004221 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004222 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4223 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4224 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4225 return ReplaceInstUsesWith(I, LHS);
4226 }
4227 case ICmpInst::ICMP_NE:
4228 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004229 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004230 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004231 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004232 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004233 break; // (X != 13 & X u< 15) -> no change
4234 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004235 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004236 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004237 break; // (X != 13 & X s< 15) -> no change
4238 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4239 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4240 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4241 return ReplaceInstUsesWith(I, RHS);
4242 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004243 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00004244 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004245 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00004246 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004247 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00004248 }
4249 break; // (X != 13 & X != 15) -> no change
4250 }
4251 break;
4252 case ICmpInst::ICMP_ULT:
4253 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004254 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004255 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4256 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004257 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004258 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4259 break;
4260 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4261 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4262 return ReplaceInstUsesWith(I, LHS);
4263 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4264 break;
4265 }
4266 break;
4267 case ICmpInst::ICMP_SLT:
4268 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004269 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004270 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4271 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004272 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004273 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4274 break;
4275 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4276 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4277 return ReplaceInstUsesWith(I, LHS);
4278 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4279 break;
4280 }
4281 break;
4282 case ICmpInst::ICMP_UGT:
4283 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004284 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004285 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4286 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4287 return ReplaceInstUsesWith(I, RHS);
4288 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4289 break;
4290 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004291 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004292 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004293 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004294 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004295 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004296 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004297 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4298 break;
4299 }
4300 break;
4301 case ICmpInst::ICMP_SGT:
4302 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004303 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004304 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4305 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4306 return ReplaceInstUsesWith(I, RHS);
4307 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4308 break;
4309 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004310 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004311 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004312 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004313 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004314 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004315 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004316 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4317 break;
4318 }
4319 break;
4320 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004321
4322 return 0;
4323}
4324
Chris Lattner93a359a2009-07-23 05:14:02 +00004325Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4326 FCmpInst *RHS) {
4327
4328 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4329 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4330 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4331 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4332 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4333 // If either of the constants are nans, then the whole thing returns
4334 // false.
4335 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004336 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004337 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004338 LHS->getOperand(0), RHS->getOperand(0));
4339 }
Chris Lattnercf373552009-07-23 05:32:17 +00004340
4341 // Handle vector zeros. This occurs because the canonical form of
4342 // "fcmp ord x,x" is "fcmp ord x, 0".
4343 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4344 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004345 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004346 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004347 return 0;
4348 }
4349
4350 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4351 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4352 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4353
4354
4355 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4356 // Swap RHS operands to match LHS.
4357 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4358 std::swap(Op1LHS, Op1RHS);
4359 }
4360
4361 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4362 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4363 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004364 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004365
4366 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004367 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004368 if (Op0CC == FCmpInst::FCMP_TRUE)
4369 return ReplaceInstUsesWith(I, RHS);
4370 if (Op1CC == FCmpInst::FCMP_TRUE)
4371 return ReplaceInstUsesWith(I, LHS);
4372
4373 bool Op0Ordered;
4374 bool Op1Ordered;
4375 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4376 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4377 if (Op1Pred == 0) {
4378 std::swap(LHS, RHS);
4379 std::swap(Op0Pred, Op1Pred);
4380 std::swap(Op0Ordered, Op1Ordered);
4381 }
4382 if (Op0Pred == 0) {
4383 // uno && ueq -> uno && (uno || eq) -> ueq
4384 // ord && olt -> ord && (ord && lt) -> olt
4385 if (Op0Ordered == Op1Ordered)
4386 return ReplaceInstUsesWith(I, RHS);
4387
4388 // uno && oeq -> uno && (ord && eq) -> false
4389 // uno && ord -> false
4390 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004391 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004392 // ord && ueq -> ord && (uno || eq) -> oeq
4393 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4394 Op0LHS, Op0RHS, Context));
4395 }
4396 }
4397
4398 return 0;
4399}
4400
Chris Lattner0631ea72008-11-16 05:06:21 +00004401
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004402Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4403 bool Changed = SimplifyCommutative(I);
4404 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4405
Chris Lattnera3e46f62009-11-10 00:55:12 +00004406 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4407 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004408
4409 // See if we can simplify any instructions used by the instruction whose sole
4410 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004411 if (SimplifyDemandedInstructionBits(I))
4412 return &I;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004413
Dan Gohman8fd520a2009-06-15 22:12:54 +00004414
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004415 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004416 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004417 APInt NotAndRHS(~AndRHSMask);
4418
4419 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004420 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004421 Value *Op0LHS = Op0I->getOperand(0);
4422 Value *Op0RHS = Op0I->getOperand(1);
4423 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004424 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004425 case Instruction::Xor:
4426 case Instruction::Or:
4427 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004428 if (!Op0I->hasOneUse()) break;
4429
4430 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4431 // Not masking anything out for the LHS, move to RHS.
4432 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4433 Op0RHS->getName()+".masked");
4434 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4435 }
4436 if (!isa<Constant>(Op0RHS) &&
4437 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4438 // Not masking anything out for the RHS, move to LHS.
4439 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4440 Op0LHS->getName()+".masked");
4441 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004442 }
4443
4444 break;
4445 case Instruction::Add:
4446 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4447 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4448 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4449 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004450 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004451 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004452 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004453 break;
4454
4455 case Instruction::Sub:
4456 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4457 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4458 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4459 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004460 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004461
Nick Lewyckya349ba42008-07-10 05:51:40 +00004462 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4463 // has 1's for all bits that the subtraction with A might affect.
4464 if (Op0I->hasOneUse()) {
4465 uint32_t BitWidth = AndRHSMask.getBitWidth();
4466 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4467 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4468
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004469 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004470 if (!(A && A->isZero()) && // avoid infinite recursion.
4471 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004472 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004473 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4474 }
4475 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004476 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004477
4478 case Instruction::Shl:
4479 case Instruction::LShr:
4480 // (1 << x) & 1 --> zext(x == 0)
4481 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004482 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004483 Value *NewICmp =
4484 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004485 return new ZExtInst(NewICmp, I.getType());
4486 }
4487 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004488 }
4489
4490 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4491 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4492 return Res;
4493 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4494 // If this is an integer truncation or change from signed-to-unsigned, and
4495 // if the source is an and/or with immediate, transform it. This
4496 // frequently occurs for bitfield accesses.
4497 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4498 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4499 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00004500 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004501 if (CastOp->getOpcode() == Instruction::And) {
4502 // Change: and (cast (and X, C1) to T), C2
4503 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4504 // This will fold the two constants together, which may allow
4505 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004506 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004507 CastOp->getOperand(0), I.getType(),
4508 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004509 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004510 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004511 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004512 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004513 } else if (CastOp->getOpcode() == Instruction::Or) {
4514 // Change: and (cast (or X, C1) to T), C2
4515 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004516 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004517 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004518 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004519 return ReplaceInstUsesWith(I, AndRHS);
4520 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004521 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004522 }
4523 }
4524
4525 // Try to fold constant and into select arguments.
4526 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4527 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4528 return R;
4529 if (isa<PHINode>(Op0))
4530 if (Instruction *NV = FoldOpIntoPhi(I))
4531 return NV;
4532 }
4533
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534
4535 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00004536 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4537 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4538 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4539 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4540 I.getName()+".demorgan");
4541 return BinaryOperator::CreateNot(Or);
4542 }
4543
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004544 {
4545 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004546 // (A|B) & ~(A&B) -> A^B
4547 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4548 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4549 ((A == C && B == D) || (A == D && B == C)))
4550 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004551
Chris Lattnera3e46f62009-11-10 00:55:12 +00004552 // ~(A&B) & (A|B) -> A^B
4553 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4554 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4555 ((A == C && B == D) || (A == D && B == C)))
4556 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004557
4558 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004559 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004560 if (A == Op1) { // (A^B)&A -> A&(A^B)
4561 I.swapOperands(); // Simplify below
4562 std::swap(Op0, Op1);
4563 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4564 cast<BinaryOperator>(Op0)->swapOperands();
4565 I.swapOperands(); // Simplify below
4566 std::swap(Op0, Op1);
4567 }
4568 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004569
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004570 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004571 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004572 if (B == Op0) { // B&(A^B) -> B&(B^A)
4573 cast<BinaryOperator>(Op1)->swapOperands();
4574 std::swap(A, B);
4575 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004576 if (A == Op0) // A&(A^B) -> A & ~B
4577 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004578 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004579
4580 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004581 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4582 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004583 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004584 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4585 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004586 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004587 }
4588
4589 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4590 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004591 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004592 return R;
4593
Chris Lattner0631ea72008-11-16 05:06:21 +00004594 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4595 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4596 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004597 }
4598
4599 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4600 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4601 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4602 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4603 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004604 if (SrcTy == Op1C->getOperand(0)->getType() &&
4605 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004606 // Only do this if the casts both really cause code to be generated.
4607 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4608 I.getType(), TD) &&
4609 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4610 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004611 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4612 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004613 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004614 }
4615 }
4616
4617 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4618 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4619 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4620 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4621 SI0->getOperand(1) == SI1->getOperand(1) &&
4622 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004623 Value *NewOp =
4624 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4625 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004626 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004627 SI1->getOperand(1));
4628 }
4629 }
4630
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004631 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004632 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004633 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4634 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4635 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004636 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004637
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004638 return Changed ? &I : 0;
4639}
4640
Chris Lattner567f5112008-10-05 02:13:19 +00004641/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4642/// capable of providing pieces of a bswap. The subexpression provides pieces
4643/// of a bswap if it is proven that each of the non-zero bytes in the output of
4644/// the expression came from the corresponding "byte swapped" byte in some other
4645/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4646/// we know that the expression deposits the low byte of %X into the high byte
4647/// of the bswap result and that all other bytes are zero. This expression is
4648/// accepted, the high byte of ByteValues is set to X to indicate a correct
4649/// match.
4650///
4651/// This function returns true if the match was unsuccessful and false if so.
4652/// On entry to the function the "OverallLeftShift" is a signed integer value
4653/// indicating the number of bytes that the subexpression is later shifted. For
4654/// example, if the expression is later right shifted by 16 bits, the
4655/// OverallLeftShift value would be -2 on entry. This is used to specify which
4656/// byte of ByteValues is actually being set.
4657///
4658/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4659/// byte is masked to zero by a user. For example, in (X & 255), X will be
4660/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4661/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4662/// always in the local (OverallLeftShift) coordinate space.
4663///
4664static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4665 SmallVector<Value*, 8> &ByteValues) {
4666 if (Instruction *I = dyn_cast<Instruction>(V)) {
4667 // If this is an or instruction, it may be an inner node of the bswap.
4668 if (I->getOpcode() == Instruction::Or) {
4669 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4670 ByteValues) ||
4671 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4672 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004673 }
Chris Lattner567f5112008-10-05 02:13:19 +00004674
4675 // If this is a logical shift by a constant multiple of 8, recurse with
4676 // OverallLeftShift and ByteMask adjusted.
4677 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4678 unsigned ShAmt =
4679 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4680 // Ensure the shift amount is defined and of a byte value.
4681 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4682 return true;
4683
4684 unsigned ByteShift = ShAmt >> 3;
4685 if (I->getOpcode() == Instruction::Shl) {
4686 // X << 2 -> collect(X, +2)
4687 OverallLeftShift += ByteShift;
4688 ByteMask >>= ByteShift;
4689 } else {
4690 // X >>u 2 -> collect(X, -2)
4691 OverallLeftShift -= ByteShift;
4692 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004693 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004694 }
4695
4696 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4697 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4698
4699 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4700 ByteValues);
4701 }
4702
4703 // If this is a logical 'and' with a mask that clears bytes, clear the
4704 // corresponding bytes in ByteMask.
4705 if (I->getOpcode() == Instruction::And &&
4706 isa<ConstantInt>(I->getOperand(1))) {
4707 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4708 unsigned NumBytes = ByteValues.size();
4709 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4710 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4711
4712 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4713 // If this byte is masked out by a later operation, we don't care what
4714 // the and mask is.
4715 if ((ByteMask & (1 << i)) == 0)
4716 continue;
4717
4718 // If the AndMask is all zeros for this byte, clear the bit.
4719 APInt MaskB = AndMask & Byte;
4720 if (MaskB == 0) {
4721 ByteMask &= ~(1U << i);
4722 continue;
4723 }
4724
4725 // If the AndMask is not all ones for this byte, it's not a bytezap.
4726 if (MaskB != Byte)
4727 return true;
4728
4729 // Otherwise, this byte is kept.
4730 }
4731
4732 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4733 ByteValues);
4734 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004735 }
4736
Chris Lattner567f5112008-10-05 02:13:19 +00004737 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4738 // the input value to the bswap. Some observations: 1) if more than one byte
4739 // is demanded from this input, then it could not be successfully assembled
4740 // into a byteswap. At least one of the two bytes would not be aligned with
4741 // their ultimate destination.
4742 if (!isPowerOf2_32(ByteMask)) return true;
4743 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004744
Chris Lattner567f5112008-10-05 02:13:19 +00004745 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4746 // is demanded, it needs to go into byte 0 of the result. This means that the
4747 // byte needs to be shifted until it lands in the right byte bucket. The
4748 // shift amount depends on the position: if the byte is coming from the high
4749 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4750 // low part, it must be shifted left.
4751 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4752 if (InputByteNo < ByteValues.size()/2) {
4753 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4754 return true;
4755 } else {
4756 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4757 return true;
4758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004759
4760 // If the destination byte value is already defined, the values are or'd
4761 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004762 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004763 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004764 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004765 return false;
4766}
4767
4768/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4769/// If so, insert the new bswap intrinsic and return it.
4770Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4771 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004772 if (!ITy || ITy->getBitWidth() % 16 ||
4773 // ByteMask only allows up to 32-byte values.
4774 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004775 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4776
4777 /// ByteValues - For each byte of the result, we keep track of which value
4778 /// defines each byte.
4779 SmallVector<Value*, 8> ByteValues;
4780 ByteValues.resize(ITy->getBitWidth()/8);
4781
4782 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004783 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4784 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004785 return 0;
4786
4787 // Check to see if all of the bytes come from the same value.
4788 Value *V = ByteValues[0];
4789 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4790
4791 // Check to make sure that all of the bytes come from the same value.
4792 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4793 if (ByteValues[i] != V)
4794 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004795 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004796 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004797 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004798 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004799}
4800
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004801/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4802/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4803/// we can simplify this expression to "cond ? C : D or B".
4804static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004805 Value *C, Value *D,
4806 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004807 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004808 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004809 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004810 return 0;
4811
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004812 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004813 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004814 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004815 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004816 return SelectInst::Create(Cond, C, B);
4817 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004818 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004819 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004820 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004821 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004822 return 0;
4823}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004824
Chris Lattner0c678e52008-11-16 05:20:07 +00004825/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4826Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4827 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner163e6ab2009-11-29 00:51:17 +00004828 // (icmp ne A, null) | (icmp ne B, null) -->
4829 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4830 if (TD &&
4831 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4832 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4833 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4834 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4835 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4836 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4837 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4838 Value *NewOr = Builder->CreateOr(A, B);
4839 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4840 Constant::getNullValue(IntPtrTy));
4841 }
4842
Chris Lattner0c678e52008-11-16 05:20:07 +00004843 Value *Val, *Val2;
4844 ConstantInt *LHSCst, *RHSCst;
4845 ICmpInst::Predicate LHSCC, RHSCC;
4846
4847 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner163e6ab2009-11-29 00:51:17 +00004848 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4849 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004850 return 0;
Chris Lattner163e6ab2009-11-29 00:51:17 +00004851
4852
4853 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4854 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4855 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4856 Value *NewOr = Builder->CreateOr(Val, Val2);
4857 return new ICmpInst(LHSCC, NewOr, LHSCst);
4858 }
Chris Lattner0c678e52008-11-16 05:20:07 +00004859
4860 // From here on, we only handle:
4861 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4862 if (Val != Val2) return 0;
4863
4864 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4865 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4866 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4867 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4868 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4869 return 0;
4870
4871 // We can't fold (ugt x, C) | (sgt x, C2).
4872 if (!PredicatesFoldable(LHSCC, RHSCC))
4873 return 0;
4874
4875 // Ensure that the larger constant is on the RHS.
4876 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004877 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004878 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004879 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004880 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4881 else
4882 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4883
4884 if (ShouldSwap) {
4885 std::swap(LHS, RHS);
4886 std::swap(LHSCst, RHSCst);
4887 std::swap(LHSCC, RHSCC);
4888 }
4889
4890 // At this point, we know we have have two icmp instructions
4891 // comparing a value against two constants and or'ing the result
4892 // together. Because of the above check, we know that we only have
4893 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4894 // FoldICmpLogical check above), that the two constants are not
4895 // equal.
4896 assert(LHSCst != RHSCst && "Compares not folded above?");
4897
4898 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004899 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004900 case ICmpInst::ICMP_EQ:
4901 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004902 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004903 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004904 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004905 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004906 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004907 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004908 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004909 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004910 }
4911 break; // (X == 13 | X == 15) -> no change
4912 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4913 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4914 break;
4915 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4916 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4917 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4918 return ReplaceInstUsesWith(I, RHS);
4919 }
4920 break;
4921 case ICmpInst::ICMP_NE:
4922 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004923 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004924 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4925 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4926 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4927 return ReplaceInstUsesWith(I, LHS);
4928 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4929 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4930 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004931 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004932 }
4933 break;
4934 case ICmpInst::ICMP_ULT:
4935 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004936 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004937 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4938 break;
4939 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4940 // If RHSCst is [us]MAXINT, it is always false. Not handling
4941 // this can cause overflow.
4942 if (RHSCst->isMaxValue(false))
4943 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004944 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004945 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004946 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4947 break;
4948 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4949 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4950 return ReplaceInstUsesWith(I, RHS);
4951 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4952 break;
4953 }
4954 break;
4955 case ICmpInst::ICMP_SLT:
4956 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004957 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004958 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4959 break;
4960 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4961 // If RHSCst is [us]MAXINT, it is always false. Not handling
4962 // this can cause overflow.
4963 if (RHSCst->isMaxValue(true))
4964 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004965 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004966 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004967 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4968 break;
4969 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4970 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4971 return ReplaceInstUsesWith(I, RHS);
4972 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4973 break;
4974 }
4975 break;
4976 case ICmpInst::ICMP_UGT:
4977 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004978 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004979 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4980 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4981 return ReplaceInstUsesWith(I, LHS);
4982 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4983 break;
4984 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4985 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004986 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004987 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4988 break;
4989 }
4990 break;
4991 case ICmpInst::ICMP_SGT:
4992 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004993 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004994 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4995 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4996 return ReplaceInstUsesWith(I, LHS);
4997 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4998 break;
4999 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5000 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005001 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00005002 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5003 break;
5004 }
5005 break;
5006 }
5007 return 0;
5008}
5009
Chris Lattner57e66fa2009-07-23 05:46:22 +00005010Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5011 FCmpInst *RHS) {
5012 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5013 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5014 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5015 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5016 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5017 // If either of the constants are nans, then the whole thing returns
5018 // true.
5019 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005020 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00005021
5022 // Otherwise, no need to compare the two constants, compare the
5023 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00005024 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005025 LHS->getOperand(0), RHS->getOperand(0));
5026 }
5027
5028 // Handle vector zeros. This occurs because the canonical form of
5029 // "fcmp uno x,x" is "fcmp uno x, 0".
5030 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5031 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00005032 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005033 LHS->getOperand(0), RHS->getOperand(0));
5034
5035 return 0;
5036 }
5037
5038 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5039 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5040 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5041
5042 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5043 // Swap RHS operands to match LHS.
5044 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5045 std::swap(Op1LHS, Op1RHS);
5046 }
5047 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5048 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5049 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00005050 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005051 Op0LHS, Op0RHS);
5052 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005053 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00005054 if (Op0CC == FCmpInst::FCMP_FALSE)
5055 return ReplaceInstUsesWith(I, RHS);
5056 if (Op1CC == FCmpInst::FCMP_FALSE)
5057 return ReplaceInstUsesWith(I, LHS);
5058 bool Op0Ordered;
5059 bool Op1Ordered;
5060 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5061 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5062 if (Op0Ordered == Op1Ordered) {
5063 // If both are ordered or unordered, return a new fcmp with
5064 // or'ed predicates.
5065 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5066 Op0LHS, Op0RHS, Context);
5067 if (Instruction *I = dyn_cast<Instruction>(RV))
5068 return I;
5069 // Otherwise, it's a constant boolean value...
5070 return ReplaceInstUsesWith(I, RV);
5071 }
5072 }
5073 return 0;
5074}
5075
Bill Wendlingdae376a2008-12-01 08:23:25 +00005076/// FoldOrWithConstants - This helper function folds:
5077///
Bill Wendling236a1192008-12-02 05:09:00 +00005078/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00005079///
5080/// into:
5081///
Bill Wendling236a1192008-12-02 05:09:00 +00005082/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00005083///
Bill Wendling236a1192008-12-02 05:09:00 +00005084/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00005085Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00005086 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00005087 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5088 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005089
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005090 Value *V1 = 0;
5091 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005092 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005093
Bill Wendling86ee3162008-12-02 06:18:11 +00005094 APInt Xor = CI1->getValue() ^ CI2->getValue();
5095 if (!Xor.isAllOnesValue()) return 0;
5096
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005097 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005098 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00005099 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005100 }
5101
5102 return 0;
5103}
5104
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005105Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5106 bool Changed = SimplifyCommutative(I);
5107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5108
Chris Lattnera3e46f62009-11-10 00:55:12 +00005109 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5110 return ReplaceInstUsesWith(I, V);
5111
5112
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005113 // See if we can simplify any instructions used by the instruction whose sole
5114 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005115 if (SimplifyDemandedInstructionBits(I))
5116 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005118 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5119 ConstantInt *C1 = 0; Value *X = 0;
5120 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005121 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005122 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005123 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005124 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005125 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005126 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 }
5128
5129 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005130 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005131 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005132 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005133 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005134 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005135 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005136 }
5137
5138 // Try to fold constant and into select arguments.
5139 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5140 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5141 return R;
5142 if (isa<PHINode>(Op0))
5143 if (Instruction *NV = FoldOpIntoPhi(I))
5144 return NV;
5145 }
5146
5147 Value *A = 0, *B = 0;
5148 ConstantInt *C1 = 0, *C2 = 0;
5149
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005150 // (A | B) | C and A | (B | C) -> bswap if possible.
5151 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00005152 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5153 match(Op1, m_Or(m_Value(), m_Value())) ||
5154 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5155 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005156 if (Instruction *BSwap = MatchBSwap(I))
5157 return BSwap;
5158 }
5159
5160 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005161 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005162 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005163 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005164 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005165 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005166 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005167 }
5168
5169 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005170 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005171 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005172 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005173 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005174 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005175 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005176 }
5177
5178 // (A & C)|(B & D)
5179 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005180 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5181 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005182 Value *V1 = 0, *V2 = 0, *V3 = 0;
5183 C1 = dyn_cast<ConstantInt>(C);
5184 C2 = dyn_cast<ConstantInt>(D);
5185 if (C1 && C2) { // (A & C1)|(B & C2)
5186 // If we have: ((V + N) & C1) | (V & C2)
5187 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5188 // replace with V+N.
5189 if (C1->getValue() == ~C2->getValue()) {
5190 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00005191 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192 // Add commutes, try both ways.
5193 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5194 return ReplaceInstUsesWith(I, A);
5195 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5196 return ReplaceInstUsesWith(I, A);
5197 }
5198 // Or commutes, try both ways.
5199 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005200 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005201 // Add commutes, try both ways.
5202 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5203 return ReplaceInstUsesWith(I, B);
5204 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5205 return ReplaceInstUsesWith(I, B);
5206 }
5207 }
5208 V1 = 0; V2 = 0; V3 = 0;
5209 }
5210
5211 // Check to see if we have any common things being and'ed. If so, find the
5212 // terms for V1 & (V2|V3).
5213 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5214 if (A == B) // (A & C)|(A & D) == A & (C|D)
5215 V1 = A, V2 = C, V3 = D;
5216 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5217 V1 = A, V2 = B, V3 = C;
5218 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5219 V1 = C, V2 = A, V3 = D;
5220 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5221 V1 = C, V2 = A, V3 = B;
5222
5223 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005224 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005225 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005226 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005227 }
Dan Gohman279952c2008-10-28 22:38:57 +00005228
Dan Gohman35b76162008-10-30 20:40:10 +00005229 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00005230 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005231 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005232 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005233 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005234 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005235 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005236 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005237 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00005238
Bill Wendling22ca8352008-11-30 13:52:49 +00005239 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005240 if ((match(C, m_Not(m_Specific(D))) &&
5241 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005242 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005243 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005244 if ((match(A, m_Not(m_Specific(D))) &&
5245 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005246 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005247 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005248 if ((match(C, m_Not(m_Specific(B))) &&
5249 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005250 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00005251 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005252 if ((match(A, m_Not(m_Specific(B))) &&
5253 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005254 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005255 }
5256
5257 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5258 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5259 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5260 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5261 SI0->getOperand(1) == SI1->getOperand(1) &&
5262 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005263 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5264 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005265 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005266 SI1->getOperand(1));
5267 }
5268 }
5269
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005270 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005271 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5272 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005273 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005274 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005275 }
5276 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005277 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5278 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005279 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005280 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005281 }
5282
Chris Lattnera3e46f62009-11-10 00:55:12 +00005283 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5284 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5285 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5286 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5287 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5288 I.getName()+".demorgan");
5289 return BinaryOperator::CreateNot(And);
5290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005291
5292 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5293 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005294 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005295 return R;
5296
Chris Lattner0c678e52008-11-16 05:20:07 +00005297 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5298 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5299 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005300 }
5301
5302 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005303 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005304 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5305 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005306 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5307 !isa<ICmpInst>(Op1C->getOperand(0))) {
5308 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005309 if (SrcTy == Op1C->getOperand(0)->getType() &&
5310 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005311 // Only do this if the casts both really cause code to be
5312 // generated.
5313 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5314 I.getType(), TD) &&
5315 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5316 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005317 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5318 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005319 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005320 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005321 }
5322 }
Chris Lattner91882432007-10-24 05:38:08 +00005323 }
5324
5325
5326 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5327 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005328 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5329 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5330 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005332
5333 return Changed ? &I : 0;
5334}
5335
Dan Gohman089efff2008-05-13 00:00:25 +00005336namespace {
5337
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005338// XorSelf - Implements: X ^ X --> 0
5339struct XorSelf {
5340 Value *RHS;
5341 XorSelf(Value *rhs) : RHS(rhs) {}
5342 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5343 Instruction *apply(BinaryOperator &Xor) const {
5344 return &Xor;
5345 }
5346};
5347
Dan Gohman089efff2008-05-13 00:00:25 +00005348}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005349
5350Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5351 bool Changed = SimplifyCommutative(I);
5352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5353
Evan Chenge5cd8032008-03-25 20:07:13 +00005354 if (isa<UndefValue>(Op1)) {
5355 if (isa<UndefValue>(Op0))
5356 // Handle undef ^ undef -> 0 special case. This is a common
5357 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005358 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005359 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005360 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005361
5362 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005363 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005364 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005365 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005366 }
5367
5368 // See if we can simplify any instructions used by the instruction whose sole
5369 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005370 if (SimplifyDemandedInstructionBits(I))
5371 return &I;
5372 if (isa<VectorType>(I.getType()))
5373 if (isa<ConstantAggregateZero>(Op1))
5374 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005375
5376 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005377 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005378 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5379 if (Op0I->getOpcode() == Instruction::And ||
5380 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00005381 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5382 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5383 if (dyn_castNotVal(Op0I->getOperand(1)))
5384 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005385 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005386 Value *NotY =
5387 Builder->CreateNot(Op0I->getOperand(1),
5388 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005389 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005390 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005391 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005392 }
Chris Lattner6e060db2009-10-26 15:40:07 +00005393
5394 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5395 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5396 if (isFreeToInvert(Op0I->getOperand(0)) &&
5397 isFreeToInvert(Op0I->getOperand(1))) {
5398 Value *NotX =
5399 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5400 Value *NotY =
5401 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5402 if (Op0I->getOpcode() == Instruction::And)
5403 return BinaryOperator::CreateOr(NotX, NotY);
5404 return BinaryOperator::CreateAnd(NotX, NotY);
5405 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005406 }
5407 }
5408 }
5409
5410
5411 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005412 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005413 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005414 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005415 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005416 ICI->getOperand(0), ICI->getOperand(1));
5417
Nick Lewycky1405e922007-08-06 20:04:16 +00005418 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005419 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005420 FCI->getOperand(0), FCI->getOperand(1));
5421 }
5422
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005423 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5424 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5425 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5426 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5427 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005428 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5429 (RHS == ConstantExpr::getCast(Opcode,
5430 ConstantInt::getTrue(*Context),
5431 Op0C->getDestTy()))) {
5432 CI->setPredicate(CI->getInversePredicate());
5433 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005434 }
5435 }
5436 }
5437 }
5438
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005439 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5440 // ~(c-X) == X-c-1 == X+(-c-1)
5441 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5442 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005443 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5444 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005445 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005446 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005447 }
5448
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005449 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005450 if (Op0I->getOpcode() == Instruction::Add) {
5451 // ~(X-c) --> (-c-1)-X
5452 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005453 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005454 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005455 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005456 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005457 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005458 } else if (RHS->getValue().isSignBit()) {
5459 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005460 Constant *C = ConstantInt::get(*Context,
5461 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005462 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005463
5464 }
5465 } else if (Op0I->getOpcode() == Instruction::Or) {
5466 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5467 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005468 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005469 // Anything in both C1 and C2 is known to be zero, remove it from
5470 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005471 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5472 NewRHS = ConstantExpr::getAnd(NewRHS,
5473 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005474 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005475 I.setOperand(0, Op0I->getOperand(0));
5476 I.setOperand(1, NewRHS);
5477 return &I;
5478 }
5479 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005480 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005481 }
5482
5483 // Try to fold constant and into select arguments.
5484 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5485 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5486 return R;
5487 if (isa<PHINode>(Op0))
5488 if (Instruction *NV = FoldOpIntoPhi(I))
5489 return NV;
5490 }
5491
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005492 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005493 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005494 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005495
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005496 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005497 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005498 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005499
5500
5501 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5502 if (Op1I) {
5503 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005504 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005505 if (A == Op0) { // B^(B|A) == (A|B)^B
5506 Op1I->swapOperands();
5507 I.swapOperands();
5508 std::swap(Op0, Op1);
5509 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5510 I.swapOperands(); // Simplified below.
5511 std::swap(Op0, Op1);
5512 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005513 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005514 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005515 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005516 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005517 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005518 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005519 if (A == Op0) { // A^(A&B) -> A^(B&A)
5520 Op1I->swapOperands();
5521 std::swap(A, B);
5522 }
5523 if (B == Op0) { // A^(B&A) -> (B&A)^A
5524 I.swapOperands(); // Simplified below.
5525 std::swap(Op0, Op1);
5526 }
5527 }
5528 }
5529
5530 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5531 if (Op0I) {
5532 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005533 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005534 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005535 if (A == Op1) // (B|A)^B == (A|B)^B
5536 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005537 if (B == Op1) // (A|B)^B == A & ~B
5538 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005539 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005540 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005541 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005542 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005543 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005544 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005545 if (A == Op1) // (A&B)^A -> (B&A)^A
5546 std::swap(A, B);
5547 if (B == Op1 && // (B&A)^A == ~B & A
5548 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005549 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005550 }
5551 }
5552 }
5553
5554 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5555 if (Op0I && Op1I && Op0I->isShift() &&
5556 Op0I->getOpcode() == Op1I->getOpcode() &&
5557 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5558 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005559 Value *NewOp =
5560 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5561 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005562 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005563 Op1I->getOperand(1));
5564 }
5565
5566 if (Op0I && Op1I) {
5567 Value *A, *B, *C, *D;
5568 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005569 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5570 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005571 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005572 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005573 }
5574 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005575 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5576 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005577 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005578 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579 }
5580
5581 // (A & B)^(C & D)
5582 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005583 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5584 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005585 // (X & Y)^(X & Y) -> (Y^Z) & X
5586 Value *X = 0, *Y = 0, *Z = 0;
5587 if (A == C)
5588 X = A, Y = B, Z = D;
5589 else if (A == D)
5590 X = A, Y = B, Z = C;
5591 else if (B == C)
5592 X = B, Y = A, Z = D;
5593 else if (B == D)
5594 X = B, Y = A, Z = C;
5595
5596 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005597 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005598 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005599 }
5600 }
5601 }
5602
5603 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5604 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005605 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005606 return R;
5607
5608 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005609 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005610 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5611 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5612 const Type *SrcTy = Op0C->getOperand(0)->getType();
5613 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5614 // Only do this if the casts both really cause code to be generated.
5615 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5616 I.getType(), TD) &&
5617 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5618 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005619 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5620 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005621 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005622 }
5623 }
Chris Lattner91882432007-10-24 05:38:08 +00005624 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005626 return Changed ? &I : 0;
5627}
5628
Owen Anderson24be4c12009-07-03 00:17:18 +00005629static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005630 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005631 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005632}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005633
Dan Gohman8fd520a2009-06-15 22:12:54 +00005634static bool HasAddOverflow(ConstantInt *Result,
5635 ConstantInt *In1, ConstantInt *In2,
5636 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005637 if (IsSigned)
5638 if (In2->getValue().isNegative())
5639 return Result->getValue().sgt(In1->getValue());
5640 else
5641 return Result->getValue().slt(In1->getValue());
5642 else
5643 return Result->getValue().ult(In1->getValue());
5644}
5645
Dan Gohman8fd520a2009-06-15 22:12:54 +00005646/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005647/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005648static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005649 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005650 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005651 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005652
Dan Gohman8fd520a2009-06-15 22:12:54 +00005653 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5654 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005655 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005656 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5657 ExtractElement(In1, Idx, Context),
5658 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005659 IsSigned))
5660 return true;
5661 }
5662 return false;
5663 }
5664
5665 return HasAddOverflow(cast<ConstantInt>(Result),
5666 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5667 IsSigned);
5668}
5669
5670static bool HasSubOverflow(ConstantInt *Result,
5671 ConstantInt *In1, ConstantInt *In2,
5672 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005673 if (IsSigned)
5674 if (In2->getValue().isNegative())
5675 return Result->getValue().slt(In1->getValue());
5676 else
5677 return Result->getValue().sgt(In1->getValue());
5678 else
5679 return Result->getValue().ugt(In1->getValue());
5680}
5681
Dan Gohman8fd520a2009-06-15 22:12:54 +00005682/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5683/// overflowed for this type.
5684static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005685 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005686 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005687 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005688
5689 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5690 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005691 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005692 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5693 ExtractElement(In1, Idx, Context),
5694 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005695 IsSigned))
5696 return true;
5697 }
5698 return false;
5699 }
5700
5701 return HasSubOverflow(cast<ConstantInt>(Result),
5702 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5703 IsSigned);
5704}
5705
Chris Lattnereba75862008-04-22 02:53:33 +00005706
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005707/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5708/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005709Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005710 ICmpInst::Predicate Cond,
5711 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005712 // Look through bitcasts.
5713 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5714 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005715
5716 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005717 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005718 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005719 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005720 // know pointers can't overflow since the gep is inbounds. See if we can
5721 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005722 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5723
5724 // If not, synthesize the offset the hard way.
5725 if (Offset == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005726 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005727 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005728 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005729 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005730 // If the base pointers are different, but the indices are the same, just
5731 // compare the base pointer.
5732 if (PtrBase != GEPRHS->getOperand(0)) {
5733 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5734 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5735 GEPRHS->getOperand(0)->getType();
5736 if (IndicesTheSame)
5737 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5738 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5739 IndicesTheSame = false;
5740 break;
5741 }
5742
5743 // If all indices are the same, just compare the base pointers.
5744 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005745 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005746 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5747
5748 // Otherwise, the base pointers are different and the indices are
5749 // different, bail out.
5750 return 0;
5751 }
5752
5753 // If one of the GEPs has all zero indices, recurse.
5754 bool AllZeros = true;
5755 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5756 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5757 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5758 AllZeros = false;
5759 break;
5760 }
5761 if (AllZeros)
5762 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5763 ICmpInst::getSwappedPredicate(Cond), I);
5764
5765 // If the other GEP has all zero indices, recurse.
5766 AllZeros = true;
5767 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5768 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5769 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5770 AllZeros = false;
5771 break;
5772 }
5773 if (AllZeros)
5774 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5775
5776 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5777 // If the GEPs only differ by one index, compare it.
5778 unsigned NumDifferences = 0; // Keep track of # differences.
5779 unsigned DiffOperand = 0; // The operand that differs.
5780 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5781 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5782 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5783 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5784 // Irreconcilable differences.
5785 NumDifferences = 2;
5786 break;
5787 } else {
5788 if (NumDifferences++) break;
5789 DiffOperand = i;
5790 }
5791 }
5792
5793 if (NumDifferences == 0) // SAME GEP?
5794 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005795 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005796 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005797
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005798 else if (NumDifferences == 1) {
5799 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5800 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5801 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005802 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005803 }
5804 }
5805
5806 // Only lower this if the icmp is the only user of the GEP or if we expect
5807 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005808 if (TD &&
5809 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005810 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5811 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005812 Value *L = EmitGEPOffset(GEPLHS, *this);
5813 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005814 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005815 }
5816 }
5817 return 0;
5818}
5819
Chris Lattnere6b62d92008-05-19 20:18:56 +00005820/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5821///
5822Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5823 Instruction *LHSI,
5824 Constant *RHSC) {
5825 if (!isa<ConstantFP>(RHSC)) return 0;
5826 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5827
5828 // Get the width of the mantissa. We don't want to hack on conversions that
5829 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005830 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005831 if (MantissaWidth == -1) return 0; // Unknown.
5832
5833 // Check to see that the input is converted from an integer type that is small
5834 // enough that preserves all bits. TODO: check here for "known" sign bits.
5835 // 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 +00005836 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005837
5838 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005839 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5840 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005841 ++InputSize;
5842
5843 // If the conversion would lose info, don't hack on this.
5844 if ((int)InputSize > MantissaWidth)
5845 return 0;
5846
5847 // Otherwise, we can potentially simplify the comparison. We know that it
5848 // will always come through as an integer value and we know the constant is
5849 // not a NAN (it would have been previously simplified).
5850 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5851
5852 ICmpInst::Predicate Pred;
5853 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005854 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005855 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005856 case FCmpInst::FCMP_OEQ:
5857 Pred = ICmpInst::ICMP_EQ;
5858 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005859 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005860 case FCmpInst::FCMP_OGT:
5861 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5862 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005863 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005864 case FCmpInst::FCMP_OGE:
5865 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5866 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005867 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005868 case FCmpInst::FCMP_OLT:
5869 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5870 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005871 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005872 case FCmpInst::FCMP_OLE:
5873 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5874 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005875 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005876 case FCmpInst::FCMP_ONE:
5877 Pred = ICmpInst::ICMP_NE;
5878 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005879 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005880 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005881 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005883 }
5884
5885 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5886
5887 // Now we know that the APFloat is a normal number, zero or inf.
5888
Chris Lattnerf13ff492008-05-20 03:50:52 +00005889 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005890 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005891 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005892
Bill Wendling20636df2008-11-09 04:26:50 +00005893 if (!LHSUnsigned) {
5894 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5895 // and large values.
5896 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5897 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5898 APFloat::rmNearestTiesToEven);
5899 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5900 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5901 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005902 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5903 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005904 }
5905 } else {
5906 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5907 // +INF and large values.
5908 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5909 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5910 APFloat::rmNearestTiesToEven);
5911 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5912 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5913 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5915 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005916 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005917 }
5918
Bill Wendling20636df2008-11-09 04:26:50 +00005919 if (!LHSUnsigned) {
5920 // See if the RHS value is < SignedMin.
5921 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5922 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5923 APFloat::rmNearestTiesToEven);
5924 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5925 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5926 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005927 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5928 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005929 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005930 }
5931
Bill Wendling20636df2008-11-09 04:26:50 +00005932 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5933 // [0, UMAX], but it may still be fractional. See if it is fractional by
5934 // casting the FP value to the integer value and back, checking for equality.
5935 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005936 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005937 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5938 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005939 if (!RHS.isZero()) {
5940 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005941 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5942 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005943 if (!Equal) {
5944 // If we had a comparison against a fractional value, we have to adjust
5945 // the compare predicate and sometimes the value. RHSC is rounded towards
5946 // zero at this point.
5947 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005948 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005949 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005950 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005951 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005952 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005953 case ICmpInst::ICMP_ULE:
5954 // (float)int <= 4.4 --> int <= 4
5955 // (float)int <= -4.4 --> false
5956 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005958 break;
5959 case ICmpInst::ICMP_SLE:
5960 // (float)int <= 4.4 --> int <= 4
5961 // (float)int <= -4.4 --> int < -4
5962 if (RHS.isNegative())
5963 Pred = ICmpInst::ICMP_SLT;
5964 break;
5965 case ICmpInst::ICMP_ULT:
5966 // (float)int < -4.4 --> false
5967 // (float)int < 4.4 --> int <= 4
5968 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005969 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005970 Pred = ICmpInst::ICMP_ULE;
5971 break;
5972 case ICmpInst::ICMP_SLT:
5973 // (float)int < -4.4 --> int < -4
5974 // (float)int < 4.4 --> int <= 4
5975 if (!RHS.isNegative())
5976 Pred = ICmpInst::ICMP_SLE;
5977 break;
5978 case ICmpInst::ICMP_UGT:
5979 // (float)int > 4.4 --> int > 4
5980 // (float)int > -4.4 --> true
5981 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005982 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005983 break;
5984 case ICmpInst::ICMP_SGT:
5985 // (float)int > 4.4 --> int > 4
5986 // (float)int > -4.4 --> int >= -4
5987 if (RHS.isNegative())
5988 Pred = ICmpInst::ICMP_SGE;
5989 break;
5990 case ICmpInst::ICMP_UGE:
5991 // (float)int >= -4.4 --> true
5992 // (float)int >= 4.4 --> int > 4
5993 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005994 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005995 Pred = ICmpInst::ICMP_UGT;
5996 break;
5997 case ICmpInst::ICMP_SGE:
5998 // (float)int >= -4.4 --> int >= -4
5999 // (float)int >= 4.4 --> int > 4
6000 if (!RHS.isNegative())
6001 Pred = ICmpInst::ICMP_SGT;
6002 break;
6003 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00006004 }
6005 }
6006
6007 // Lower this FP comparison into an appropriate integer version of the
6008 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00006009 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00006010}
6011
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006012Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006013 bool Changed = false;
6014
6015 /// Orders the operands of the compare so that they are listed from most
6016 /// complex to least complex. This puts constants before unary operators,
6017 /// before binary operators.
6018 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6019 I.swapOperands();
6020 Changed = true;
6021 }
6022
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006024
Chris Lattner54c21352009-11-09 23:55:12 +00006025 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6026 return ReplaceInstUsesWith(I, V);
6027
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006028 // Simplify 'fcmp pred X, X'
6029 if (Op0 == Op1) {
6030 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006031 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006032 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6033 case FCmpInst::FCMP_ULT: // True if unordered or less than
6034 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6035 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6036 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6037 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00006038 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006039 return &I;
6040
6041 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6042 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6043 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6044 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6045 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6046 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00006047 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006048 return &I;
6049 }
6050 }
6051
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006052 // Handle fcmp with constant RHS
6053 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6054 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6055 switch (LHSI->getOpcode()) {
6056 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006057 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6058 // block. If in the same block, we're encouraging jump threading. If
6059 // not, we are just pessimizing the code by making an i1 phi.
6060 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006061 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006062 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006063 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00006064 case Instruction::SIToFP:
6065 case Instruction::UIToFP:
6066 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6067 return NV;
6068 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006069 case Instruction::Select:
6070 // If either operand of the select is a constant, we can fold the
6071 // comparison into the select arms, which will cause one to be
6072 // constant folded and the select turned into a bitwise or.
6073 Value *Op1 = 0, *Op2 = 0;
6074 if (LHSI->hasOneUse()) {
6075 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6076 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006077 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006078 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006079 Op2 = Builder->CreateFCmp(I.getPredicate(),
6080 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006081 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6082 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006083 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006084 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006085 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6086 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006087 }
6088 }
6089
6090 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006091 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006092 break;
6093 }
6094 }
6095
6096 return Changed ? &I : 0;
6097}
6098
6099Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006100 bool Changed = false;
6101
6102 /// Orders the operands of the compare so that they are listed from most
6103 /// complex to least complex. This puts constants before unary operators,
6104 /// before binary operators.
6105 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6106 I.swapOperands();
6107 Changed = true;
6108 }
6109
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lambf78cd322007-12-18 21:32:20 +00006111
Chris Lattner54c21352009-11-09 23:55:12 +00006112 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6113 return ReplaceInstUsesWith(I, V);
6114
6115 const Type *Ty = Op0->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006116
6117 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006118 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006119 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006120 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006121 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006122 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006123 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006124 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006125 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006126 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006127
6128 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006129 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006130 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006131 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006132 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006133 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006134 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006135 case ICmpInst::ICMP_SGT:
6136 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006137 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006138 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006139 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006140 return BinaryOperator::CreateAnd(Not, Op0);
6141 }
6142 case ICmpInst::ICMP_UGE:
6143 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6144 // FALL THROUGH
6145 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006146 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006147 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006148 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006149 case ICmpInst::ICMP_SGE:
6150 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6151 // FALL THROUGH
6152 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006153 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006154 return BinaryOperator::CreateOr(Not, Op0);
6155 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006156 }
6157 }
6158
Dan Gohman7934d592009-04-25 17:12:48 +00006159 unsigned BitWidth = 0;
6160 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006161 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6162 else if (Ty->isIntOrIntVector())
6163 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006164
6165 bool isSignBit = false;
6166
Dan Gohman58c09632008-09-16 18:46:06 +00006167 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006169 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006170
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006171 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6172 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006173 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006174 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006175 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006176 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006177
Dan Gohman58c09632008-09-16 18:46:06 +00006178 // If we have an icmp le or icmp ge instruction, turn it into the
6179 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner54c21352009-11-09 23:55:12 +00006180 // them being folded in the code below. The SimplifyICmpInst code has
6181 // already handled the edge cases for us, so we just assert on them.
Chris Lattner62d0f232008-07-11 05:08:55 +00006182 switch (I.getPredicate()) {
6183 default: break;
6184 case ICmpInst::ICMP_ULE:
Chris Lattner54c21352009-11-09 23:55:12 +00006185 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006186 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006187 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006188 case ICmpInst::ICMP_SLE:
Chris Lattner54c21352009-11-09 23:55:12 +00006189 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006190 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006191 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006192 case ICmpInst::ICMP_UGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006193 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006194 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006195 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006196 case ICmpInst::ICMP_SGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006197 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006198 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006199 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006200 }
6201
Chris Lattnera1308652008-07-11 05:40:05 +00006202 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006203 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006204 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006205 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6206 }
6207
6208 // See if we can fold the comparison based on range information we can get
6209 // by checking whether bits are known to be zero or one in the input.
6210 if (BitWidth != 0) {
6211 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6212 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6213
6214 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006215 isSignBit ? APInt::getSignBit(BitWidth)
6216 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006217 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006218 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006219 if (SimplifyDemandedBits(I.getOperandUse(1),
6220 APInt::getAllOnesValue(BitWidth),
6221 Op1KnownZero, Op1KnownOne, 0))
6222 return &I;
6223
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006224 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006225 // in. Compute the Min, Max and RHS values based on the known bits. For the
6226 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006227 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6228 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006229 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006230 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6231 Op0Min, Op0Max);
6232 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6233 Op1Min, Op1Max);
6234 } else {
6235 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6236 Op0Min, Op0Max);
6237 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6238 Op1Min, Op1Max);
6239 }
6240
Chris Lattnera1308652008-07-11 05:40:05 +00006241 // If Min and Max are known to be the same, then SimplifyDemandedBits
6242 // figured out that the LHS is a constant. Just constant fold this now so
6243 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006244 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006245 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006246 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006247 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006248 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006249 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006250
Chris Lattnera1308652008-07-11 05:40:05 +00006251 // Based on the range information we know about the LHS, see if we can
6252 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006253 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006254 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006255 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006256 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006257 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006258 break;
6259 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006260 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006262 break;
6263 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006264 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006265 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006266 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006267 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006268 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006269 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006270 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6271 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006272 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006273 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006274
6275 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6276 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006277 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006278 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006279 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006280 break;
6281 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006282 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006283 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006284 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006285 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006286
6287 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006288 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006289 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6290 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006291 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006292 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006293
6294 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6295 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006296 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006297 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006298 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006299 break;
6300 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006301 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006302 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006303 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006304 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006305 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006306 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006307 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6308 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006309 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006310 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006311 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006312 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006313 case ICmpInst::ICMP_SGT:
6314 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006315 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006316 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006317 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006318
6319 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006320 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6322 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006323 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006324 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006325 }
6326 break;
6327 case ICmpInst::ICMP_SGE:
6328 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6329 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006330 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006331 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006332 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006333 break;
6334 case ICmpInst::ICMP_SLE:
6335 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6336 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006337 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006338 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006339 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006340 break;
6341 case ICmpInst::ICMP_UGE:
6342 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6343 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006344 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006345 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006346 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006347 break;
6348 case ICmpInst::ICMP_ULE:
6349 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6350 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006351 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006352 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006353 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006354 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006355 }
Dan Gohman7934d592009-04-25 17:12:48 +00006356
6357 // Turn a signed comparison into an unsigned one if both operands
6358 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006359 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006360 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6361 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006362 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006363 }
6364
6365 // Test if the ICmpInst instruction is used exclusively by a select as
6366 // part of a minimum or maximum operation. If so, refrain from doing
6367 // any other folding. This helps out other analyses which understand
6368 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6369 // and CodeGen. And in this case, at least one of the comparison
6370 // operands has at least one user besides the compare (the select),
6371 // which would often largely negate the benefit of folding anyway.
6372 if (I.hasOneUse())
6373 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6374 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6375 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6376 return 0;
6377
6378 // See if we are doing a comparison between a constant and an instruction that
6379 // can be folded into the comparison.
6380 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006381 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6382 // instruction, see if that instruction also has constants so that the
6383 // instruction can be folded into the icmp
6384 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6385 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6386 return Res;
6387 }
6388
6389 // Handle icmp with constant (but not simple integer constant) RHS
6390 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6391 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6392 switch (LHSI->getOpcode()) {
6393 case Instruction::GetElementPtr:
6394 if (RHSC->isNullValue()) {
6395 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6396 bool isAllZeros = true;
6397 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6398 if (!isa<Constant>(LHSI->getOperand(i)) ||
6399 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6400 isAllZeros = false;
6401 break;
6402 }
6403 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006404 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006405 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006406 }
6407 break;
6408
6409 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006410 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006411 // block. If in the same block, we're encouraging jump threading. If
6412 // not, we are just pessimizing the code by making an i1 phi.
6413 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006414 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006415 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006416 break;
6417 case Instruction::Select: {
6418 // If either operand of the select is a constant, we can fold the
6419 // comparison into the select arms, which will cause one to be
6420 // constant folded and the select turned into a bitwise or.
6421 Value *Op1 = 0, *Op2 = 0;
Eli Friedman4779a952009-12-18 08:22:35 +00006422 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6423 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6424 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6425 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6426
6427 // We only want to perform this transformation if it will not lead to
6428 // additional code. This is true if either both sides of the select
6429 // fold to a constant (in which case the icmp is replaced with a select
6430 // which will usually simplify) or this is the only user of the
6431 // select (in which case we are trading a select+icmp for a simpler
6432 // select+icmp).
6433 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6434 if (!Op1)
Chris Lattnerc7694852009-08-30 07:44:24 +00006435 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6436 RHSC, I.getName());
Eli Friedman4779a952009-12-18 08:22:35 +00006437 if (!Op2)
6438 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6439 RHSC, I.getName());
Gabor Greifd6da1d02008-04-06 20:25:17 +00006440 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman4779a952009-12-18 08:22:35 +00006441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006442 break;
6443 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006444 case Instruction::Call:
6445 // If we have (malloc != null), and if the malloc has a single use, we
6446 // can assume it is successful and remove the malloc.
6447 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6448 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006449 // Need to explicitly erase malloc call here, instead of adding it to
6450 // Worklist, because it won't get DCE'd from the Worklist since
6451 // isInstructionTriviallyDead() returns false for function calls.
6452 // It is OK to replace LHSI/MallocCall with Undef because the
6453 // instruction that uses it will be erased via Worklist.
6454 if (extractMallocCall(LHSI)) {
6455 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6456 EraseInstFromFunction(*LHSI);
6457 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006458 ConstantInt::get(Type::getInt1Ty(*Context),
6459 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006460 }
6461 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6462 if (MallocCall->hasOneUse()) {
6463 MallocCall->replaceAllUsesWith(
6464 UndefValue::get(MallocCall->getType()));
6465 EraseInstFromFunction(*MallocCall);
6466 Worklist.Add(LHSI); // The malloc's bitcast use.
6467 return ReplaceInstUsesWith(I,
6468 ConstantInt::get(Type::getInt1Ty(*Context),
6469 !I.isTrueWhenEqual()));
6470 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006471 }
6472 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006473 }
6474 }
6475
6476 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006477 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006478 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6479 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006480 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6482 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6483 return NI;
6484
6485 // Test to see if the operands of the icmp are casted versions of other
6486 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6487 // now.
6488 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6489 if (isa<PointerType>(Op0->getType()) &&
6490 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6491 // We keep moving the cast from the left operand over to the right
6492 // operand, where it can often be eliminated completely.
6493 Op0 = CI->getOperand(0);
6494
6495 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6496 // so eliminate it as well.
6497 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6498 Op1 = CI2->getOperand(0);
6499
6500 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006501 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006502 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006503 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006504 } else {
6505 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006506 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006507 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006508 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006509 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006510 }
6511 }
6512
6513 if (isa<CastInst>(Op0)) {
6514 // Handle the special case of: icmp (cast bool to X), <cst>
6515 // This comes up when you have code like
6516 // int X = A < B;
6517 // if (X) ...
6518 // For generality, we handle any zero-extension of any operand comparison
6519 // with a constant or another cast from the same type.
Eli Friedmanbb8954b2009-12-17 21:27:47 +00006520 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006521 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6522 return R;
6523 }
6524
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006525 // See if it's the same type of instruction on the left and right.
6526 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6527 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006528 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006529 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006530 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006531 default: break;
6532 case Instruction::Add:
6533 case Instruction::Sub:
6534 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006535 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006536 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006537 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006538 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6539 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6540 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006541 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006542 ? I.getUnsignedPredicate()
6543 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006544 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006545 Op1I->getOperand(0));
6546 }
6547
6548 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006549 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006550 ? I.getUnsignedPredicate()
6551 : I.getSignedPredicate();
6552 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006553 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006554 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006555 }
6556 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006557 break;
6558 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006559 if (!I.isEquality())
6560 break;
6561
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006562 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6563 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6564 // Mask = -1 >> count-trailing-zeros(Cst).
6565 if (!CI->isZero() && !CI->isOne()) {
6566 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006567 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006568 APInt::getLowBitsSet(AP.getBitWidth(),
6569 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006570 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006571 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6572 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006573 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006574 }
6575 }
6576 break;
6577 }
6578 }
6579 }
6580 }
6581
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006582 // ~x < ~y --> y < x
6583 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006584 if (match(Op0, m_Not(m_Value(A))) &&
6585 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006586 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006587 }
6588
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006589 if (I.isEquality()) {
6590 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006591
6592 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006593 if (match(Op0, m_Neg(m_Value(A))) &&
6594 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006595 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006596
Dan Gohmancdff2122009-08-12 16:23:25 +00006597 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6599 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006600 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006601 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006602 }
6603
Dan Gohmancdff2122009-08-12 16:23:25 +00006604 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006605 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006606 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006607 if (match(B, m_ConstantInt(C1)) &&
6608 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006609 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006610 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006611 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6612 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006613 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006614
6615 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006616 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6617 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6618 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6619 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006620 }
6621 }
6622
Dan Gohmancdff2122009-08-12 16:23:25 +00006623 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006624 (A == Op0 || B == Op0)) {
6625 // A == (A^B) -> B == 0
6626 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006627 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006628 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006629 }
Chris Lattner3b874082008-11-16 05:38:51 +00006630
6631 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006632 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006633 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006634 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006635
6636 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006637 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006638 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006639 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640
6641 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6642 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006643 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6644 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 Value *X = 0, *Y = 0, *Z = 0;
6646
6647 if (A == C) {
6648 X = B; Y = D; Z = A;
6649 } else if (A == D) {
6650 X = B; Y = C; Z = A;
6651 } else if (B == C) {
6652 X = A; Y = D; Z = B;
6653 } else if (B == D) {
6654 X = A; Y = C; Z = B;
6655 }
6656
6657 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006658 Op1 = Builder->CreateXor(X, Y, "tmp");
6659 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006660 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006661 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006662 return &I;
6663 }
6664 }
6665 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006666
6667 {
6668 Value *X; ConstantInt *Cst;
Chris Lattnera54b96b2009-12-21 04:04:05 +00006669 // icmp X+Cst, X
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006670 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattnera54b96b2009-12-21 04:04:05 +00006671 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6672
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006673 // icmp X, X+Cst
6674 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattnera54b96b2009-12-21 04:04:05 +00006675 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006676 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006677 return Changed ? &I : 0;
6678}
6679
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006680/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6681Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6682 Value *X, ConstantInt *CI,
Chris Lattnera54b96b2009-12-21 04:04:05 +00006683 ICmpInst::Predicate Pred,
6684 Value *TheAdd) {
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006685 // If we have X+0, exit early (simplifying logic below) and let it get folded
6686 // elsewhere. icmp X+0, X -> icmp X, X
6687 if (CI->isZero()) {
6688 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6689 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6690 }
6691
6692 // (X+4) == X -> false.
6693 if (Pred == ICmpInst::ICMP_EQ)
6694 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6695
6696 // (X+4) != X -> true.
6697 if (Pred == ICmpInst::ICMP_NE)
6698 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006699
6700 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6701 bool isNUW = false, isNSW = false;
6702 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6703 isNUW = Add->hasNoUnsignedWrap();
6704 isNSW = Add->hasNoSignedWrap();
6705 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006706
6707 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6708 // so the values can never be equal. Similiarly for all other "or equals"
6709 // operators.
6710
6711 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6712 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6713 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6714 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattnera54b96b2009-12-21 04:04:05 +00006715 // If this is an NUW add, then this is always false.
6716 if (isNUW)
6717 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6718
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006719 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6720 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6721 }
6722
6723 // (X+1) >u X --> X <u (0-1) --> X != 255
6724 // (X+2) >u X --> X <u (0-2) --> X <u 254
6725 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattnera54b96b2009-12-21 04:04:05 +00006726 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6727 // If this is an NUW add, then this is always true.
6728 if (isNUW)
6729 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006730 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006731 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006732
6733 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6734 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6735 APInt::getSignedMaxValue(BitWidth));
6736
6737 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6738 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6739 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6740 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6741 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6742 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattnera54b96b2009-12-21 04:04:05 +00006743 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6744 // If this is an NSW add, then we have two cases: if the constant is
6745 // positive, then this is always false, if negative, this is always true.
6746 if (isNSW) {
6747 bool isTrue = CI->getValue().isNegative();
6748 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6749 }
6750
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006751 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006752 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006753
6754 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6755 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6756 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6757 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6758 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6759 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattnera54b96b2009-12-21 04:04:05 +00006760
6761 // If this is an NSW add, then we have two cases: if the constant is
6762 // positive, then this is always true, if negative, this is always false.
6763 if (isNSW) {
6764 bool isTrue = !CI->getValue().isNegative();
6765 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6766 }
6767
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006768 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6769 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6770 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6771}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006772
6773/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6774/// and CmpRHS are both known to be integer constants.
6775Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6776 ConstantInt *DivRHS) {
6777 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6778 const APInt &CmpRHSV = CmpRHS->getValue();
6779
6780 // FIXME: If the operand types don't match the type of the divide
6781 // then don't attempt this transform. The code below doesn't have the
6782 // logic to deal with a signed divide and an unsigned compare (and
6783 // vice versa). This is because (x /s C1) <s C2 produces different
6784 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6785 // (x /u C1) <u C2. Simply casting the operands and result won't
6786 // work. :( The if statement below tests that condition and bails
6787 // if it finds it.
6788 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006789 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006790 return 0;
6791 if (DivRHS->isZero())
6792 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006793 if (DivIsSigned && DivRHS->isAllOnesValue())
6794 return 0; // The overflow computation also screws up here
6795 if (DivRHS->isOne())
6796 return 0; // Not worth bothering, and eliminates some funny cases
6797 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006798
6799 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6800 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6801 // C2 (CI). By solving for X we can turn this into a range check
6802 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006803 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006804
6805 // Determine if the product overflows by seeing if the product is
6806 // not equal to the divide. Make sure we do the same kind of divide
6807 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006808 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6809 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006810
6811 // Get the ICmp opcode
6812 ICmpInst::Predicate Pred = ICI.getPredicate();
6813
6814 // Figure out the interval that is being checked. For example, a comparison
6815 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6816 // Compute this interval based on the constants involved and the signedness of
6817 // the compare/divide. This computes a half-open interval, keeping track of
6818 // whether either value in the interval overflows. After analysis each
6819 // overflow variable is set to 0 if it's corresponding bound variable is valid
6820 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6821 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006822 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006824 if (!DivIsSigned) { // udiv
6825 // e.g. X/5 op 3 --> [15, 20)
6826 LoBound = Prod;
6827 HiOverflow = LoOverflow = ProdOV;
6828 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006829 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006830 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006831 if (CmpRHSV == 0) { // (X / pos) op 0
6832 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006833 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006834 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006835 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006836 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6837 HiOverflow = LoOverflow = ProdOV;
6838 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006839 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006840 } else { // (X / pos) op neg
6841 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006842 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006843 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6844 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006845 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006846 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006847 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006848 true) ? -1 : 0;
6849 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006850 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006851 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006852 if (CmpRHSV == 0) { // (X / neg) op 0
6853 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006854 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006855 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006856 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6857 HiOverflow = 1; // [INTMIN+1, overflow)
6858 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6859 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006860 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006861 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006862 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006863 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6864 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006865 LoOverflow = AddWithOverflow(LoBound, HiBound,
6866 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006867 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006868 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6869 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006870 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006871 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006872 }
6873
6874 // Dividing by a negative swaps the condition. LT <-> GT
6875 Pred = ICmpInst::getSwappedPredicate(Pred);
6876 }
6877
6878 Value *X = DivI->getOperand(0);
6879 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006880 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006881 case ICmpInst::ICMP_EQ:
6882 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006883 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006884 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006885 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006886 ICmpInst::ICMP_UGE, X, LoBound);
6887 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006888 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006889 ICmpInst::ICMP_ULT, X, HiBound);
6890 else
6891 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6892 case ICmpInst::ICMP_NE:
6893 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006894 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006895 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006896 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006897 ICmpInst::ICMP_ULT, X, LoBound);
6898 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006899 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006900 ICmpInst::ICMP_UGE, X, HiBound);
6901 else
6902 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6903 case ICmpInst::ICMP_ULT:
6904 case ICmpInst::ICMP_SLT:
6905 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006906 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006907 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006908 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006909 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006910 case ICmpInst::ICMP_UGT:
6911 case ICmpInst::ICMP_SGT:
6912 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006913 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006914 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006915 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006916 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006917 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006918 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006919 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006920 }
6921}
6922
6923
6924/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6925///
6926Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6927 Instruction *LHSI,
6928 ConstantInt *RHS) {
6929 const APInt &RHSV = RHS->getValue();
6930
6931 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006932 case Instruction::Trunc:
6933 if (ICI.isEquality() && LHSI->hasOneUse()) {
6934 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6935 // of the high bits truncated out of x are known.
6936 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6937 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6938 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6939 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6940 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6941
6942 // If all the high bits are known, we can do this xform.
6943 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6944 // Pull in the high bits from known-ones set.
6945 APInt NewRHS(RHS->getValue());
6946 NewRHS.zext(SrcBits);
6947 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006948 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006949 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006950 }
6951 }
6952 break;
6953
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006954 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6955 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6956 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6957 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006958 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6959 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006960 Value *CompareVal = LHSI->getOperand(0);
6961
6962 // If the sign bit of the XorCST is not set, there is no change to
6963 // the operation, just stop using the Xor.
6964 if (!XorCST->getValue().isNegative()) {
6965 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006966 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006967 return &ICI;
6968 }
6969
6970 // Was the old condition true if the operand is positive?
6971 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6972
6973 // If so, the new one isn't.
6974 isTrueIfPositive ^= true;
6975
6976 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006977 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006978 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006979 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006980 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006981 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006982 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006983
6984 if (LHSI->hasOneUse()) {
6985 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6986 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6987 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006988 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006989 ? ICI.getUnsignedPredicate()
6990 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006991 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006992 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006993 }
6994
6995 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006996 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006997 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006998 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006999 ? ICI.getUnsignedPredicate()
7000 : ICI.getSignedPredicate();
7001 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00007002 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007003 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00007004 }
7005 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007006 }
7007 break;
7008 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7009 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7010 LHSI->getOperand(0)->hasOneUse()) {
7011 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7012
7013 // If the LHS is an AND of a truncating cast, we can widen the
7014 // and/compare to be the input width without changing the value
7015 // produced, eliminating a cast.
7016 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7017 // We can do this transformation if either the AND constant does not
7018 // have its sign bit set or if it is an equality comparison.
7019 // Extending a relational comparison when we're checking the sign
7020 // bit would not work.
7021 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00007022 (ICI.isEquality() ||
7023 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007024 uint32_t BitWidth =
7025 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7026 APInt NewCST = AndCST->getValue();
7027 NewCST.zext(BitWidth);
7028 APInt NewCI = RHSV;
7029 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00007030 Value *NewAnd =
7031 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007032 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007033 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007034 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007035 }
7036 }
7037
7038 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7039 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7040 // happens a LOT in code produced by the C front-end, for bitfield
7041 // access.
7042 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7043 if (Shift && !Shift->isShift())
7044 Shift = 0;
7045
7046 ConstantInt *ShAmt;
7047 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7048 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7049 const Type *AndTy = AndCST->getType(); // Type of the and.
7050
7051 // We can fold this as long as we can't shift unknown bits
7052 // into the mask. This can only happen with signed shift
7053 // rights, as they sign-extend.
7054 if (ShAmt) {
7055 bool CanFold = Shift->isLogicalShift();
7056 if (!CanFold) {
7057 // To test for the bad case of the signed shr, see if any
7058 // of the bits shifted in could be tested after the mask.
7059 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7060 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7061
7062 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7063 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7064 AndCST->getValue()) == 0)
7065 CanFold = true;
7066 }
7067
7068 if (CanFold) {
7069 Constant *NewCst;
7070 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00007071 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007072 else
Owen Anderson02b48c32009-07-29 18:55:55 +00007073 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007074
7075 // Check to see if we are shifting out any of the bits being
7076 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00007077 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007078 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007079 // If we shifted bits out, the fold is not going to work out.
7080 // As a special case, check to see if this means that the
7081 // result is always true or false now.
7082 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007083 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007085 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007086 } else {
7087 ICI.setOperand(1, NewCst);
7088 Constant *NewAndCST;
7089 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00007090 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007091 else
Owen Anderson02b48c32009-07-29 18:55:55 +00007092 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007093 LHSI->setOperand(1, NewAndCST);
7094 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00007095 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007096 return &ICI;
7097 }
7098 }
7099 }
7100
7101 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7102 // preferable because it allows the C<<Y expression to be hoisted out
7103 // of a loop if Y is invariant and X is not.
7104 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00007105 ICI.isEquality() && !Shift->isArithmeticShift() &&
7106 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007107 // Compute C << Y.
7108 Value *NS;
7109 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007110 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111 } else {
7112 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00007113 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007114 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007115
7116 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00007117 Value *NewAnd =
7118 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007119
7120 ICI.setOperand(0, NewAnd);
7121 return &ICI;
7122 }
7123 }
7124 break;
7125
7126 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7127 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7128 if (!ShAmt) break;
7129
7130 uint32_t TypeBits = RHSV.getBitWidth();
7131
7132 // Check that the shift amount is in range. If not, don't perform
7133 // undefined shifts. When the shift is visited it will be
7134 // simplified.
7135 if (ShAmt->uge(TypeBits))
7136 break;
7137
7138 if (ICI.isEquality()) {
7139 // If we are comparing against bits always shifted out, the
7140 // comparison cannot succeed.
7141 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00007142 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00007143 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7145 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007146 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 return ReplaceInstUsesWith(ICI, Cst);
7148 }
7149
7150 if (LHSI->hasOneUse()) {
7151 // Otherwise strength reduce the shift into an and.
7152 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7153 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007154 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00007155 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007156
Chris Lattnerc7694852009-08-30 07:44:24 +00007157 Value *And =
7158 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007159 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007160 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007161 }
7162 }
7163
7164 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7165 bool TrueIfSigned = false;
7166 if (LHSI->hasOneUse() &&
7167 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7168 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00007169 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007170 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00007171 Value *And =
7172 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007173 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00007174 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007175 }
7176 break;
7177 }
7178
7179 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
7180 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007181 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007182 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007183 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007184
Chris Lattner5ee84f82008-03-21 05:19:58 +00007185 // Check that the shift amount is in range. If not, don't perform
7186 // undefined shifts. When the shift is visited it will be
7187 // simplified.
7188 uint32_t TypeBits = RHSV.getBitWidth();
7189 if (ShAmt->uge(TypeBits))
7190 break;
7191
7192 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007193
Chris Lattner5ee84f82008-03-21 05:19:58 +00007194 // If we are comparing against bits always shifted out, the
7195 // comparison cannot succeed.
7196 APInt Comp = RHSV << ShAmtVal;
7197 if (LHSI->getOpcode() == Instruction::LShr)
7198 Comp = Comp.lshr(ShAmtVal);
7199 else
7200 Comp = Comp.ashr(ShAmtVal);
7201
7202 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7203 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007204 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007205 return ReplaceInstUsesWith(ICI, Cst);
7206 }
7207
7208 // Otherwise, check to see if the bits shifted out are known to be zero.
7209 // If so, we can compare against the unshifted value:
7210 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007211 if (LHSI->hasOneUse() &&
7212 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007213 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007214 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007215 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007216 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007217
Evan Chengfb9292a2008-04-23 00:38:06 +00007218 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007219 // Otherwise strength reduce the shift into an and.
7220 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007221 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007222
Chris Lattnerc7694852009-08-30 07:44:24 +00007223 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7224 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007225 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007226 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007227 }
7228 break;
7229 }
7230
7231 case Instruction::SDiv:
7232 case Instruction::UDiv:
7233 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7234 // Fold this div into the comparison, producing a range check.
7235 // Determine, based on the divide type, what the range is being
7236 // checked. If there is an overflow on the low or high side, remember
7237 // it, otherwise compute the range [low, hi) bounding the new value.
7238 // See: InsertRangeTest above for the kinds of replacements possible.
7239 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7240 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7241 DivRHS))
7242 return R;
7243 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007244
7245 case Instruction::Add:
Chris Lattner258a2ffb2009-12-21 03:19:28 +00007246 // Fold: icmp pred (add X, C1), C2
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007247 if (!ICI.isEquality()) {
7248 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7249 if (!LHSC) break;
7250 const APInt &LHSV = LHSC->getValue();
7251
7252 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7253 .subtract(LHSV);
7254
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007255 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007256 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007257 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007258 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007259 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007260 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007261 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007262 }
7263 } else {
7264 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007265 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007266 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007267 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007268 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007269 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007270 }
7271 }
7272 }
7273 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007274 }
7275
7276 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7277 if (ICI.isEquality()) {
7278 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7279
7280 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7281 // the second operand is a constant, simplify a bit.
7282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7283 switch (BO->getOpcode()) {
7284 case Instruction::SRem:
7285 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7286 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7287 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7288 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007289 Value *NewRem =
7290 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7291 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007292 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007293 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007294 }
7295 }
7296 break;
7297 case Instruction::Add:
7298 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7299 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7300 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007301 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007302 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007303 } else if (RHSV == 0) {
7304 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7305 // efficiently invertible, or if the add has just this one use.
7306 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7307
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007308 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007309 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007310 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007311 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007312 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007313 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007314 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007315 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007316 }
7317 }
7318 break;
7319 case Instruction::Xor:
7320 // For the xor case, we can xor two constants together, eliminating
7321 // the explicit xor.
7322 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007323 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007324 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007325
7326 // FALLTHROUGH
7327 case Instruction::Sub:
7328 // Replace (([sub|xor] A, B) != 0) with (A != B)
7329 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007330 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007331 BO->getOperand(1));
7332 break;
7333
7334 case Instruction::Or:
7335 // If bits are being or'd in that are not present in the constant we
7336 // are comparing against, then the comparison could never succeed!
7337 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007338 Constant *NotCI = ConstantExpr::getNot(RHS);
7339 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007340 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007341 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007342 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007343 }
7344 break;
7345
7346 case Instruction::And:
7347 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7348 // If bits are being compared against that are and'd out, then the
7349 // comparison can never succeed!
7350 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007351 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007352 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007353 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007354
7355 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7356 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007357 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007358 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007359 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007360
7361 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007362 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007363 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007364 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007365 ICmpInst::Predicate pred = isICMP_NE ?
7366 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007367 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007368 }
7369
7370 // ((X & ~7) == 0) --> X < 8
7371 if (RHSV == 0 && isHighOnes(BOC)) {
7372 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007373 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007374 ICmpInst::Predicate pred = isICMP_NE ?
7375 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007376 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007377 }
7378 }
7379 default: break;
7380 }
7381 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7382 // Handle icmp {eq|ne} <intrinsic>, intcst.
7383 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007384 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007385 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007386 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007387 return &ICI;
7388 }
7389 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390 }
7391 return 0;
7392}
7393
7394/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7395/// We only handle extending casts so far.
7396///
7397Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7398 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7399 Value *LHSCIOp = LHSCI->getOperand(0);
7400 const Type *SrcTy = LHSCIOp->getType();
7401 const Type *DestTy = LHSCI->getType();
7402 Value *RHSCIOp;
7403
7404 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7405 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007406 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7407 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007408 cast<IntegerType>(DestTy)->getBitWidth()) {
7409 Value *RHSOp = 0;
7410 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007411 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007412 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7413 RHSOp = RHSC->getOperand(0);
7414 // If the pointer types don't match, insert a bitcast.
7415 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007416 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007417 }
7418
7419 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007420 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007421 }
7422
7423 // The code below only handles extension cast instructions, so far.
7424 // Enforce this.
7425 if (LHSCI->getOpcode() != Instruction::ZExt &&
7426 LHSCI->getOpcode() != Instruction::SExt)
7427 return 0;
7428
7429 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007430 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007431
7432 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7433 // Not an extension from the same type?
7434 RHSCIOp = CI->getOperand(0);
7435 if (RHSCIOp->getType() != LHSCIOp->getType())
7436 return 0;
7437
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007438 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007439 // and the other is a zext), then we can't handle this.
7440 if (CI->getOpcode() != LHSCI->getOpcode())
7441 return 0;
7442
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007443 // Deal with equality cases early.
7444 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007445 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007446
7447 // A signed comparison of sign extended values simplifies into a
7448 // signed comparison.
7449 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007450 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007451
7452 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007453 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007454 }
7455
7456 // If we aren't dealing with a constant on the RHS, exit early
7457 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7458 if (!CI)
7459 return 0;
7460
7461 // Compute the constant that would happen if we truncated to SrcTy then
7462 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007463 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7464 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007465 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466
7467 // If the re-extended constant didn't change...
7468 if (Res2 == CI) {
Eli Friedman96438472009-12-17 22:42:29 +00007469 // Deal with equality cases early.
7470 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007471 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedman96438472009-12-17 22:42:29 +00007472
7473 // A signed comparison of sign extended values simplifies into a
7474 // signed comparison.
7475 if (isSignedExt && isSignedCmp)
7476 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7477
7478 // The other three cases all fold into an unsigned comparison.
7479 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007480 }
7481
7482 // The re-extended constant changed so the constant cannot be represented
7483 // in the shorter type. Consequently, we cannot emit a simple comparison.
7484
7485 // First, handle some easy cases. We know the result cannot be equal at this
7486 // point so handle the ICI.isEquality() cases
7487 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007488 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007489 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007490 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007491
7492 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7493 // should have been folded away previously and not enter in here.
7494 Value *Result;
7495 if (isSignedCmp) {
7496 // We're performing a signed comparison.
7497 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007498 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007499 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007500 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007501 } else {
7502 // We're performing an unsigned comparison.
7503 if (isSignedExt) {
7504 // We're performing an unsigned comp with a sign extended value.
7505 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007506 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007507 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007508 } else {
7509 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007510 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007511 }
7512 }
7513
7514 // Finally, return the value computed.
7515 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007516 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007517 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007518
7519 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7520 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7521 "ICmp should be folded!");
7522 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007523 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007524 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007525}
7526
7527Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7528 return commonShiftTransforms(I);
7529}
7530
7531Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7532 return commonShiftTransforms(I);
7533}
7534
7535Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007536 if (Instruction *R = commonShiftTransforms(I))
7537 return R;
7538
7539 Value *Op0 = I.getOperand(0);
7540
7541 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7542 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7543 if (CSI->isAllOnesValue())
7544 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007545
Dan Gohman2526aea2009-06-16 19:55:29 +00007546 // See if we can turn a signed shr into an unsigned shr.
7547 if (MaskedValueIsZero(Op0,
7548 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7549 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7550
7551 // Arithmetic shifting an all-sign-bit value is a no-op.
7552 unsigned NumSignBits = ComputeNumSignBits(Op0);
7553 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7554 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007555
Chris Lattnere3c504f2007-12-06 01:59:46 +00007556 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007557}
7558
7559Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7560 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7562
7563 // shl X, 0 == X and shr X, 0 == X
7564 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007565 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7566 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007567 return ReplaceInstUsesWith(I, Op0);
7568
7569 if (isa<UndefValue>(Op0)) {
7570 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7571 return ReplaceInstUsesWith(I, Op0);
7572 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007573 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007574 }
7575 if (isa<UndefValue>(Op1)) {
7576 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7577 return ReplaceInstUsesWith(I, Op0);
7578 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007579 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007580 }
7581
Dan Gohman2bc21562009-05-21 02:28:33 +00007582 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007583 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007584 return &I;
7585
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007586 // Try to fold constant and into select arguments.
7587 if (isa<Constant>(Op0))
7588 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7589 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7590 return R;
7591
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007592 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7593 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7594 return Res;
7595 return 0;
7596}
7597
7598Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7599 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007600 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007601
7602 // See if we can simplify any instructions used by the instruction whose sole
7603 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007604 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007605
Dan Gohman9e1657f2009-06-14 23:30:43 +00007606 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7607 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007608 //
7609 if (Op1->uge(TypeBits)) {
7610 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007611 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007612 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007613 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007614 return &I;
7615 }
7616 }
7617
7618 // ((X*C1) << C2) == (X * (C1 << C2))
7619 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7620 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7621 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007622 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007623 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007624
7625 // Try to fold constant and into select arguments.
7626 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7627 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7628 return R;
7629 if (isa<PHINode>(Op0))
7630 if (Instruction *NV = FoldOpIntoPhi(I))
7631 return NV;
7632
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007633 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7634 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7635 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7636 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7637 // place. Don't try to do this transformation in this case. Also, we
7638 // require that the input operand is a shift-by-constant so that we have
7639 // confidence that the shifts will get folded together. We could do this
7640 // xform in more cases, but it is unlikely to be profitable.
7641 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7642 isa<ConstantInt>(TrOp->getOperand(1))) {
7643 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007644 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007645 // (shift2 (shift1 & 0x00FF), c2)
7646 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007647
7648 // For logical shifts, the truncation has the effect of making the high
7649 // part of the register be zeros. Emulate this by inserting an AND to
7650 // clear the top bits as needed. This 'and' will usually be zapped by
7651 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007652 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7653 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007654 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7655
7656 // The mask we constructed says what the trunc would do if occurring
7657 // between the shifts. We want to know the effect *after* the second
7658 // shift. We know that it is a logical shift by a constant, so adjust the
7659 // mask as appropriate.
7660 if (I.getOpcode() == Instruction::Shl)
7661 MaskV <<= Op1->getZExtValue();
7662 else {
7663 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7664 MaskV = MaskV.lshr(Op1->getZExtValue());
7665 }
7666
Chris Lattnerc7694852009-08-30 07:44:24 +00007667 // shift1 & 0x00FF
7668 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7669 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007670
7671 // Return the value truncated to the interesting size.
7672 return new TruncInst(And, I.getType());
7673 }
7674 }
7675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007676 if (Op0->hasOneUse()) {
7677 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7678 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7679 Value *V1, *V2;
7680 ConstantInt *CC;
7681 switch (Op0BO->getOpcode()) {
7682 default: break;
7683 case Instruction::Add:
7684 case Instruction::And:
7685 case Instruction::Or:
7686 case Instruction::Xor: {
7687 // These operators commute.
7688 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7689 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007690 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007691 m_Specific(Op1)))) {
7692 Value *YS = // (Y << C)
7693 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7694 // (X + (Y << C))
7695 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7696 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007697 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007698 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007699 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7700 }
7701
7702 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7703 Value *Op0BOOp1 = Op0BO->getOperand(1);
7704 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7705 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007706 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007707 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007708 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007709 Value *YS = // (Y << C)
7710 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7711 Op0BO->getName());
7712 // X & (CC << C)
7713 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7714 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007715 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 }
7717 }
7718
7719 // FALL THROUGH.
7720 case Instruction::Sub: {
7721 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7722 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007723 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007724 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007725 Value *YS = // (Y << C)
7726 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7727 // (X + (Y << C))
7728 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7729 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007730 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007731 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007732 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7733 }
7734
7735 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7736 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7737 match(Op0BO->getOperand(0),
7738 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007739 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007740 cast<BinaryOperator>(Op0BO->getOperand(0))
7741 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007742 Value *YS = // (Y << C)
7743 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7744 // X & (CC << C)
7745 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7746 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007747
Gabor Greifa645dd32008-05-16 19:29:10 +00007748 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007749 }
7750
7751 break;
7752 }
7753 }
7754
7755
7756 // If the operand is an bitwise operator with a constant RHS, and the
7757 // shift is the only use, we can pull it out of the shift.
7758 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7759 bool isValid = true; // Valid only for And, Or, Xor
7760 bool highBitSet = false; // Transform if high bit of constant set?
7761
7762 switch (Op0BO->getOpcode()) {
7763 default: isValid = false; break; // Do not perform transform!
7764 case Instruction::Add:
7765 isValid = isLeftShift;
7766 break;
7767 case Instruction::Or:
7768 case Instruction::Xor:
7769 highBitSet = false;
7770 break;
7771 case Instruction::And:
7772 highBitSet = true;
7773 break;
7774 }
7775
7776 // If this is a signed shift right, and the high bit is modified
7777 // by the logical operation, do not perform the transformation.
7778 // The highBitSet boolean indicates the value of the high bit of
7779 // the constant which would cause it to be modified for this
7780 // operation.
7781 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007782 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007783 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007784
7785 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007786 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007787
Chris Lattnerad7516a2009-08-30 18:50:58 +00007788 Value *NewShift =
7789 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007790 NewShift->takeName(Op0BO);
7791
Gabor Greifa645dd32008-05-16 19:29:10 +00007792 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007793 NewRHS);
7794 }
7795 }
7796 }
7797 }
7798
7799 // Find out if this is a shift of a shift by a constant.
7800 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7801 if (ShiftOp && !ShiftOp->isShift())
7802 ShiftOp = 0;
7803
7804 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7805 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7806 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7807 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7808 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7809 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7810 Value *X = ShiftOp->getOperand(0);
7811
7812 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007813
7814 const IntegerType *Ty = cast<IntegerType>(I.getType());
7815
7816 // Check for (X << c1) << c2 and (X >> c1) >> c2
7817 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007818 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7819 // saturates.
7820 if (AmtSum >= TypeBits) {
7821 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007822 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007823 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7824 }
7825
Gabor Greifa645dd32008-05-16 19:29:10 +00007826 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007827 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007828 }
7829
7830 if (ShiftOp->getOpcode() == Instruction::LShr &&
7831 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007832 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007835 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007836 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007837 }
7838
7839 if (ShiftOp->getOpcode() == Instruction::AShr &&
7840 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007841 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007842 if (AmtSum >= TypeBits)
7843 AmtSum = TypeBits-1;
7844
Chris Lattnerad7516a2009-08-30 18:50:58 +00007845 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007846
7847 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007848 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007849 }
7850
7851 // Okay, if we get here, one shift must be left, and the other shift must be
7852 // right. See if the amounts are equal.
7853 if (ShiftAmt1 == ShiftAmt2) {
7854 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7855 if (I.getOpcode() == Instruction::Shl) {
7856 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007857 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007858 }
7859 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7860 if (I.getOpcode() == Instruction::LShr) {
7861 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007862 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007863 }
7864 // We can simplify ((X << C) >>s C) into a trunc + sext.
7865 // NOTE: we could do this for any C, but that would make 'unusual' integer
7866 // types. For now, just stick to ones well-supported by the code
7867 // generators.
7868 const Type *SExtType = 0;
7869 switch (Ty->getBitWidth() - ShiftAmt1) {
7870 case 1 :
7871 case 8 :
7872 case 16 :
7873 case 32 :
7874 case 64 :
7875 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007876 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007877 break;
7878 default: break;
7879 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007880 if (SExtType)
7881 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007882 // Otherwise, we can't handle it yet.
7883 } else if (ShiftAmt1 < ShiftAmt2) {
7884 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7885
7886 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7887 if (I.getOpcode() == Instruction::Shl) {
7888 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7889 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007890 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007891
7892 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007893 return BinaryOperator::CreateAnd(Shift,
7894 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007895 }
7896
7897 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7898 if (I.getOpcode() == Instruction::LShr) {
7899 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007900 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007901
7902 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007903 return BinaryOperator::CreateAnd(Shift,
7904 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007905 }
7906
7907 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7908 } else {
7909 assert(ShiftAmt2 < ShiftAmt1);
7910 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7911
7912 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7913 if (I.getOpcode() == Instruction::Shl) {
7914 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7915 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007916 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7917 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007918
7919 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007920 return BinaryOperator::CreateAnd(Shift,
7921 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007922 }
7923
7924 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7925 if (I.getOpcode() == Instruction::LShr) {
7926 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007927 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928
7929 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007930 return BinaryOperator::CreateAnd(Shift,
7931 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007932 }
7933
7934 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7935 }
7936 }
7937 return 0;
7938}
7939
7940
7941/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7942/// expression. If so, decompose it, returning some value X, such that Val is
7943/// X*Scale+Offset.
7944///
7945static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007946 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007947 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7948 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007949 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7950 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007951 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007952 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007953 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7954 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7955 if (I->getOpcode() == Instruction::Shl) {
7956 // This is a value scaled by '1 << the shift amt'.
7957 Scale = 1U << RHS->getZExtValue();
7958 Offset = 0;
7959 return I->getOperand(0);
7960 } else if (I->getOpcode() == Instruction::Mul) {
7961 // This value is scaled by 'RHS'.
7962 Scale = RHS->getZExtValue();
7963 Offset = 0;
7964 return I->getOperand(0);
7965 } else if (I->getOpcode() == Instruction::Add) {
7966 // We have X+C. Check to see if we really have (X*C2)+C1,
7967 // where C1 is divisible by C2.
7968 unsigned SubScale;
7969 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007970 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7971 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007972 Offset += RHS->getZExtValue();
7973 Scale = SubScale;
7974 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007975 }
7976 }
7977 }
7978
7979 // Otherwise, we can't look past this.
7980 Scale = 1;
7981 Offset = 0;
7982 return Val;
7983}
7984
7985
7986/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7987/// try to eliminate the cast by moving the type information into the alloc.
7988Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00007989 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007990 const PointerType *PTy = cast<PointerType>(CI.getType());
7991
Chris Lattnerad7516a2009-08-30 18:50:58 +00007992 BuilderTy AllocaBuilder(*Builder);
7993 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7994
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007995 // Remove any uses of AI that are dead.
7996 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7997
7998 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7999 Instruction *User = cast<Instruction>(*UI++);
8000 if (isInstructionTriviallyDead(User)) {
8001 while (UI != E && *UI == User)
8002 ++UI; // If this instruction uses AI more than once, don't break UI.
8003
8004 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00008005 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008006 EraseInstFromFunction(*User);
8007 }
8008 }
Dan Gohmana80e2712009-07-21 23:21:54 +00008009
8010 // This requires TargetData to get the alloca alignment and size information.
8011 if (!TD) return 0;
8012
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008013 // Get the type really allocated and the type casted to.
8014 const Type *AllocElTy = AI.getAllocatedType();
8015 const Type *CastElTy = PTy->getElementType();
8016 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
8017
8018 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8019 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
8020 if (CastElTyAlign < AllocElTyAlign) return 0;
8021
8022 // If the allocation has multiple uses, only promote it if we are strictly
8023 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00008024 // same, we open the door to infinite loops of various kinds. (A reference
8025 // from a dbg.declare doesn't count as a use for this purpose.)
8026 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8027 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008028
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008029 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8030 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
8032
8033 // See if we can satisfy the modulus by pulling a scale out of the array
8034 // size argument.
8035 unsigned ArraySizeScale;
8036 int ArrayOffset;
8037 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00008038 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8039 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008040
8041 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8042 // do the xform.
8043 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8044 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
8045
8046 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8047 Value *Amt = 0;
8048 if (Scale == 1) {
8049 Amt = NumElements;
8050 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00008051 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008052 // Insert before the alloca, not before the cast.
8053 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008054 }
8055
8056 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00008057 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008058 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008059 }
8060
Victor Hernandezb1687302009-10-23 21:09:37 +00008061 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008062 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008063 New->takeName(&AI);
8064
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00008065 // If the allocation has one real use plus a dbg.declare, just remove the
8066 // declare.
8067 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8068 EraseInstFromFunction(*DI);
8069 }
8070 // If the allocation has multiple real uses, insert a cast and change all
8071 // things that used it to use the new cast. This will also hack on CI, but it
8072 // will die soon.
8073 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008074 // New is the allocation instruction, pointer typed. AI is the original
8075 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008076 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008077 AI.replaceAllUsesWith(NewCast);
8078 }
8079 return ReplaceInstUsesWith(CI, New);
8080}
8081
8082/// CanEvaluateInDifferentType - Return true if we can take the specified value
8083/// and return it as type Ty without inserting any new casts and without
8084/// changing the computed value. This is used by code that tries to decide
8085/// whether promoting or shrinking integer operations to wider or smaller types
8086/// will allow us to eliminate a truncate or extend.
8087///
8088/// This is a truncation operation if Ty is smaller than V->getType(), or an
8089/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00008090///
8091/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8092/// should return true if trunc(V) can be computed by computing V in the smaller
8093/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8094/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8095/// efficiently truncated.
8096///
8097/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8098/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8099/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008100bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00008101 unsigned CastOpc,
8102 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008103 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008104 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008105 return true;
8106
8107 Instruction *I = dyn_cast<Instruction>(V);
8108 if (!I) return false;
8109
Dan Gohman8fd520a2009-06-15 22:12:54 +00008110 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008111
Chris Lattneref70bb82007-08-02 06:11:14 +00008112 // If this is an extension or truncate, we can often eliminate it.
8113 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8114 // If this is a cast from the destination type, we can trivially eliminate
8115 // it, and this will remove a cast overall.
8116 if (I->getOperand(0)->getType() == Ty) {
8117 // If the first operand is itself a cast, and is eliminable, do not count
8118 // this as an eliminable cast. We would prefer to eliminate those two
8119 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00008120 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00008121 ++NumCastsRemoved;
8122 return true;
8123 }
8124 }
8125
8126 // We can't extend or shrink something that has multiple uses: doing so would
8127 // require duplicating the instruction in general, which isn't profitable.
8128 if (!I->hasOneUse()) return false;
8129
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008130 unsigned Opc = I->getOpcode();
8131 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008132 case Instruction::Add:
8133 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008134 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008135 case Instruction::And:
8136 case Instruction::Or:
8137 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008138 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00008139 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008140 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00008141 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008142 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008143
Eli Friedman08c45bc2009-07-13 22:46:01 +00008144 case Instruction::UDiv:
8145 case Instruction::URem: {
8146 // UDiv and URem can be truncated if all the truncated bits are zero.
8147 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8148 uint32_t BitWidth = Ty->getScalarSizeInBits();
8149 if (BitWidth < OrigBitWidth) {
8150 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8151 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8152 MaskedValueIsZero(I->getOperand(1), Mask)) {
8153 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8154 NumCastsRemoved) &&
8155 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8156 NumCastsRemoved);
8157 }
8158 }
8159 break;
8160 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008161 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008162 // If we are truncating the result of this SHL, and if it's a shift of a
8163 // constant amount, we can always perform a SHL in a smaller type.
8164 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008165 uint32_t BitWidth = Ty->getScalarSizeInBits();
8166 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008167 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008168 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008169 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008170 }
8171 break;
8172 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008173 // If this is a truncate of a logical shr, we can truncate it to a smaller
8174 // lshr iff we know that the bits we would otherwise be shifting in are
8175 // already zeros.
8176 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008177 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8178 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008179 if (BitWidth < OrigBitWidth &&
8180 MaskedValueIsZero(I->getOperand(0),
8181 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8182 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008183 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008184 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008185 }
8186 }
8187 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008188 case Instruction::ZExt:
8189 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008190 case Instruction::Trunc:
8191 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008192 // can safely replace it. Note that replacing it does not reduce the number
8193 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008194 if (Opc == CastOpc)
8195 return true;
8196
8197 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008198 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008199 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008200 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008201 case Instruction::Select: {
8202 SelectInst *SI = cast<SelectInst>(I);
8203 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008204 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008205 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008206 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008207 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008208 case Instruction::PHI: {
8209 // We can change a phi if we can change all operands.
8210 PHINode *PN = cast<PHINode>(I);
8211 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8212 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008213 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008214 return false;
8215 return true;
8216 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008217 default:
8218 // TODO: Can handle more cases here.
8219 break;
8220 }
8221
8222 return false;
8223}
8224
8225/// EvaluateInDifferentType - Given an expression that
8226/// CanEvaluateInDifferentType returns true for, actually insert the code to
8227/// evaluate the expression.
8228Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8229 bool isSigned) {
8230 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008231 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008232
8233 // Otherwise, it must be an instruction.
8234 Instruction *I = cast<Instruction>(V);
8235 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008236 unsigned Opc = I->getOpcode();
8237 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008238 case Instruction::Add:
8239 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008240 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008241 case Instruction::And:
8242 case Instruction::Or:
8243 case Instruction::Xor:
8244 case Instruction::AShr:
8245 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008246 case Instruction::Shl:
8247 case Instruction::UDiv:
8248 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008249 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8250 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008251 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008252 break;
8253 }
8254 case Instruction::Trunc:
8255 case Instruction::ZExt:
8256 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008257 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008258 // just return the source. There's no need to insert it because it is not
8259 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008260 if (I->getOperand(0)->getType() == Ty)
8261 return I->getOperand(0);
8262
Chris Lattner4200c2062008-06-18 04:00:49 +00008263 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008264 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008265 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008266 case Instruction::Select: {
8267 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8268 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8269 Res = SelectInst::Create(I->getOperand(0), True, False);
8270 break;
8271 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008272 case Instruction::PHI: {
8273 PHINode *OPN = cast<PHINode>(I);
8274 PHINode *NPN = PHINode::Create(Ty);
8275 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8276 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8277 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8278 }
8279 Res = NPN;
8280 break;
8281 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008282 default:
8283 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008284 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008285 break;
8286 }
8287
Chris Lattner4200c2062008-06-18 04:00:49 +00008288 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008289 return InsertNewInstBefore(Res, *I);
8290}
8291
8292/// @brief Implement the transforms common to all CastInst visitors.
8293Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8294 Value *Src = CI.getOperand(0);
8295
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8297 // eliminate it now.
8298 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8299 if (Instruction::CastOps opc =
8300 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8301 // The first cast (CSrc) is eliminable so we need to fix up or replace
8302 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008303 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008304 }
8305 }
8306
8307 // If we are casting a select then fold the cast into the select
8308 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8309 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8310 return NV;
8311
8312 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00008313 if (isa<PHINode>(Src)) {
8314 // We don't do this if this would create a PHI node with an illegal type if
8315 // it is currently legal.
8316 if (!isa<IntegerType>(Src->getType()) ||
8317 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerd0011092009-11-10 07:23:37 +00008318 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008319 if (Instruction *NV = FoldOpIntoPhi(CI))
8320 return NV;
Chris Lattner1cd526b2009-11-08 19:23:30 +00008321 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008322
8323 return 0;
8324}
8325
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008326/// FindElementAtOffset - Given a type and a constant offset, determine whether
8327/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008328/// the specified offset. If so, fill them into NewIndices and return the
8329/// resultant element type, otherwise return null.
8330static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8331 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008332 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008333 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008334 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008335 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008336
8337 // Start with the index over the outer type. Note that the type size
8338 // might be zero (even if the offset isn't zero) if the indexed type
8339 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008340 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008341 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008342 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008343 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008344 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008345
Chris Lattnerce48c462009-01-11 20:15:20 +00008346 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008347 if (Offset < 0) {
8348 --FirstIdx;
8349 Offset += TySize;
8350 assert(Offset >= 0);
8351 }
8352 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8353 }
8354
Owen Andersoneacb44d2009-07-24 23:12:02 +00008355 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008356
8357 // Index into the types. If we fail, set OrigBase to null.
8358 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008359 // Indexing into tail padding between struct/array elements.
8360 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008361 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008362
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008363 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8364 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008365 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8366 "Offset must stay within the indexed type");
8367
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008368 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008369 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008370
8371 Offset -= SL->getElementOffset(Elt);
8372 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008373 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008374 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008375 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008376 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008377 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008378 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008379 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008380 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008381 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008382 }
8383 }
8384
Chris Lattner54dddc72009-01-24 01:00:13 +00008385 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008386}
8387
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008388/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8389Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8390 Value *Src = CI.getOperand(0);
8391
8392 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8393 // If casting the result of a getelementptr instruction with no offset, turn
8394 // this into a cast of the original pointer!
8395 if (GEP->hasAllZeroIndices()) {
8396 // Changing the cast operand is usually not a good idea but it is safe
8397 // here because the pointer operand is being replaced with another
8398 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008399 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008400 CI.setOperand(0, GEP->getOperand(0));
8401 return &CI;
8402 }
8403
8404 // If the GEP has a single use, and the base pointer is a bitcast, and the
8405 // GEP computes a constant offset, see if we can convert these three
8406 // instructions into fewer. This typically happens with unions and other
8407 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008408 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008409 if (GEP->hasAllConstantIndices()) {
8410 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +00008411 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008412 int64_t Offset = OffsetV->getSExtValue();
8413
8414 // Get the base pointer input of the bitcast, and the type it points to.
8415 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8416 const Type *GEPIdxTy =
8417 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008418 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008419 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008420 // If we were able to index down into an element, create the GEP
8421 // and bitcast the result. This eliminates one bitcast, potentially
8422 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008423 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8424 Builder->CreateInBoundsGEP(OrigBase,
8425 NewIndices.begin(), NewIndices.end()) :
8426 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008427 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008428
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008429 if (isa<BitCastInst>(CI))
8430 return new BitCastInst(NGEP, CI.getType());
8431 assert(isa<PtrToIntInst>(CI));
8432 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 }
8434 }
8435 }
8436 }
8437
8438 return commonCastTransforms(CI);
8439}
8440
Eli Friedman827e37a2009-07-13 20:58:59 +00008441/// commonIntCastTransforms - This function implements the common transforms
8442/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008443Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8444 if (Instruction *Result = commonCastTransforms(CI))
8445 return Result;
8446
8447 Value *Src = CI.getOperand(0);
8448 const Type *SrcTy = Src->getType();
8449 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008450 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8451 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008452
8453 // See if we can simplify any instructions used by the LHS whose sole
8454 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008455 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008456 return &CI;
8457
8458 // If the source isn't an instruction or has more than one use then we
8459 // can't do anything more.
8460 Instruction *SrcI = dyn_cast<Instruction>(Src);
8461 if (!SrcI || !Src->hasOneUse())
8462 return 0;
8463
8464 // Attempt to propagate the cast into the instruction for int->int casts.
8465 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008466 // Only do this if the dest type is a simple type, don't convert the
8467 // expression tree to something weird like i93 unless the source is also
8468 // strange.
Chris Lattnerbc5d0132009-11-10 17:00:47 +00008469 if ((isa<VectorType>(DestTy) ||
8470 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8471 CanEvaluateInDifferentType(SrcI, DestTy,
8472 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008473 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008474 // eliminates the cast, so it is always a win. If this is a zero-extension,
8475 // we need to do an AND to maintain the clear top-part of the computation,
8476 // so we require that the input have eliminated at least one cast. If this
8477 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008478 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008479 bool DoXForm = false;
8480 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008481 switch (CI.getOpcode()) {
8482 default:
8483 // All the others use floating point so we shouldn't actually
8484 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008485 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008486 case Instruction::Trunc:
8487 DoXForm = true;
8488 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008489 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008490 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008491
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008492 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008493 // If it's unnecessary to issue an AND to clear the high bits, it's
8494 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008495 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008496 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8497 if (MaskedValueIsZero(TryRes, Mask))
8498 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008499
8500 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008501 if (TryI->use_empty())
8502 EraseInstFromFunction(*TryI);
8503 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008504 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008505 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008506 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008507 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008508 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008509 // If we do not have to emit the truncate + sext pair, then it's always
8510 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008511 //
8512 // It's not safe to eliminate the trunc + sext pair if one of the
8513 // eliminated cast is a truncate. e.g.
8514 // t2 = trunc i32 t1 to i16
8515 // t3 = sext i16 t2 to i32
8516 // !=
8517 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008518 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008519 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8520 if (NumSignBits > (DestBitSize - SrcBitSize))
8521 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008522
8523 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008524 if (TryI->use_empty())
8525 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008526 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008527 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008528 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008529 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008530
8531 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008532 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8533 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008534 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8535 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008536 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008537 // Just replace this cast with the result.
8538 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008539
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008540 assert(Res->getType() == DestTy);
8541 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008542 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008543 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008544 // Just replace this cast with the result.
8545 return ReplaceInstUsesWith(CI, Res);
8546 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008547 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008548
8549 // If the high bits are already zero, just replace this cast with the
8550 // result.
8551 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8552 if (MaskedValueIsZero(Res, Mask))
8553 return ReplaceInstUsesWith(CI, Res);
8554
8555 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008556 Constant *C = ConstantInt::get(*Context,
8557 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008558 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008559 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008560 case Instruction::SExt: {
8561 // If the high bits are already filled with sign bit, just replace this
8562 // cast with the result.
8563 unsigned NumSignBits = ComputeNumSignBits(Res);
8564 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008565 return ReplaceInstUsesWith(CI, Res);
8566
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008567 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008568 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008569 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008570 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008571 }
8572 }
8573
8574 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8575 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8576
8577 switch (SrcI->getOpcode()) {
8578 case Instruction::Add:
8579 case Instruction::Mul:
8580 case Instruction::And:
8581 case Instruction::Or:
8582 case Instruction::Xor:
8583 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008584 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8585 // Don't insert two casts unless at least one can be eliminated.
8586 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008587 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008588 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8589 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008590 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008591 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8592 }
8593 }
8594
8595 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8596 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8597 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008598 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008599 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008600 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008601 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008602 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008603 }
8604 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008605
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008606 case Instruction::Shl: {
8607 // Canonicalize trunc inside shl, if we can.
8608 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8609 if (CI && DestBitSize < SrcBitSize &&
8610 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008611 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8612 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008613 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008614 }
8615 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008616 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008617 }
8618 return 0;
8619}
8620
8621Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8622 if (Instruction *Result = commonIntCastTransforms(CI))
8623 return Result;
8624
8625 Value *Src = CI.getOperand(0);
8626 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008627 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8628 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008629
8630 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008631 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008632 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008633 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008634 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008635 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008636 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008637
Chris Lattner32177f82009-03-24 18:15:30 +00008638 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8639 ConstantInt *ShAmtV = 0;
8640 Value *ShiftOp = 0;
8641 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008642 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008643 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8644
8645 // Get a mask for the bits shifting in.
8646 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8647 if (MaskedValueIsZero(ShiftOp, Mask)) {
8648 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008649 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008650
8651 // Okay, we can shrink this. Truncate the input, then return a new
8652 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008653 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008654 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008655 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008656 }
8657 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008658
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008659 return 0;
8660}
8661
Evan Chenge3779cf2008-03-24 00:21:34 +00008662/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8663/// in order to eliminate the icmp.
8664Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8665 bool DoXform) {
8666 // If we are just checking for a icmp eq of a single bit and zext'ing it
8667 // to an integer, then shift the bit to the appropriate place and then
8668 // cast to integer to avoid the comparison.
8669 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8670 const APInt &Op1CV = Op1C->getValue();
8671
8672 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8673 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8674 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8675 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8676 if (!DoXform) return ICI;
8677
8678 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008679 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008680 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008681 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008682 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008683 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008684
8685 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008686 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008687 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008688 }
8689
8690 return ReplaceInstUsesWith(CI, In);
8691 }
8692
8693
8694
8695 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8696 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8697 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8698 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8699 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8700 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8701 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8702 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8703 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8704 // This only works for EQ and NE
8705 ICI->isEquality()) {
8706 // If Op1C some other power of two, convert:
8707 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8708 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8709 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8710 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8711
8712 APInt KnownZeroMask(~KnownZero);
8713 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8714 if (!DoXform) return ICI;
8715
8716 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8717 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8718 // (X&4) == 2 --> false
8719 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008720 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008721 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008722 return ReplaceInstUsesWith(CI, Res);
8723 }
8724
8725 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8726 Value *In = ICI->getOperand(0);
8727 if (ShiftAmt) {
8728 // Perform a logical shr by shiftamt.
8729 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008730 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8731 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008732 }
8733
8734 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008735 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008736 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008737 }
8738
8739 if (CI.getType() == In->getType())
8740 return ReplaceInstUsesWith(CI, In);
8741 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008742 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008743 }
8744 }
8745 }
8746
Nick Lewyckyef61f692009-11-23 03:17:33 +00008747 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8748 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8749 // may lead to additional simplifications.
8750 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8751 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8752 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008753 Value *LHS = ICI->getOperand(0);
8754 Value *RHS = ICI->getOperand(1);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008755
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008756 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8757 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8758 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8759 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8760 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008761
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008762 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8763 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8764 APInt UnknownBit = ~KnownBits;
8765 if (UnknownBit.countPopulation() == 1) {
Nick Lewyckyef61f692009-11-23 03:17:33 +00008766 if (!DoXform) return ICI;
8767
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008768 Value *Result = Builder->CreateXor(LHS, RHS);
8769
8770 // Mask off any bits that are set and won't be shifted away.
8771 if (KnownOneLHS.uge(UnknownBit))
8772 Result = Builder->CreateAnd(Result,
8773 ConstantInt::get(ITy, UnknownBit));
8774
8775 // Shift the bit we're testing down to the lsb.
8776 Result = Builder->CreateLShr(
8777 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8778
Nick Lewyckyef61f692009-11-23 03:17:33 +00008779 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008780 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8781 Result->takeName(ICI);
8782 return ReplaceInstUsesWith(CI, Result);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008783 }
8784 }
8785 }
8786 }
8787
Evan Chenge3779cf2008-03-24 00:21:34 +00008788 return 0;
8789}
8790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008791Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8792 // If one of the common conversion will work ..
8793 if (Instruction *Result = commonIntCastTransforms(CI))
8794 return Result;
8795
8796 Value *Src = CI.getOperand(0);
8797
Chris Lattner215d56e2009-02-17 20:47:23 +00008798 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8799 // types and if the sizes are just right we can convert this into a logical
8800 // 'and' which will be much cheaper than the pair of casts.
8801 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8802 // Get the sizes of the types involved. We know that the intermediate type
8803 // will be smaller than A or C, but don't know the relation between A and C.
8804 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008805 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8806 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8807 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008808 // If we're actually extending zero bits, then if
8809 // SrcSize < DstSize: zext(a & mask)
8810 // SrcSize == DstSize: a & mask
8811 // SrcSize > DstSize: trunc(a) & mask
8812 if (SrcSize < DstSize) {
8813 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008814 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008815 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008816 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008817 }
8818
8819 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008820 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008821 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008822 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008823 }
8824 if (SrcSize > DstSize) {
8825 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008826 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008827 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008828 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008829 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008830 }
8831 }
8832
Evan Chenge3779cf2008-03-24 00:21:34 +00008833 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8834 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008835
Evan Chenge3779cf2008-03-24 00:21:34 +00008836 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8837 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8838 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8839 // of the (zext icmp) will be transformed.
8840 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8841 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8842 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8843 (transformZExtICmp(LHS, CI, false) ||
8844 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008845 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8846 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008847 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008848 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008849 }
8850
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008851 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008852 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8853 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8854 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8855 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008856 if (TI0->getType() == CI.getType())
8857 return
8858 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008859 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008860 }
8861
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008862 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8863 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8864 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8865 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8866 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8867 And->getOperand(1) == C)
8868 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8869 Value *TI0 = TI->getOperand(0);
8870 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008871 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008872 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008873 return BinaryOperator::CreateXor(NewAnd, ZC);
8874 }
8875 }
8876
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008877 return 0;
8878}
8879
8880Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8881 if (Instruction *I = commonIntCastTransforms(CI))
8882 return I;
8883
8884 Value *Src = CI.getOperand(0);
8885
Dan Gohman35b76162008-10-30 20:40:10 +00008886 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008887 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008888 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008889 Constant::getAllOnesValue(CI.getType()),
8890 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008891
8892 // See if the value being truncated is already sign extended. If so, just
8893 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008894 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008895 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008896 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8897 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8898 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008899 unsigned NumSignBits = ComputeNumSignBits(Op);
8900
8901 if (OpBits == DestBits) {
8902 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8903 // bits, it is already ready.
8904 if (NumSignBits > DestBits-MidBits)
8905 return ReplaceInstUsesWith(CI, Op);
8906 } else if (OpBits < DestBits) {
8907 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8908 // bits, just sext from i32.
8909 if (NumSignBits > OpBits-MidBits)
8910 return new SExtInst(Op, CI.getType(), "tmp");
8911 } else {
8912 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8913 // bits, just truncate to i32.
8914 if (NumSignBits > OpBits-MidBits)
8915 return new TruncInst(Op, CI.getType(), "tmp");
8916 }
8917 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008918
8919 // If the input is a shl/ashr pair of a same constant, then this is a sign
8920 // extension from a smaller value. If we could trust arbitrary bitwidth
8921 // integers, we could turn this into a truncate to the smaller bit and then
8922 // use a sext for the whole extension. Since we don't, look deeper and check
8923 // for a truncate. If the source and dest are the same type, eliminate the
8924 // trunc and extend and just do shifts. For example, turn:
8925 // %a = trunc i32 %i to i8
8926 // %b = shl i8 %a, 6
8927 // %c = ashr i8 %b, 6
8928 // %d = sext i8 %c to i32
8929 // into:
8930 // %a = shl i32 %i, 30
8931 // %d = ashr i32 %a, 30
8932 Value *A = 0;
8933 ConstantInt *BA = 0, *CA = 0;
8934 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008935 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008936 BA == CA && isa<TruncInst>(A)) {
8937 Value *I = cast<TruncInst>(A)->getOperand(0);
8938 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008939 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8940 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008941 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008942 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008943 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008944 return BinaryOperator::CreateAShr(I, ShAmtV);
8945 }
8946 }
8947
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008948 return 0;
8949}
8950
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008951/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8952/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008953static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008954 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008955 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008956 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008957 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8958 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008959 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008960 return 0;
8961}
8962
8963/// LookThroughFPExtensions - If this is an fp extension instruction, look
8964/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008965static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008966 if (Instruction *I = dyn_cast<Instruction>(V))
8967 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008968 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008969
8970 // If this value is a constant, return the constant in the smallest FP type
8971 // that can accurately represent it. This allows us to turn
8972 // (float)((double)X+2.0) into x+2.0f.
8973 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008974 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008975 return V; // No constant folding of this.
8976 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008977 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008978 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008979 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008980 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008981 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008982 return V;
8983 // Don't try to shrink to various long double types.
8984 }
8985
8986 return V;
8987}
8988
8989Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8990 if (Instruction *I = commonCastTransforms(CI))
8991 return I;
8992
Dan Gohman7ce405e2009-06-04 22:49:04 +00008993 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008994 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008995 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008996 // many builtins (sqrt, etc).
8997 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8998 if (OpI && OpI->hasOneUse()) {
8999 switch (OpI->getOpcode()) {
9000 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009001 case Instruction::FAdd:
9002 case Instruction::FSub:
9003 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009004 case Instruction::FDiv:
9005 case Instruction::FRem:
9006 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00009007 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9008 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009009 if (LHSTrunc->getType() != SrcTy &&
9010 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00009011 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009012 // If the source types were both smaller than the destination type of
9013 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00009014 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9015 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009016 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9017 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00009018 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009019 }
9020 }
9021 break;
9022 }
9023 }
9024 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009025}
9026
9027Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9028 return commonCastTransforms(CI);
9029}
9030
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009031Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00009032 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9033 if (OpI == 0)
9034 return commonCastTransforms(FI);
9035
9036 // fptoui(uitofp(X)) --> X
9037 // fptoui(sitofp(X)) --> X
9038 // This is safe if the intermediate type has enough bits in its mantissa to
9039 // accurately represent all values of X. For example, do not do this with
9040 // i64->float->i64. This is also safe for sitofp case, because any negative
9041 // 'X' value would cause an undefined result for the fptoui.
9042 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9043 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00009044 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00009045 OpI->getType()->getFPMantissaWidth())
9046 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009047
9048 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009049}
9050
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009051Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00009052 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9053 if (OpI == 0)
9054 return commonCastTransforms(FI);
9055
9056 // fptosi(sitofp(X)) --> X
9057 // fptosi(uitofp(X)) --> X
9058 // This is safe if the intermediate type has enough bits in its mantissa to
9059 // accurately represent all values of X. For example, do not do this with
9060 // i64->float->i64. This is also safe for sitofp case, because any negative
9061 // 'X' value would cause an undefined result for the fptoui.
9062 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9063 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00009064 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00009065 OpI->getType()->getFPMantissaWidth())
9066 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009067
9068 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009069}
9070
9071Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9072 return commonCastTransforms(CI);
9073}
9074
9075Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9076 return commonCastTransforms(CI);
9077}
9078
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009079Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9080 // If the destination integer type is smaller than the intptr_t type for
9081 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9082 // trunc to be exposed to other transforms. Don't do this for extending
9083 // ptrtoint's, because we don't know if the target sign or zero extends its
9084 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00009085 if (TD &&
9086 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009087 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9088 TD->getIntPtrType(CI.getContext()),
9089 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009090 return new TruncInst(P, CI.getType());
9091 }
9092
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009093 return commonPointerCastTransforms(CI);
9094}
9095
Chris Lattner7c1626482008-01-08 07:23:51 +00009096Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009097 // If the source integer type is larger than the intptr_t type for
9098 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9099 // allows the trunc to be exposed to other transforms. Don't do this for
9100 // extending inttoptr's, because we don't know if the target sign or zero
9101 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009102 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009103 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009104 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9105 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009106 return new IntToPtrInst(P, CI.getType());
9107 }
9108
Chris Lattner7c1626482008-01-08 07:23:51 +00009109 if (Instruction *I = commonCastTransforms(CI))
9110 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00009111
Chris Lattner7c1626482008-01-08 07:23:51 +00009112 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009113}
9114
9115Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9116 // If the operands are integer typed then apply the integer transforms,
9117 // otherwise just apply the common ones.
9118 Value *Src = CI.getOperand(0);
9119 const Type *SrcTy = Src->getType();
9120 const Type *DestTy = CI.getType();
9121
Eli Friedman5013d3f2009-07-13 20:53:00 +00009122 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009123 if (Instruction *I = commonPointerCastTransforms(CI))
9124 return I;
9125 } else {
9126 if (Instruction *Result = commonCastTransforms(CI))
9127 return Result;
9128 }
9129
9130
9131 // Get rid of casts from one type to the same type. These are useless and can
9132 // be replaced by the operand.
9133 if (DestTy == Src->getType())
9134 return ReplaceInstUsesWith(CI, Src);
9135
9136 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9137 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9138 const Type *DstElTy = DstPTy->getElementType();
9139 const Type *SrcElTy = SrcPTy->getElementType();
9140
Nate Begemandf5b3612008-03-31 00:22:16 +00009141 // If the address spaces don't match, don't eliminate the bitcast, which is
9142 // required for changing types.
9143 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9144 return 0;
9145
Victor Hernandez48c3c542009-09-18 22:35:49 +00009146 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009147 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00009148 // There is no need to modify malloc calls because it is their bitcast that
9149 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00009150 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009151 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9152 return V;
9153
9154 // If the source and destination are pointers, and this cast is equivalent
9155 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9156 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00009157 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009158 unsigned NumZeros = 0;
9159 while (SrcElTy != DstElTy &&
9160 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9161 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9162 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9163 ++NumZeros;
9164 }
9165
9166 // If we found a path from the src to dest, create the getelementptr now.
9167 if (SrcElTy == DstElTy) {
9168 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00009169 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9170 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009171 }
9172 }
9173
Eli Friedman1d31dee2009-07-18 23:06:53 +00009174 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9175 if (DestVTy->getNumElements() == 1) {
9176 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009177 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009178 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00009179 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009180 }
9181 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9182 }
9183 }
9184
9185 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9186 if (SrcVTy->getNumElements() == 1) {
9187 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009188 Value *Elem =
9189 Builder->CreateExtractElement(Src,
9190 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009191 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9192 }
9193 }
9194 }
9195
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009196 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9197 if (SVI->hasOneUse()) {
9198 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9199 // a bitconvert to a vector with the same # elts.
9200 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009201 cast<VectorType>(DestTy)->getNumElements() ==
9202 SVI->getType()->getNumElements() &&
9203 SVI->getType()->getNumElements() ==
9204 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009205 CastInst *Tmp;
9206 // If either of the operands is a cast from CI.getType(), then
9207 // evaluating the shuffle in the casted destination's type will allow
9208 // us to eliminate at least one cast.
9209 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9210 Tmp->getOperand(0)->getType() == DestTy) ||
9211 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9212 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009213 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9214 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009215 // Return a new shuffle vector. Use the same element ID's, as we
9216 // know the vector types match #elts.
9217 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9218 }
9219 }
9220 }
9221 }
9222 return 0;
9223}
9224
9225/// GetSelectFoldableOperands - We want to turn code that looks like this:
9226/// %C = or %A, %B
9227/// %D = select %cond, %C, %A
9228/// into:
9229/// %C = select %cond, %B, 0
9230/// %D = or %A, %C
9231///
9232/// Assuming that the specified instruction is an operand to the select, return
9233/// a bitmask indicating which operands of this instruction are foldable if they
9234/// equal the other incoming value of the select.
9235///
9236static unsigned GetSelectFoldableOperands(Instruction *I) {
9237 switch (I->getOpcode()) {
9238 case Instruction::Add:
9239 case Instruction::Mul:
9240 case Instruction::And:
9241 case Instruction::Or:
9242 case Instruction::Xor:
9243 return 3; // Can fold through either operand.
9244 case Instruction::Sub: // Can only fold on the amount subtracted.
9245 case Instruction::Shl: // Can only fold on the shift amount.
9246 case Instruction::LShr:
9247 case Instruction::AShr:
9248 return 1;
9249 default:
9250 return 0; // Cannot fold
9251 }
9252}
9253
9254/// GetSelectFoldableConstant - For the same transformation as the previous
9255/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009256static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009257 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009258 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009259 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009260 case Instruction::Add:
9261 case Instruction::Sub:
9262 case Instruction::Or:
9263 case Instruction::Xor:
9264 case Instruction::Shl:
9265 case Instruction::LShr:
9266 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009267 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009268 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009269 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009270 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009271 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009272 }
9273}
9274
9275/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9276/// have the same opcode and only one use each. Try to simplify this.
9277Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9278 Instruction *FI) {
9279 if (TI->getNumOperands() == 1) {
9280 // If this is a non-volatile load or a cast from the same type,
9281 // merge.
9282 if (TI->isCast()) {
9283 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9284 return 0;
9285 } else {
9286 return 0; // unknown unary op.
9287 }
9288
9289 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009290 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009291 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009292 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009293 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009294 TI->getType());
9295 }
9296
9297 // Only handle binary operators here.
9298 if (!isa<BinaryOperator>(TI))
9299 return 0;
9300
9301 // Figure out if the operations have any operands in common.
9302 Value *MatchOp, *OtherOpT, *OtherOpF;
9303 bool MatchIsOpZero;
9304 if (TI->getOperand(0) == FI->getOperand(0)) {
9305 MatchOp = TI->getOperand(0);
9306 OtherOpT = TI->getOperand(1);
9307 OtherOpF = FI->getOperand(1);
9308 MatchIsOpZero = true;
9309 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9310 MatchOp = TI->getOperand(1);
9311 OtherOpT = TI->getOperand(0);
9312 OtherOpF = FI->getOperand(0);
9313 MatchIsOpZero = false;
9314 } else if (!TI->isCommutative()) {
9315 return 0;
9316 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9317 MatchOp = TI->getOperand(0);
9318 OtherOpT = TI->getOperand(1);
9319 OtherOpF = FI->getOperand(0);
9320 MatchIsOpZero = true;
9321 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9322 MatchOp = TI->getOperand(1);
9323 OtherOpT = TI->getOperand(0);
9324 OtherOpF = FI->getOperand(1);
9325 MatchIsOpZero = true;
9326 } else {
9327 return 0;
9328 }
9329
9330 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009331 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9332 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009333 InsertNewInstBefore(NewSI, SI);
9334
9335 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9336 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009337 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009338 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009339 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009340 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009341 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009342 return 0;
9343}
9344
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009345static bool isSelect01(Constant *C1, Constant *C2) {
9346 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9347 if (!C1I)
9348 return false;
9349 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9350 if (!C2I)
9351 return false;
9352 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9353}
9354
9355/// FoldSelectIntoOp - Try fold the select into one of the operands to
9356/// facilitate further optimization.
9357Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9358 Value *FalseVal) {
9359 // See the comment above GetSelectFoldableOperands for a description of the
9360 // transformation we are doing here.
9361 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9362 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9363 !isa<Constant>(FalseVal)) {
9364 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9365 unsigned OpToFold = 0;
9366 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9367 OpToFold = 1;
9368 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9369 OpToFold = 2;
9370 }
9371
9372 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009373 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009374 Value *OOp = TVI->getOperand(2-OpToFold);
9375 // Avoid creating select between 2 constants unless it's selecting
9376 // between 0 and 1.
9377 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9378 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9379 InsertNewInstBefore(NewSel, SI);
9380 NewSel->takeName(TVI);
9381 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9382 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009383 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009384 }
9385 }
9386 }
9387 }
9388 }
9389
9390 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9391 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9392 !isa<Constant>(TrueVal)) {
9393 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9394 unsigned OpToFold = 0;
9395 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9396 OpToFold = 1;
9397 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9398 OpToFold = 2;
9399 }
9400
9401 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009402 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009403 Value *OOp = FVI->getOperand(2-OpToFold);
9404 // Avoid creating select between 2 constants unless it's selecting
9405 // between 0 and 1.
9406 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9407 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9408 InsertNewInstBefore(NewSel, SI);
9409 NewSel->takeName(FVI);
9410 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9411 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009412 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009413 }
9414 }
9415 }
9416 }
9417 }
9418
9419 return 0;
9420}
9421
Dan Gohman58c09632008-09-16 18:46:06 +00009422/// visitSelectInstWithICmp - Visit a SelectInst that has an
9423/// ICmpInst as its first operand.
9424///
9425Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9426 ICmpInst *ICI) {
9427 bool Changed = false;
9428 ICmpInst::Predicate Pred = ICI->getPredicate();
9429 Value *CmpLHS = ICI->getOperand(0);
9430 Value *CmpRHS = ICI->getOperand(1);
9431 Value *TrueVal = SI.getTrueValue();
9432 Value *FalseVal = SI.getFalseValue();
9433
9434 // Check cases where the comparison is with a constant that
9435 // can be adjusted to fit the min/max idiom. We may edit ICI in
9436 // place here, so make sure the select is the only user.
9437 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009438 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009439 switch (Pred) {
9440 default: break;
9441 case ICmpInst::ICMP_ULT:
9442 case ICmpInst::ICMP_SLT: {
9443 // X < MIN ? T : F --> F
9444 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9445 return ReplaceInstUsesWith(SI, FalseVal);
9446 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009447 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009448 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9449 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9450 Pred = ICmpInst::getSwappedPredicate(Pred);
9451 CmpRHS = AdjustedRHS;
9452 std::swap(FalseVal, TrueVal);
9453 ICI->setPredicate(Pred);
9454 ICI->setOperand(1, CmpRHS);
9455 SI.setOperand(1, TrueVal);
9456 SI.setOperand(2, FalseVal);
9457 Changed = true;
9458 }
9459 break;
9460 }
9461 case ICmpInst::ICMP_UGT:
9462 case ICmpInst::ICMP_SGT: {
9463 // X > MAX ? T : F --> F
9464 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9465 return ReplaceInstUsesWith(SI, FalseVal);
9466 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009467 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009468 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9469 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9470 Pred = ICmpInst::getSwappedPredicate(Pred);
9471 CmpRHS = AdjustedRHS;
9472 std::swap(FalseVal, TrueVal);
9473 ICI->setPredicate(Pred);
9474 ICI->setOperand(1, CmpRHS);
9475 SI.setOperand(1, TrueVal);
9476 SI.setOperand(2, FalseVal);
9477 Changed = true;
9478 }
9479 break;
9480 }
9481 }
9482
Dan Gohman35b76162008-10-30 20:40:10 +00009483 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9484 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009485 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009486 if (match(TrueVal, m_ConstantInt<-1>()) &&
9487 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009488 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009489 else if (match(TrueVal, m_ConstantInt<0>()) &&
9490 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009491 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9492
Dan Gohman35b76162008-10-30 20:40:10 +00009493 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9494 // If we are just checking for a icmp eq of a single bit and zext'ing it
9495 // to an integer, then shift the bit to the appropriate place and then
9496 // cast to integer to avoid the comparison.
9497 const APInt &Op1CV = CI->getValue();
9498
9499 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9500 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9501 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009502 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009503 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009504 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009505 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009506 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009507 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009508 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009509 if (In->getType() != SI.getType())
9510 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009511 true/*SExt*/, "tmp", ICI);
9512
9513 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009514 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009515 In->getName()+".not"), *ICI);
9516
9517 return ReplaceInstUsesWith(SI, In);
9518 }
9519 }
9520 }
9521
Dan Gohman58c09632008-09-16 18:46:06 +00009522 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9523 // Transform (X == Y) ? X : Y -> Y
9524 if (Pred == ICmpInst::ICMP_EQ)
9525 return ReplaceInstUsesWith(SI, FalseVal);
9526 // Transform (X != Y) ? X : Y -> X
9527 if (Pred == ICmpInst::ICMP_NE)
9528 return ReplaceInstUsesWith(SI, TrueVal);
9529 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9530
9531 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9532 // Transform (X == Y) ? Y : X -> X
9533 if (Pred == ICmpInst::ICMP_EQ)
9534 return ReplaceInstUsesWith(SI, FalseVal);
9535 // Transform (X != Y) ? Y : X -> Y
9536 if (Pred == ICmpInst::ICMP_NE)
9537 return ReplaceInstUsesWith(SI, TrueVal);
9538 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9539 }
Dan Gohman58c09632008-09-16 18:46:06 +00009540 return Changed ? &SI : 0;
9541}
9542
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009543
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009544/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9545/// PHI node (but the two may be in different blocks). See if the true/false
9546/// values (V) are live in all of the predecessor blocks of the PHI. For
9547/// example, cases like this cannot be mapped:
9548///
9549/// X = phi [ C1, BB1], [C2, BB2]
9550/// Y = add
9551/// Z = select X, Y, 0
9552///
9553/// because Y is not live in BB1/BB2.
9554///
9555static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9556 const SelectInst &SI) {
9557 // If the value is a non-instruction value like a constant or argument, it
9558 // can always be mapped.
9559 const Instruction *I = dyn_cast<Instruction>(V);
9560 if (I == 0) return true;
9561
9562 // If V is a PHI node defined in the same block as the condition PHI, we can
9563 // map the arguments.
9564 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9565
9566 if (const PHINode *VP = dyn_cast<PHINode>(I))
9567 if (VP->getParent() == CondPHI->getParent())
9568 return true;
9569
9570 // Otherwise, if the PHI and select are defined in the same block and if V is
9571 // defined in a different block, then we can transform it.
9572 if (SI.getParent() == CondPHI->getParent() &&
9573 I->getParent() != CondPHI->getParent())
9574 return true;
9575
9576 // Otherwise we have a 'hard' case and we can't tell without doing more
9577 // detailed dominator based analysis, punt.
9578 return false;
9579}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009580
Chris Lattner78500cb2009-12-21 06:03:05 +00009581/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9582/// SPF2(SPF1(A, B), C)
9583Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9584 SelectPatternFlavor SPF1,
9585 Value *A, Value *B,
9586 Instruction &Outer,
9587 SelectPatternFlavor SPF2, Value *C) {
9588 if (C == A || C == B) {
9589 // MAX(MAX(A, B), B) -> MAX(A, B)
9590 // MIN(MIN(a, b), a) -> MIN(a, b)
9591 if (SPF1 == SPF2)
9592 return ReplaceInstUsesWith(Outer, Inner);
9593
9594 // MAX(MIN(a, b), a) -> a
9595 // MIN(MAX(a, b), a) -> a
Daniel Dunbarb61aa2b2009-12-21 23:27:57 +00009596 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9597 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9598 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9599 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattner78500cb2009-12-21 06:03:05 +00009600 return ReplaceInstUsesWith(Outer, C);
9601 }
9602
9603 // TODO: MIN(MIN(A, 23), 97)
9604 return 0;
9605}
9606
9607
9608
9609
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009610Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9611 Value *CondVal = SI.getCondition();
9612 Value *TrueVal = SI.getTrueValue();
9613 Value *FalseVal = SI.getFalseValue();
9614
9615 // select true, X, Y -> X
9616 // select false, X, Y -> Y
9617 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9618 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9619
9620 // select C, X, X -> X
9621 if (TrueVal == FalseVal)
9622 return ReplaceInstUsesWith(SI, TrueVal);
9623
9624 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9625 return ReplaceInstUsesWith(SI, FalseVal);
9626 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9627 return ReplaceInstUsesWith(SI, TrueVal);
9628 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9629 if (isa<Constant>(TrueVal))
9630 return ReplaceInstUsesWith(SI, TrueVal);
9631 else
9632 return ReplaceInstUsesWith(SI, FalseVal);
9633 }
9634
Owen Anderson35b47072009-08-13 21:58:54 +00009635 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009636 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9637 if (C->getZExtValue()) {
9638 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009639 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009640 } else {
9641 // Change: A = select B, false, C --> A = and !B, C
9642 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009643 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009644 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009645 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009646 }
9647 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9648 if (C->getZExtValue() == false) {
9649 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009650 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009651 } else {
9652 // Change: A = select B, C, true --> A = or !B, C
9653 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009654 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009655 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009656 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009657 }
9658 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009659
9660 // select a, b, a -> a&b
9661 // select a, a, b -> a|b
9662 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009663 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009664 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009665 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009666 }
9667
9668 // Selecting between two integer constants?
9669 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9670 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9671 // select C, 1, 0 -> zext C to int
9672 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009673 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009674 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9675 // select C, 0, 1 -> zext !C to int
9676 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009677 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009678 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009679 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009680 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009681
9682 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009683 // If one of the constants is zero (we know they can't both be) and we
9684 // have an icmp instruction with zero, and we have an 'and' with the
9685 // non-constant value, eliminate this whole mess. This corresponds to
9686 // cases like this: ((X & 27) ? 27 : 0)
9687 if (TrueValC->isZero() || FalseValC->isZero())
9688 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9689 cast<Constant>(IC->getOperand(1))->isNullValue())
9690 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9691 if (ICA->getOpcode() == Instruction::And &&
9692 isa<ConstantInt>(ICA->getOperand(1)) &&
9693 (ICA->getOperand(1) == TrueValC ||
9694 ICA->getOperand(1) == FalseValC) &&
9695 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9696 // Okay, now we know that everything is set up, we just don't
9697 // know whether we have a icmp_ne or icmp_eq and whether the
9698 // true or false val is the zero.
9699 bool ShouldNotVal = !TrueValC->isZero();
9700 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9701 Value *V = ICA;
9702 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009703 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009704 Instruction::Xor, V, ICA->getOperand(1)), SI);
9705 return ReplaceInstUsesWith(SI, V);
9706 }
9707 }
9708 }
9709
9710 // See if we are selecting two values based on a comparison of the two values.
9711 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9712 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9713 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009714 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9715 // This is not safe in general for floating point:
9716 // consider X== -0, Y== +0.
9717 // It becomes safe if either operand is a nonzero constant.
9718 ConstantFP *CFPt, *CFPf;
9719 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9720 !CFPt->getValueAPF().isZero()) ||
9721 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9722 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009723 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009724 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009725 // Transform (X != Y) ? X : Y -> X
9726 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9727 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009728 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009729
9730 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9731 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009732 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9733 // This is not safe in general for floating point:
9734 // consider X== -0, Y== +0.
9735 // It becomes safe if either operand is a nonzero constant.
9736 ConstantFP *CFPt, *CFPf;
9737 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9738 !CFPt->getValueAPF().isZero()) ||
9739 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9740 !CFPf->getValueAPF().isZero()))
9741 return ReplaceInstUsesWith(SI, FalseVal);
9742 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009743 // Transform (X != Y) ? Y : X -> Y
9744 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9745 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009746 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009747 }
Dan Gohman58c09632008-09-16 18:46:06 +00009748 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009749 }
9750
9751 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009752 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9753 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9754 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009755
9756 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9757 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9758 if (TI->hasOneUse() && FI->hasOneUse()) {
9759 Instruction *AddOp = 0, *SubOp = 0;
9760
9761 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9762 if (TI->getOpcode() == FI->getOpcode())
9763 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9764 return IV;
9765
9766 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9767 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009768 if ((TI->getOpcode() == Instruction::Sub &&
9769 FI->getOpcode() == Instruction::Add) ||
9770 (TI->getOpcode() == Instruction::FSub &&
9771 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009772 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009773 } else if ((FI->getOpcode() == Instruction::Sub &&
9774 TI->getOpcode() == Instruction::Add) ||
9775 (FI->getOpcode() == Instruction::FSub &&
9776 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009777 AddOp = TI; SubOp = FI;
9778 }
9779
9780 if (AddOp) {
9781 Value *OtherAddOp = 0;
9782 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9783 OtherAddOp = AddOp->getOperand(1);
9784 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9785 OtherAddOp = AddOp->getOperand(0);
9786 }
9787
9788 if (OtherAddOp) {
9789 // So at this point we know we have (Y -> OtherAddOp):
9790 // select C, (add X, Y), (sub X, Z)
9791 Value *NegVal; // Compute -Z
9792 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009793 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009794 } else {
9795 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009796 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009797 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009798 }
9799
9800 Value *NewTrueOp = OtherAddOp;
9801 Value *NewFalseOp = NegVal;
9802 if (AddOp != TI)
9803 std::swap(NewTrueOp, NewFalseOp);
9804 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009805 SelectInst::Create(CondVal, NewTrueOp,
9806 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009807
9808 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009809 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009810 }
9811 }
9812 }
9813
9814 // See if we can fold the select into one of our operands.
9815 if (SI.getType()->isInteger()) {
Chris Lattner78500cb2009-12-21 06:03:05 +00009816 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009817 return FoldI;
Chris Lattner78500cb2009-12-21 06:03:05 +00009818
9819 // MAX(MAX(a, b), a) -> MAX(a, b)
9820 // MIN(MIN(a, b), a) -> MIN(a, b)
9821 // MAX(MIN(a, b), a) -> a
9822 // MIN(MAX(a, b), a) -> a
9823 Value *LHS, *RHS, *LHS2, *RHS2;
9824 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
9825 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
9826 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
9827 SI, SPF, RHS))
9828 return R;
9829 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
9830 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
9831 SI, SPF, LHS))
9832 return R;
9833 }
9834
9835 // TODO.
9836 // ABS(-X) -> ABS(X)
9837 // ABS(ABS(X)) -> ABS(X)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009838 }
9839
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009840 // See if we can fold the select into a phi node if the condition is a select.
9841 if (isa<PHINode>(SI.getCondition()))
9842 // The true/false values have to be live in the PHI predecessor's blocks.
9843 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9844 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9845 if (Instruction *NV = FoldOpIntoPhi(SI))
9846 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00009847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009848 if (BinaryOperator::isNot(CondVal)) {
9849 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9850 SI.setOperand(1, FalseVal);
9851 SI.setOperand(2, TrueVal);
9852 return &SI;
9853 }
9854
9855 return 0;
9856}
9857
Dan Gohman2d648bb2008-04-10 18:43:06 +00009858/// EnforceKnownAlignment - If the specified pointer points to an object that
9859/// we control, modify the object's alignment to PrefAlign. This isn't
9860/// often possible though. If alignment is important, a more reliable approach
9861/// is to simply align all global variables and allocation instructions to
9862/// their preferred alignment from the beginning.
9863///
9864static unsigned EnforceKnownAlignment(Value *V,
9865 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009866
Dan Gohman2d648bb2008-04-10 18:43:06 +00009867 User *U = dyn_cast<User>(V);
9868 if (!U) return Align;
9869
Dan Gohman9545fb02009-07-17 20:47:02 +00009870 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009871 default: break;
9872 case Instruction::BitCast:
9873 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9874 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009875 // If all indexes are zero, it is just the alignment of the base pointer.
9876 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009877 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009878 if (!isa<Constant>(*i) ||
9879 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009880 AllZeroOperands = false;
9881 break;
9882 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009883
9884 if (AllZeroOperands) {
9885 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009886 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009887 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009888 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009889 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009890 }
9891
9892 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9893 // If there is a large requested alignment and we can, bump up the alignment
9894 // of the global.
9895 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009896 if (GV->getAlignment() >= PrefAlign)
9897 Align = GV->getAlignment();
9898 else {
9899 GV->setAlignment(PrefAlign);
9900 Align = PrefAlign;
9901 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009902 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009903 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9904 // If there is a requested alignment and if this is an alloca, round up.
9905 if (AI->getAlignment() >= PrefAlign)
9906 Align = AI->getAlignment();
9907 else {
9908 AI->setAlignment(PrefAlign);
9909 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009910 }
9911 }
9912
9913 return Align;
9914}
9915
9916/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9917/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9918/// and it is more than the alignment of the ultimate object, see if we can
9919/// increase the alignment of the ultimate object, making this check succeed.
9920unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9921 unsigned PrefAlign) {
9922 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9923 sizeof(PrefAlign) * CHAR_BIT;
9924 APInt Mask = APInt::getAllOnesValue(BitWidth);
9925 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9926 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9927 unsigned TrailZ = KnownZero.countTrailingOnes();
9928 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9929
9930 if (PrefAlign > Align)
9931 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9932
9933 // We don't need to make any adjustment.
9934 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009935}
9936
Chris Lattner00ae5132008-01-13 23:50:23 +00009937Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009938 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009939 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009940 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009941 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009942
9943 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009944 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009945 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009946 return MI;
9947 }
9948
9949 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9950 // load/store.
9951 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9952 if (MemOpLength == 0) return 0;
9953
Chris Lattnerc669fb62008-01-14 00:28:35 +00009954 // Source and destination pointer types are always "i8*" for intrinsic. See
9955 // if the size is something we can handle with a single primitive load/store.
9956 // A single load+store correctly handles overlapping memory in the memmove
9957 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009958 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009959 if (Size == 0) return MI; // Delete this mem transfer.
9960
9961 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009962 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009963
Chris Lattnerc669fb62008-01-14 00:28:35 +00009964 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009965 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009966 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009967
9968 // Memcpy forces the use of i8* for the source and destination. That means
9969 // that if you're using memcpy to move one double around, you'll get a cast
9970 // from double* to i8*. We'd much rather use a double load+store rather than
9971 // an i64 load+store, here because this improves the odds that the source or
9972 // dest address will be promotable. See if we can find a better type than the
9973 // integer datatype.
9974 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9975 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009976 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009977 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9978 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009979 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009980 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9981 if (STy->getNumElements() == 1)
9982 SrcETy = STy->getElementType(0);
9983 else
9984 break;
9985 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9986 if (ATy->getNumElements() == 1)
9987 SrcETy = ATy->getElementType();
9988 else
9989 break;
9990 } else
9991 break;
9992 }
9993
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009994 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009995 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009996 }
9997 }
9998
9999
Chris Lattner00ae5132008-01-13 23:50:23 +000010000 // If the memcpy/memmove provides better alignment info than we can
10001 // infer, use it.
10002 SrcAlign = std::max(SrcAlign, CopyAlign);
10003 DstAlign = std::max(DstAlign, CopyAlign);
10004
Chris Lattner78628292009-08-30 19:47:22 +000010005 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10006 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +000010007 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10008 InsertNewInstBefore(L, *MI);
10009 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10010
10011 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +000010012 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +000010013 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +000010014}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010015
Chris Lattner5af8a912008-04-30 06:39:11 +000010016Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10017 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +000010018 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000010019 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +000010020 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +000010021 return MI;
10022 }
10023
10024 // Extract the length and alignment and fill if they are constant.
10025 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10026 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +000010027 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +000010028 return 0;
10029 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +000010030 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +000010031
10032 // If the length is zero, this is a no-op
10033 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10034
10035 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10036 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +000010037 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +000010038
10039 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +000010040 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +000010041
10042 // Alignment 0 is identity for alignment 1 for memset, but not store.
10043 if (Alignment == 0) Alignment = 1;
10044
10045 // Extract the fill value and store.
10046 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +000010047 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +000010048 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +000010049
10050 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +000010051 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +000010052 return MI;
10053 }
10054
10055 return 0;
10056}
10057
10058
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010059/// visitCallInst - CallInst simplification. This mostly only handles folding
10060/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10061/// the heavy lifting.
10062///
10063Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +000010064 if (isFreeCall(&CI))
10065 return visitFree(CI);
10066
Chris Lattneraa295aa2009-05-13 17:39:14 +000010067 // If the caller function is nounwind, mark the call as nounwind, even if the
10068 // callee isn't.
10069 if (CI.getParent()->getParent()->doesNotThrow() &&
10070 !CI.doesNotThrow()) {
10071 CI.setDoesNotThrow();
10072 return &CI;
10073 }
10074
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010075 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10076 if (!II) return visitCallSite(&CI);
10077
10078 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10079 // visitCallSite.
10080 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
10081 bool Changed = false;
10082
10083 // memmove/cpy/set of zero bytes is a noop.
10084 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10085 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10086
10087 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
10088 if (CI->getZExtValue() == 1) {
10089 // Replace the instruction with just byte operations. We would
10090 // transform other cases to loads/stores, but we don't know if
10091 // alignment is sufficient.
10092 }
10093 }
10094
10095 // If we have a memmove and the source operation is a constant global,
10096 // then the source and dest pointers can't alias, so we can change this
10097 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +000010098 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010099 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10100 if (GVSrc->isConstant()) {
10101 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +000010102 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10103 const Type *Tys[1];
10104 Tys[0] = CI.getOperand(3)->getType();
10105 CI.setOperand(0,
10106 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010107 Changed = true;
10108 }
Eli Friedman626e32a2009-12-17 21:07:31 +000010109 }
Chris Lattner59b27d92008-05-28 05:30:41 +000010110
Eli Friedman626e32a2009-12-17 21:07:31 +000010111 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +000010112 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +000010113 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +000010114 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010115 }
10116
10117 // If we can determine a pointer alignment that is bigger than currently
10118 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +000010119 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +000010120 if (Instruction *I = SimplifyMemTransfer(MI))
10121 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +000010122 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10123 if (Instruction *I = SimplifyMemSet(MSI))
10124 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010125 }
10126
10127 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +000010128 }
10129
10130 switch (II->getIntrinsicID()) {
10131 default: break;
10132 case Intrinsic::bswap:
10133 // bswap(bswap(x)) -> x
10134 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10135 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10136 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattner723b9642010-01-01 18:34:40 +000010137
10138 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10139 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10140 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10141 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10142 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10143 TI->getType()->getPrimitiveSizeInBits();
10144 Value *CV = ConstantInt::get(Operand->getType(), C);
10145 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10146 return new TruncInst(V, TI->getType());
10147 }
10148 }
10149
Chris Lattner989ba312008-06-18 04:33:20 +000010150 break;
Chris Lattnerfd4f21a2010-01-01 01:52:15 +000010151 case Intrinsic::powi:
10152 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10153 // powi(x, 0) -> 1.0
10154 if (Power->isZero())
10155 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10156 // powi(x, 1) -> x
10157 if (Power->isOne())
10158 return ReplaceInstUsesWith(CI, II->getOperand(1));
10159 // powi(x, -1) -> 1/x
Chris Lattner60179fb2010-01-01 01:54:08 +000010160 if (Power->isAllOnesValue())
10161 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10162 II->getOperand(1));
Chris Lattnerfd4f21a2010-01-01 01:52:15 +000010163 }
10164 break;
10165
Chris Lattner0b452262009-11-26 21:42:47 +000010166 case Intrinsic::uadd_with_overflow: {
10167 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10168 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10169 uint32_t BitWidth = IT->getBitWidth();
10170 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +000010171 APInt LHSKnownZero(BitWidth, 0);
10172 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010173 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10174 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10175 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10176
10177 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +000010178 APInt RHSKnownZero(BitWidth, 0);
10179 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010180 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10181 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10182 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10183 if (LHSKnownNegative && RHSKnownNegative) {
10184 // The sign bit is set in both cases: this MUST overflow.
10185 // Create a simple add instruction, and insert it into the struct.
10186 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10187 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010188 Constant *V[] = {
10189 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10190 };
Chris Lattner0b452262009-11-26 21:42:47 +000010191 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10192 return InsertValueInst::Create(Struct, Add, 0);
10193 }
10194
10195 if (LHSKnownPositive && RHSKnownPositive) {
10196 // The sign bit is clear in both cases: this CANNOT overflow.
10197 // Create a simple add instruction, and insert it into the struct.
10198 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10199 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010200 Constant *V[] = {
10201 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10202 };
Chris Lattner0b452262009-11-26 21:42:47 +000010203 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10204 return InsertValueInst::Create(Struct, Add, 0);
10205 }
10206 }
10207 }
10208 // FALL THROUGH uadd into sadd
10209 case Intrinsic::sadd_with_overflow:
10210 // Canonicalize constants into the RHS.
10211 if (isa<Constant>(II->getOperand(1)) &&
10212 !isa<Constant>(II->getOperand(2))) {
10213 Value *LHS = II->getOperand(1);
10214 II->setOperand(1, II->getOperand(2));
10215 II->setOperand(2, LHS);
10216 return II;
10217 }
10218
10219 // X + undef -> undef
10220 if (isa<UndefValue>(II->getOperand(2)))
10221 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10222
10223 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10224 // X + 0 -> {X, false}
10225 if (RHS->isZero()) {
10226 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010227 UndefValue::get(II->getOperand(0)->getType()),
10228 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010229 };
10230 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10231 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10232 }
10233 }
10234 break;
10235 case Intrinsic::usub_with_overflow:
10236 case Intrinsic::ssub_with_overflow:
10237 // undef - X -> undef
10238 // X - undef -> undef
10239 if (isa<UndefValue>(II->getOperand(1)) ||
10240 isa<UndefValue>(II->getOperand(2)))
10241 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10242
10243 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10244 // X - 0 -> {X, false}
10245 if (RHS->isZero()) {
10246 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010247 UndefValue::get(II->getOperand(1)->getType()),
10248 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010249 };
10250 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10251 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10252 }
10253 }
10254 break;
10255 case Intrinsic::umul_with_overflow:
10256 case Intrinsic::smul_with_overflow:
10257 // Canonicalize constants into the RHS.
10258 if (isa<Constant>(II->getOperand(1)) &&
10259 !isa<Constant>(II->getOperand(2))) {
10260 Value *LHS = II->getOperand(1);
10261 II->setOperand(1, II->getOperand(2));
10262 II->setOperand(2, LHS);
10263 return II;
10264 }
10265
10266 // X * undef -> undef
10267 if (isa<UndefValue>(II->getOperand(2)))
10268 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10269
10270 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10271 // X*0 -> {0, false}
10272 if (RHSI->isZero())
10273 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10274
10275 // X * 1 -> {X, false}
10276 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010277 Constant *V[] = {
10278 UndefValue::get(II->getOperand(1)->getType()),
10279 ConstantInt::getFalse(*Context)
10280 };
Chris Lattner0b452262009-11-26 21:42:47 +000010281 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010282 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010283 }
10284 }
10285 break;
Chris Lattner989ba312008-06-18 04:33:20 +000010286 case Intrinsic::ppc_altivec_lvx:
10287 case Intrinsic::ppc_altivec_lvxl:
10288 case Intrinsic::x86_sse_loadu_ps:
10289 case Intrinsic::x86_sse2_loadu_pd:
10290 case Intrinsic::x86_sse2_loadu_dq:
10291 // Turn PPC lvx -> load if the pointer is known aligned.
10292 // Turn X86 loadups -> load if the pointer is known aligned.
10293 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +000010294 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10295 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +000010296 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010297 }
Chris Lattner989ba312008-06-18 04:33:20 +000010298 break;
10299 case Intrinsic::ppc_altivec_stvx:
10300 case Intrinsic::ppc_altivec_stvxl:
10301 // Turn stvx -> store if the pointer is known aligned.
10302 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10303 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010304 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010305 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010306 return new StoreInst(II->getOperand(1), Ptr);
10307 }
10308 break;
10309 case Intrinsic::x86_sse_storeu_ps:
10310 case Intrinsic::x86_sse2_storeu_pd:
10311 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +000010312 // Turn X86 storeu -> store if the pointer is known aligned.
10313 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10314 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010315 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010316 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010317 return new StoreInst(II->getOperand(2), Ptr);
10318 }
10319 break;
10320
10321 case Intrinsic::x86_sse_cvttss2si: {
10322 // These intrinsics only demands the 0th element of its input vector. If
10323 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +000010324 unsigned VWidth =
10325 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10326 APInt DemandedElts(VWidth, 1);
10327 APInt UndefElts(VWidth, 0);
10328 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +000010329 UndefElts)) {
10330 II->setOperand(1, V);
10331 return II;
10332 }
10333 break;
10334 }
10335
10336 case Intrinsic::ppc_altivec_vperm:
10337 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10338 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10339 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010340
Chris Lattner989ba312008-06-18 04:33:20 +000010341 // Check that all of the elements are integer constants or undefs.
10342 bool AllEltsOk = true;
10343 for (unsigned i = 0; i != 16; ++i) {
10344 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10345 !isa<UndefValue>(Mask->getOperand(i))) {
10346 AllEltsOk = false;
10347 break;
10348 }
10349 }
10350
10351 if (AllEltsOk) {
10352 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +000010353 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10354 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +000010355 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010356
Chris Lattner989ba312008-06-18 04:33:20 +000010357 // Only extract each element once.
10358 Value *ExtractedElts[32];
10359 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10360
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010361 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +000010362 if (isa<UndefValue>(Mask->getOperand(i)))
10363 continue;
10364 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10365 Idx &= 31; // Match the hardware behavior.
10366
10367 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010368 ExtractedElts[Idx] =
10369 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10370 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10371 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010372 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010373
Chris Lattner989ba312008-06-18 04:33:20 +000010374 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +000010375 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10376 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10377 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010378 }
Chris Lattner989ba312008-06-18 04:33:20 +000010379 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010380 }
Chris Lattner989ba312008-06-18 04:33:20 +000010381 }
10382 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010383
Chris Lattner989ba312008-06-18 04:33:20 +000010384 case Intrinsic::stackrestore: {
10385 // If the save is right next to the restore, remove the restore. This can
10386 // happen when variable allocas are DCE'd.
10387 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10388 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10389 BasicBlock::iterator BI = SS;
10390 if (&*++BI == II)
10391 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010392 }
Chris Lattner989ba312008-06-18 04:33:20 +000010393 }
10394
10395 // Scan down this block to see if there is another stack restore in the
10396 // same block without an intervening call/alloca.
10397 BasicBlock::iterator BI = II;
10398 TerminatorInst *TI = II->getParent()->getTerminator();
10399 bool CannotRemove = false;
10400 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000010401 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +000010402 CannotRemove = true;
10403 break;
10404 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010405 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10406 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10407 // If there is a stackrestore below this one, remove this one.
10408 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10409 return EraseInstFromFunction(CI);
10410 // Otherwise, ignore the intrinsic.
10411 } else {
10412 // If we found a non-intrinsic call, we can't remove the stack
10413 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010414 CannotRemove = true;
10415 break;
10416 }
Chris Lattner989ba312008-06-18 04:33:20 +000010417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010418 }
Chris Lattner989ba312008-06-18 04:33:20 +000010419
10420 // If the stack restore is in a return/unwind block and if there are no
10421 // allocas or calls between the restore and the return, nuke the restore.
10422 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10423 return EraseInstFromFunction(CI);
10424 break;
10425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010426 }
10427
10428 return visitCallSite(II);
10429}
10430
10431// InvokeInst simplification
10432//
10433Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10434 return visitCallSite(&II);
10435}
10436
Dale Johannesen96021832008-04-25 21:16:07 +000010437/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10438/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010439static bool isSafeToEliminateVarargsCast(const CallSite CS,
10440 const CastInst * const CI,
10441 const TargetData * const TD,
10442 const int ix) {
10443 if (!CI->isLosslessCast())
10444 return false;
10445
10446 // The size of ByVal arguments is derived from the type, so we
10447 // can't change to a type with a different size. If the size were
10448 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010449 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010450 return true;
10451
10452 const Type* SrcTy =
10453 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10454 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10455 if (!SrcTy->isSized() || !DstTy->isSized())
10456 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010457 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010458 return false;
10459 return true;
10460}
10461
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010462// visitCallSite - Improvements for call and invoke instructions.
10463//
10464Instruction *InstCombiner::visitCallSite(CallSite CS) {
10465 bool Changed = false;
10466
10467 // If the callee is a constexpr cast of a function, attempt to move the cast
10468 // to the arguments of the call/invoke.
10469 if (transformConstExprCastCall(CS)) return 0;
10470
10471 Value *Callee = CS.getCalledValue();
10472
10473 if (Function *CalleeF = dyn_cast<Function>(Callee))
10474 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10475 Instruction *OldCall = CS.getInstruction();
10476 // If the call and callee calling conventions don't match, this call must
10477 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010478 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010479 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010480 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010481 // If OldCall dues not return void then replaceAllUsesWith undef.
10482 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010483 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010484 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010485 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10486 return EraseInstFromFunction(*OldCall);
10487 return 0;
10488 }
10489
10490 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10491 // This instruction is not reachable, just remove it. We insert a store to
10492 // undef so that we know that this code is not reachable, despite the fact
10493 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010494 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010495 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010496 CS.getInstruction());
10497
Devang Patele3829c82009-10-13 22:56:32 +000010498 // If CS dues not return void then replaceAllUsesWith undef.
10499 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010500 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010501 CS.getInstruction()->
10502 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010503
10504 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10505 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010506 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010507 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010508 }
10509 return EraseInstFromFunction(*CS.getInstruction());
10510 }
10511
Duncan Sands74833f22007-09-17 10:26:40 +000010512 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10513 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10514 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10515 return transformCallThroughTrampoline(CS);
10516
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010517 const PointerType *PTy = cast<PointerType>(Callee->getType());
10518 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10519 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010520 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010521 // See if we can optimize any arguments passed through the varargs area of
10522 // the call.
10523 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010524 E = CS.arg_end(); I != E; ++I, ++ix) {
10525 CastInst *CI = dyn_cast<CastInst>(*I);
10526 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10527 *I = CI->getOperand(0);
10528 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010529 }
Dale Johannesen35615462008-04-23 18:34:37 +000010530 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010531 }
10532
Duncan Sands2937e352007-12-19 21:13:37 +000010533 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010534 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010535 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010536 Changed = true;
10537 }
10538
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010539 return Changed ? CS.getInstruction() : 0;
10540}
10541
10542// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10543// attempt to move the cast to the arguments of the call/invoke.
10544//
10545bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10546 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10547 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10548 if (CE->getOpcode() != Instruction::BitCast ||
10549 !isa<Function>(CE->getOperand(0)))
10550 return false;
10551 Function *Callee = cast<Function>(CE->getOperand(0));
10552 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010553 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010554
10555 // Okay, this is a cast from a function to a different type. Unless doing so
10556 // would cause a type conversion of one of our arguments, change this call to
10557 // be a direct call with arguments casted to the appropriate types.
10558 //
10559 const FunctionType *FT = Callee->getFunctionType();
10560 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010561 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010562
Duncan Sands7901ce12008-06-01 07:38:42 +000010563 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010564 return false; // TODO: Handle multiple return values.
10565
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010566 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010567 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010568 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010569 // Conversion is ok if changing from one pointer type to another or from
10570 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010571 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010572 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010573 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010574 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010575 return false; // Cannot transform this return value.
10576
Duncan Sands5c489582008-01-06 10:12:28 +000010577 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010578 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010579 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010580 return false; // Cannot transform this return value.
10581
Chris Lattner1c8733e2008-03-12 17:45:29 +000010582 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010583 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010584 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010585 return false; // Attribute not compatible with transformed value.
10586 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010587
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010588 // If the callsite is an invoke instruction, and the return value is used by
10589 // a PHI node in a successor, we cannot change the return type of the call
10590 // because there is no place to put the cast instruction (without breaking
10591 // the critical edge). Bail out in this case.
10592 if (!Caller->use_empty())
10593 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10594 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10595 UI != E; ++UI)
10596 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10597 if (PN->getParent() == II->getNormalDest() ||
10598 PN->getParent() == II->getUnwindDest())
10599 return false;
10600 }
10601
10602 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10603 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10604
10605 CallSite::arg_iterator AI = CS.arg_begin();
10606 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10607 const Type *ParamTy = FT->getParamType(i);
10608 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010609
10610 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010611 return false; // Cannot transform this parameter value.
10612
Devang Patelf2a4a922008-09-26 22:53:05 +000010613 if (CallerPAL.getParamAttributes(i + 1)
10614 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010615 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010616
Duncan Sands7901ce12008-06-01 07:38:42 +000010617 // Converting from one pointer type to another or between a pointer and an
10618 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010619 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010620 (TD && ((isa<PointerType>(ParamTy) ||
10621 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10622 (isa<PointerType>(ActTy) ||
10623 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010624 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010625 }
10626
10627 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10628 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010629 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010630
Chris Lattner1c8733e2008-03-12 17:45:29 +000010631 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10632 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010633 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010634 // won't be dropping them. Check that these extra arguments have attributes
10635 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010636 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10637 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010638 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010639 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010640 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010641 return false;
10642 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010643
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010644 // Okay, we decided that this is a safe thing to do: go ahead and start
10645 // inserting cast instructions as necessary...
10646 std::vector<Value*> Args;
10647 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010648 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010649 attrVec.reserve(NumCommonArgs);
10650
10651 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010652 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010653
10654 // If the return value is not being used, the type may not be compatible
10655 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010656 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010657
10658 // Add the new return attributes.
10659 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010660 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010661
10662 AI = CS.arg_begin();
10663 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10664 const Type *ParamTy = FT->getParamType(i);
10665 if ((*AI)->getType() == ParamTy) {
10666 Args.push_back(*AI);
10667 } else {
10668 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10669 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010670 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010671 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010672
10673 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010674 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010675 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010676 }
10677
10678 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010679 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010680 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010681 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010682
Chris Lattnerad7516a2009-08-30 18:50:58 +000010683 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010684 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010685 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010686 errs() << "WARNING: While resolving call to function '"
10687 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010688 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010689 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010690 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10691 const Type *PTy = getPromotedType((*AI)->getType());
10692 if (PTy != (*AI)->getType()) {
10693 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010694 Instruction::CastOps opcode =
10695 CastInst::getCastOpcode(*AI, false, PTy, false);
10696 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010697 } else {
10698 Args.push_back(*AI);
10699 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010700
Duncan Sands4ced1f82008-01-13 08:02:44 +000010701 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010702 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010703 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010704 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010705 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010707
Devang Patelf2a4a922008-09-26 22:53:05 +000010708 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10709 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10710
Devang Patele9d08b82009-10-14 17:29:00 +000010711 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010712 Caller->setName(""); // Void type should not have a name.
10713
Eric Christopher3e7381f2009-07-25 02:45:27 +000010714 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10715 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010716
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010717 Instruction *NC;
10718 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010719 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010720 Args.begin(), Args.end(),
10721 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010722 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010723 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010724 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010725 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10726 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010727 CallInst *CI = cast<CallInst>(Caller);
10728 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010729 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010730 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010731 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010732 }
10733
10734 // Insert a cast of the return type as necessary.
10735 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010736 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010737 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010738 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010739 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010740 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010741
10742 // If this is an invoke instruction, we should insert it after the first
10743 // non-phi, instruction in the normal successor block.
10744 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010745 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010746 InsertNewInstBefore(NC, *I);
10747 } else {
10748 // Otherwise, it's a call, just insert cast right after the call instr
10749 InsertNewInstBefore(NC, *Caller);
10750 }
Chris Lattner4796b622009-08-30 06:22:51 +000010751 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010752 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010753 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010754 }
10755 }
10756
Devang Pateledad36f2009-10-13 21:41:20 +000010757
Chris Lattner26b7f942009-08-31 05:17:58 +000010758 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010759 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010760
10761 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010762 return true;
10763}
10764
Duncan Sands74833f22007-09-17 10:26:40 +000010765// transformCallThroughTrampoline - Turn a call to a function created by the
10766// init_trampoline intrinsic into a direct call to the underlying function.
10767//
10768Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10769 Value *Callee = CS.getCalledValue();
10770 const PointerType *PTy = cast<PointerType>(Callee->getType());
10771 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010772 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010773
10774 // If the call already has the 'nest' attribute somewhere then give up -
10775 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010776 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010777 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010778
10779 IntrinsicInst *Tramp =
10780 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10781
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010782 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010783 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10784 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10785
Devang Pateld222f862008-09-25 21:00:45 +000010786 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010787 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010788 unsigned NestIdx = 1;
10789 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010790 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010791
10792 // Look for a parameter marked with the 'nest' attribute.
10793 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10794 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010795 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010796 // Record the parameter type and any other attributes.
10797 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010798 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010799 break;
10800 }
10801
10802 if (NestTy) {
10803 Instruction *Caller = CS.getInstruction();
10804 std::vector<Value*> NewArgs;
10805 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10806
Devang Pateld222f862008-09-25 21:00:45 +000010807 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010808 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010809
Duncan Sands74833f22007-09-17 10:26:40 +000010810 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010811 // mean appending it. Likewise for attributes.
10812
Devang Patelf2a4a922008-09-26 22:53:05 +000010813 // Add any result attributes.
10814 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010815 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010816
Duncan Sands74833f22007-09-17 10:26:40 +000010817 {
10818 unsigned Idx = 1;
10819 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10820 do {
10821 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010822 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010823 Value *NestVal = Tramp->getOperand(3);
10824 if (NestVal->getType() != NestTy)
10825 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10826 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010827 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010828 }
10829
10830 if (I == E)
10831 break;
10832
Duncan Sands48b81112008-01-14 19:52:09 +000010833 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010834 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010835 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010836 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010837 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010838
10839 ++Idx, ++I;
10840 } while (1);
10841 }
10842
Devang Patelf2a4a922008-09-26 22:53:05 +000010843 // Add any function attributes.
10844 if (Attributes Attr = Attrs.getFnAttributes())
10845 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10846
Duncan Sands74833f22007-09-17 10:26:40 +000010847 // The trampoline may have been bitcast to a bogus type (FTy).
10848 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010849 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010850
Duncan Sands74833f22007-09-17 10:26:40 +000010851 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010852 NewTypes.reserve(FTy->getNumParams()+1);
10853
Duncan Sands74833f22007-09-17 10:26:40 +000010854 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010855 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010856 {
10857 unsigned Idx = 1;
10858 FunctionType::param_iterator I = FTy->param_begin(),
10859 E = FTy->param_end();
10860
10861 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010862 if (Idx == NestIdx)
10863 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010864 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010865
10866 if (I == E)
10867 break;
10868
Duncan Sands48b81112008-01-14 19:52:09 +000010869 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010870 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010871
10872 ++Idx, ++I;
10873 } while (1);
10874 }
10875
10876 // Replace the trampoline call with a direct call. Let the generic
10877 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010878 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010879 FTy->isVarArg());
10880 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010881 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010882 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010883 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010884 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10885 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010886
10887 Instruction *NewCaller;
10888 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010889 NewCaller = InvokeInst::Create(NewCallee,
10890 II->getNormalDest(), II->getUnwindDest(),
10891 NewArgs.begin(), NewArgs.end(),
10892 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010893 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010894 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010895 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010896 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10897 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010898 if (cast<CallInst>(Caller)->isTailCall())
10899 cast<CallInst>(NewCaller)->setTailCall();
10900 cast<CallInst>(NewCaller)->
10901 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010902 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010903 }
Devang Patele9d08b82009-10-14 17:29:00 +000010904 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010905 Caller->replaceAllUsesWith(NewCaller);
10906 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010907 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010908 return 0;
10909 }
10910 }
10911
10912 // Replace the trampoline call with a direct call. Since there is no 'nest'
10913 // parameter, there is no need to adjust the argument list. Let the generic
10914 // code sort out any function type mismatches.
10915 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010916 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010917 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010918 CS.setCalledFunction(NewCallee);
10919 return CS.getInstruction();
10920}
10921
Dan Gohman09cf2b62009-09-16 16:50:24 +000010922/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10923/// 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 +000010924/// and a single binop.
10925Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10926 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010927 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010928 unsigned Opc = FirstInst->getOpcode();
10929 Value *LHSVal = FirstInst->getOperand(0);
10930 Value *RHSVal = FirstInst->getOperand(1);
10931
10932 const Type *LHSType = LHSVal->getType();
10933 const Type *RHSType = RHSVal->getType();
10934
Dan Gohman09cf2b62009-09-16 16:50:24 +000010935 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010936 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010937 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10938 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10939 // Verify type of the LHS matches so we don't fold cmp's of different
10940 // types or GEP's with different index types.
10941 I->getOperand(0)->getType() != LHSType ||
10942 I->getOperand(1)->getType() != RHSType)
10943 return 0;
10944
10945 // If they are CmpInst instructions, check their predicates
10946 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10947 if (cast<CmpInst>(I)->getPredicate() !=
10948 cast<CmpInst>(FirstInst)->getPredicate())
10949 return 0;
10950
10951 // Keep track of which operand needs a phi node.
10952 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10953 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10954 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010955
10956 // If both LHS and RHS would need a PHI, don't do this transformation,
10957 // because it would increase the number of PHIs entering the block,
10958 // which leads to higher register pressure. This is especially
10959 // bad when the PHIs are in the header of a loop.
10960 if (!LHSVal && !RHSVal)
10961 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010962
Chris Lattner30078012008-12-01 03:42:51 +000010963 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010964
10965 Value *InLHS = FirstInst->getOperand(0);
10966 Value *InRHS = FirstInst->getOperand(1);
10967 PHINode *NewLHS = 0, *NewRHS = 0;
10968 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010969 NewLHS = PHINode::Create(LHSType,
10970 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010971 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10972 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10973 InsertNewInstBefore(NewLHS, PN);
10974 LHSVal = NewLHS;
10975 }
10976
10977 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010978 NewRHS = PHINode::Create(RHSType,
10979 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010980 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10981 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10982 InsertNewInstBefore(NewRHS, PN);
10983 RHSVal = NewRHS;
10984 }
10985
10986 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010987 if (NewLHS || NewRHS) {
10988 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10989 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10990 if (NewLHS) {
10991 Value *NewInLHS = InInst->getOperand(0);
10992 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10993 }
10994 if (NewRHS) {
10995 Value *NewInRHS = InInst->getOperand(1);
10996 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10997 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010998 }
10999 }
11000
11001 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011002 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000011003 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000011004 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000011005 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011006}
11007
Chris Lattner9e1916e2008-12-01 02:34:36 +000011008Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11009 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11010
11011 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11012 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000011013 // This is true if all GEP bases are allocas and if all indices into them are
11014 // constants.
11015 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000011016
11017 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000011018 // more than one phi, which leads to higher register pressure. This is
11019 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000011020 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000011021
Dan Gohman09cf2b62009-09-16 16:50:24 +000011022 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000011023 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11024 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11025 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11026 GEP->getNumOperands() != FirstInst->getNumOperands())
11027 return 0;
11028
Chris Lattneradf354b2009-02-21 00:46:50 +000011029 // Keep track of whether or not all GEPs are of alloca pointers.
11030 if (AllBasePointersAreAllocas &&
11031 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11032 !GEP->hasAllConstantIndices()))
11033 AllBasePointersAreAllocas = false;
11034
Chris Lattner9e1916e2008-12-01 02:34:36 +000011035 // Compare the operand lists.
11036 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11037 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11038 continue;
11039
11040 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11041 // if one of the PHIs has a constant for the index. The index may be
11042 // substantially cheaper to compute for the constants, so making it a
11043 // variable index could pessimize the path. This also handles the case
11044 // for struct indices, which must always be constant.
11045 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11046 isa<ConstantInt>(GEP->getOperand(op)))
11047 return 0;
11048
11049 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11050 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000011051
11052 // If we already needed a PHI for an earlier operand, and another operand
11053 // also requires a PHI, we'd be introducing more PHIs than we're
11054 // eliminating, which increases register pressure on entry to the PHI's
11055 // block.
11056 if (NeededPhi)
11057 return 0;
11058
Chris Lattner9e1916e2008-12-01 02:34:36 +000011059 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000011060 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000011061 }
11062 }
11063
Chris Lattneradf354b2009-02-21 00:46:50 +000011064 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000011065 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000011066 // offset calculation, but all the predecessors will have to materialize the
11067 // stack address into a register anyway. We'd actually rather *clone* the
11068 // load up into the predecessors so that we have a load of a gep of an alloca,
11069 // which can usually all be folded into the load.
11070 if (AllBasePointersAreAllocas)
11071 return 0;
11072
Chris Lattner9e1916e2008-12-01 02:34:36 +000011073 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11074 // that is variable.
11075 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11076
11077 bool HasAnyPHIs = false;
11078 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11079 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11080 Value *FirstOp = FirstInst->getOperand(i);
11081 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11082 FirstOp->getName()+".pn");
11083 InsertNewInstBefore(NewPN, PN);
11084
11085 NewPN->reserveOperandSpace(e);
11086 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11087 OperandPhis[i] = NewPN;
11088 FixedOperands[i] = NewPN;
11089 HasAnyPHIs = true;
11090 }
11091
11092
11093 // Add all operands to the new PHIs.
11094 if (HasAnyPHIs) {
11095 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11096 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11097 BasicBlock *InBB = PN.getIncomingBlock(i);
11098
11099 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11100 if (PHINode *OpPhi = OperandPhis[op])
11101 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11102 }
11103 }
11104
11105 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011106 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11107 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11108 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011109 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11110 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000011111}
11112
11113
Chris Lattnerf1e30c82009-02-23 05:56:17 +000011114/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11115/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000011116/// obvious the value of the load is not changed from the point of the load to
11117/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011118///
11119/// Finally, it is safe, but not profitable, to sink a load targetting a
11120/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11121/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000011122static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011123 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11124
11125 for (++BBI; BBI != E; ++BBI)
11126 if (BBI->mayWriteToMemory())
11127 return false;
11128
11129 // Check for non-address taken alloca. If not address-taken already, it isn't
11130 // profitable to do this xform.
11131 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11132 bool isAddressTaken = false;
11133 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11134 UI != E; ++UI) {
11135 if (isa<LoadInst>(UI)) continue;
11136 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11137 // If storing TO the alloca, then the address isn't taken.
11138 if (SI->getOperand(1) == AI) continue;
11139 }
11140 isAddressTaken = true;
11141 break;
11142 }
11143
Chris Lattneradf354b2009-02-21 00:46:50 +000011144 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011145 return false;
11146 }
11147
Chris Lattneradf354b2009-02-21 00:46:50 +000011148 // If this load is a load from a GEP with a constant offset from an alloca,
11149 // then we don't want to sink it. In its present form, it will be
11150 // load [constant stack offset]. Sinking it will cause us to have to
11151 // materialize the stack addresses in each predecessor in a register only to
11152 // do a shared load from register in the successor.
11153 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11154 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11155 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11156 return false;
11157
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011158 return true;
11159}
11160
Chris Lattner38751f82009-11-01 20:04:24 +000011161Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11162 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11163
11164 // When processing loads, we need to propagate two bits of information to the
11165 // sunk load: whether it is volatile, and what its alignment is. We currently
11166 // don't sink loads when some have their alignment specified and some don't.
11167 // visitLoadInst will propagate an alignment onto the load when TD is around,
11168 // and if TD isn't around, we can't handle the mixed case.
11169 bool isVolatile = FirstLI->isVolatile();
11170 unsigned LoadAlignment = FirstLI->getAlignment();
11171
11172 // We can't sink the load if the loaded value could be modified between the
11173 // load and the PHI.
11174 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11175 !isSafeAndProfitableToSinkLoad(FirstLI))
11176 return 0;
11177
11178 // If the PHI is of volatile loads and the load block has multiple
11179 // successors, sinking it would remove a load of the volatile value from
11180 // the path through the other successor.
11181 if (isVolatile &&
11182 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11183 return 0;
11184
11185 // Check to see if all arguments are the same operation.
11186 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11187 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11188 if (!LI || !LI->hasOneUse())
11189 return 0;
11190
11191 // We can't sink the load if the loaded value could be modified between
11192 // the load and the PHI.
11193 if (LI->isVolatile() != isVolatile ||
11194 LI->getParent() != PN.getIncomingBlock(i) ||
11195 !isSafeAndProfitableToSinkLoad(LI))
11196 return 0;
11197
11198 // If some of the loads have an alignment specified but not all of them,
11199 // we can't do the transformation.
11200 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11201 return 0;
11202
Chris Lattner52fe1bc2009-11-01 20:07:07 +000011203 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +000011204
11205 // If the PHI is of volatile loads and the load block has multiple
11206 // successors, sinking it would remove a load of the volatile value from
11207 // the path through the other successor.
11208 if (isVolatile &&
11209 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11210 return 0;
11211 }
11212
11213 // Okay, they are all the same operation. Create a new PHI node of the
11214 // correct type, and PHI together all of the LHS's of the instructions.
11215 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11216 PN.getName()+".in");
11217 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11218
11219 Value *InVal = FirstLI->getOperand(0);
11220 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11221
11222 // Add all operands to the new PHI.
11223 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11224 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11225 if (NewInVal != InVal)
11226 InVal = 0;
11227 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11228 }
11229
11230 Value *PhiVal;
11231 if (InVal) {
11232 // The new PHI unions all of the same values together. This is really
11233 // common, so we handle it intelligently here for compile-time speed.
11234 PhiVal = InVal;
11235 delete NewPN;
11236 } else {
11237 InsertNewInstBefore(NewPN, PN);
11238 PhiVal = NewPN;
11239 }
11240
11241 // If this was a volatile load that we are merging, make sure to loop through
11242 // and mark all the input loads as non-volatile. If we don't do this, we will
11243 // insert a new volatile load and the old ones will not be deletable.
11244 if (isVolatile)
11245 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11246 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11247
11248 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11249}
11250
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011251
Chris Lattnerd0011092009-11-10 07:23:37 +000011252
11253/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11254/// operator and they all are only used by the PHI, PHI together their
11255/// inputs, and do the operation once, to the result of the PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011256Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11257 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11258
Chris Lattner38751f82009-11-01 20:04:24 +000011259 if (isa<GetElementPtrInst>(FirstInst))
11260 return FoldPHIArgGEPIntoPHI(PN);
11261 if (isa<LoadInst>(FirstInst))
11262 return FoldPHIArgLoadIntoPHI(PN);
11263
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011264 // Scan the instruction, looking for input operations that can be folded away.
11265 // If all input operands to the phi are the same instruction (e.g. a cast from
11266 // the same type or "+42") we can pull the operation through the PHI, reducing
11267 // code size and simplifying code.
11268 Constant *ConstantOp = 0;
11269 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +000011270
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 if (isa<CastInst>(FirstInst)) {
11272 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +000011273
11274 // Be careful about transforming integer PHIs. We don't want to pessimize
11275 // the code by turning an i32 into an i1293.
11276 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerd0011092009-11-10 07:23:37 +000011277 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattner4ca73902009-11-08 21:20:06 +000011278 return 0;
11279 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011280 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11281 // Can fold binop, compare or shift here if the RHS is a constant,
11282 // otherwise call FoldPHIArgBinOpIntoPHI.
11283 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11284 if (ConstantOp == 0)
11285 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011286 } else {
11287 return 0; // Cannot fold this operation.
11288 }
11289
11290 // Check to see if all arguments are the same operation.
11291 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +000011292 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11293 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011294 return 0;
11295 if (CastSrcTy) {
11296 if (I->getOperand(0)->getType() != CastSrcTy)
11297 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011298 } else if (I->getOperand(1) != ConstantOp) {
11299 return 0;
11300 }
11301 }
11302
11303 // Okay, they are all the same operation. Create a new PHI node of the
11304 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000011305 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11306 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011307 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11308
11309 Value *InVal = FirstInst->getOperand(0);
11310 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11311
11312 // Add all operands to the new PHI.
11313 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11314 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11315 if (NewInVal != InVal)
11316 InVal = 0;
11317 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11318 }
11319
11320 Value *PhiVal;
11321 if (InVal) {
11322 // The new PHI unions all of the same values together. This is really
11323 // common, so we handle it intelligently here for compile-time speed.
11324 PhiVal = InVal;
11325 delete NewPN;
11326 } else {
11327 InsertNewInstBefore(NewPN, PN);
11328 PhiVal = NewPN;
11329 }
11330
11331 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +000011332 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011333 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +000011334
Chris Lattnerfc984e92008-04-29 17:13:43 +000011335 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011336 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +000011337
Chris Lattner38751f82009-11-01 20:04:24 +000011338 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11339 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11340 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011341}
11342
11343/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11344/// that is dead.
11345static bool DeadPHICycle(PHINode *PN,
11346 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11347 if (PN->use_empty()) return true;
11348 if (!PN->hasOneUse()) return false;
11349
11350 // Remember this node, and if we find the cycle, return.
11351 if (!PotentiallyDeadPHIs.insert(PN))
11352 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000011353
11354 // Don't scan crazily complex things.
11355 if (PotentiallyDeadPHIs.size() == 16)
11356 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011357
11358 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11359 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11360
11361 return false;
11362}
11363
Chris Lattner27b695d2007-11-06 21:52:06 +000011364/// PHIsEqualValue - Return true if this phi node is always equal to
11365/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11366/// z = some value; x = phi (y, z); y = phi (x, z)
11367static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11368 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11369 // See if we already saw this PHI node.
11370 if (!ValueEqualPHIs.insert(PN))
11371 return true;
11372
11373 // Don't scan crazily complex things.
11374 if (ValueEqualPHIs.size() == 16)
11375 return false;
11376
11377 // Scan the operands to see if they are either phi nodes or are equal to
11378 // the value.
11379 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11380 Value *Op = PN->getIncomingValue(i);
11381 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11382 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11383 return false;
11384 } else if (Op != NonPhiInVal)
11385 return false;
11386 }
11387
11388 return true;
11389}
11390
11391
Chris Lattner1cd526b2009-11-08 19:23:30 +000011392namespace {
11393struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +000011394 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +000011395 unsigned Shift; // The amount shifted.
11396 Instruction *Inst; // The trunc instruction.
11397
Chris Lattner073c12c2009-11-09 01:38:00 +000011398 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11399 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +000011400
11401 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +000011402 if (PHIId < RHS.PHIId) return true;
11403 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011404 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +000011405 if (Shift > RHS.Shift) return false;
11406 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +000011407 RHS.Inst->getType()->getPrimitiveSizeInBits();
11408 }
11409};
Chris Lattner073c12c2009-11-09 01:38:00 +000011410
11411struct LoweredPHIRecord {
11412 PHINode *PN; // The PHI that was lowered.
11413 unsigned Shift; // The amount shifted.
11414 unsigned Width; // The width extracted.
11415
11416 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11417 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11418
11419 // Ctor form used by DenseMap.
11420 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11421 : PN(pn), Shift(Sh), Width(0) {}
11422};
11423}
11424
11425namespace llvm {
11426 template<>
11427 struct DenseMapInfo<LoweredPHIRecord> {
11428 static inline LoweredPHIRecord getEmptyKey() {
11429 return LoweredPHIRecord(0, 0);
11430 }
11431 static inline LoweredPHIRecord getTombstoneKey() {
11432 return LoweredPHIRecord(0, 1);
11433 }
11434 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11435 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11436 (Val.Width>>3);
11437 }
11438 static bool isEqual(const LoweredPHIRecord &LHS,
11439 const LoweredPHIRecord &RHS) {
11440 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11441 LHS.Width == RHS.Width;
11442 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011443 };
Chris Lattner169f3a22009-12-15 07:26:43 +000011444 template <>
11445 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner1cd526b2009-11-08 19:23:30 +000011446}
11447
11448
11449/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11450/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11451/// so, we split the PHI into the various pieces being extracted. This sort of
11452/// thing is introduced when SROA promotes an aggregate to large integer values.
11453///
11454/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11455/// inttoptr. We should produce new PHIs in the right type.
11456///
Chris Lattner073c12c2009-11-09 01:38:00 +000011457Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11458 // PHIUsers - Keep track of all of the truncated values extracted from a set
11459 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011460 SmallVector<PHIUsageRecord, 16> PHIUsers;
11461
Chris Lattner073c12c2009-11-09 01:38:00 +000011462 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11463 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11464 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11465 // check the uses of (to ensure they are all extracts).
11466 SmallVector<PHINode*, 8> PHIsToSlice;
11467 SmallPtrSet<PHINode*, 8> PHIsInspected;
11468
11469 PHIsToSlice.push_back(&FirstPhi);
11470 PHIsInspected.insert(&FirstPhi);
11471
11472 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11473 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011474
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011475 // Scan the input list of the PHI. If any input is an invoke, and if the
11476 // input is defined in the predecessor, then we won't be split the critical
11477 // edge which is required to insert a truncate. Because of this, we have to
11478 // bail out.
11479 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11480 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11481 if (II == 0) continue;
11482 if (II->getParent() != PN->getIncomingBlock(i))
11483 continue;
11484
11485 // If we have a phi, and if it's directly in the predecessor, then we have
11486 // a critical edge where we need to put the truncate. Since we can't
11487 // split the edge in instcombine, we have to bail out.
11488 return 0;
11489 }
11490
11491
Chris Lattner073c12c2009-11-09 01:38:00 +000011492 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11493 UI != E; ++UI) {
11494 Instruction *User = cast<Instruction>(*UI);
11495
11496 // If the user is a PHI, inspect its uses recursively.
11497 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11498 if (PHIsInspected.insert(UserPN))
11499 PHIsToSlice.push_back(UserPN);
11500 continue;
11501 }
11502
11503 // Truncates are always ok.
11504 if (isa<TruncInst>(User)) {
11505 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11506 continue;
11507 }
11508
11509 // Otherwise it must be a lshr which can only be used by one trunc.
11510 if (User->getOpcode() != Instruction::LShr ||
11511 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11512 !isa<ConstantInt>(User->getOperand(1)))
11513 return 0;
11514
11515 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11516 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011517 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011518 }
11519
11520 // If we have no users, they must be all self uses, just nuke the PHI.
11521 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +000011522 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011523
11524 // If this phi node is transformable, create new PHIs for all the pieces
11525 // extracted out of it. First, sort the users by their offset and size.
11526 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11527
Chris Lattner073c12c2009-11-09 01:38:00 +000011528 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11529 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11530 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11531 );
Chris Lattner1cd526b2009-11-08 19:23:30 +000011532
Chris Lattner073c12c2009-11-09 01:38:00 +000011533 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11534 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011535 DenseMap<BasicBlock*, Value*> PredValues;
11536
Chris Lattner073c12c2009-11-09 01:38:00 +000011537 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11538 // introduce redundant PHIs.
11539 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11540
11541 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11542 unsigned PHIId = PHIUsers[UserI].PHIId;
11543 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011544 unsigned Offset = PHIUsers[UserI].Shift;
11545 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011546
Chris Lattner073c12c2009-11-09 01:38:00 +000011547 PHINode *EltPHI;
11548
11549 // If we've already lowered a user like this, reuse the previously lowered
11550 // value.
11551 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +000011552
Chris Lattner073c12c2009-11-09 01:38:00 +000011553 // Otherwise, Create the new PHI node for this user.
11554 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11555 assert(EltPHI->getType() != PN->getType() &&
11556 "Truncate didn't shrink phi?");
11557
11558 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11559 BasicBlock *Pred = PN->getIncomingBlock(i);
11560 Value *&PredVal = PredValues[Pred];
11561
11562 // If we already have a value for this predecessor, reuse it.
11563 if (PredVal) {
11564 EltPHI->addIncoming(PredVal, Pred);
11565 continue;
11566 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011567
Chris Lattner073c12c2009-11-09 01:38:00 +000011568 // Handle the PHI self-reuse case.
11569 Value *InVal = PN->getIncomingValue(i);
11570 if (InVal == PN) {
11571 PredVal = EltPHI;
11572 EltPHI->addIncoming(PredVal, Pred);
11573 continue;
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011574 }
11575
11576 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattner073c12c2009-11-09 01:38:00 +000011577 // If the incoming value was a PHI, and if it was one of the PHIs we
11578 // already rewrote it, just use the lowered value.
11579 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11580 PredVal = Res;
11581 EltPHI->addIncoming(PredVal, Pred);
11582 continue;
11583 }
11584 }
11585
11586 // Otherwise, do an extract in the predecessor.
11587 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11588 Value *Res = InVal;
11589 if (Offset)
11590 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11591 Offset), "extract");
11592 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11593 PredVal = Res;
11594 EltPHI->addIncoming(Res, Pred);
11595
11596 // If the incoming value was a PHI, and if it was one of the PHIs we are
11597 // rewriting, we will ultimately delete the code we inserted. This
11598 // means we need to revisit that PHI to make sure we extract out the
11599 // needed piece.
11600 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11601 if (PHIsInspected.count(OldInVal)) {
11602 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11603 OldInVal)-PHIsToSlice.begin();
11604 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11605 cast<Instruction>(Res)));
11606 ++UserE;
11607 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011608 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011609 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011610
Chris Lattner073c12c2009-11-09 01:38:00 +000011611 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11612 << *EltPHI << '\n');
11613 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011614 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011615
Chris Lattner073c12c2009-11-09 01:38:00 +000011616 // Replace the use of this piece with the PHI node.
11617 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011618 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011619
11620 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11621 // with undefs.
11622 Value *Undef = UndefValue::get(FirstPhi.getType());
11623 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11624 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11625 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011626}
11627
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011628// PHINode simplification
11629//
11630Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11631 // If LCSSA is around, don't mess with Phi nodes
11632 if (MustPreserveLCSSA) return 0;
11633
11634 if (Value *V = PN.hasConstantValue())
11635 return ReplaceInstUsesWith(PN, V);
11636
11637 // If all PHI operands are the same operation, pull them through the PHI,
11638 // reducing code size.
11639 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000011640 isa<Instruction>(PN.getIncomingValue(1)) &&
11641 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11642 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11643 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11644 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011645 PN.getIncomingValue(0)->hasOneUse())
11646 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11647 return Result;
11648
11649 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11650 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11651 // PHI)... break the cycle.
11652 if (PN.hasOneUse()) {
11653 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11654 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11655 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11656 PotentiallyDeadPHIs.insert(&PN);
11657 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011658 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011659 }
11660
11661 // If this phi has a single use, and if that use just computes a value for
11662 // the next iteration of a loop, delete the phi. This occurs with unused
11663 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11664 // common case here is good because the only other things that catch this
11665 // are induction variable analysis (sometimes) and ADCE, which is only run
11666 // late.
11667 if (PHIUser->hasOneUse() &&
11668 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11669 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011670 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011671 }
11672 }
11673
Chris Lattner27b695d2007-11-06 21:52:06 +000011674 // We sometimes end up with phi cycles that non-obviously end up being the
11675 // same value, for example:
11676 // z = some value; x = phi (y, z); y = phi (x, z)
11677 // where the phi nodes don't necessarily need to be in the same block. Do a
11678 // quick check to see if the PHI node only contains a single non-phi value, if
11679 // so, scan to see if the phi cycle is actually equal to that value.
11680 {
11681 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11682 // Scan for the first non-phi operand.
11683 while (InValNo != NumOperandVals &&
11684 isa<PHINode>(PN.getIncomingValue(InValNo)))
11685 ++InValNo;
11686
11687 if (InValNo != NumOperandVals) {
11688 Value *NonPhiInVal = PN.getOperand(InValNo);
11689
11690 // Scan the rest of the operands to see if there are any conflicts, if so
11691 // there is no need to recursively scan other phis.
11692 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11693 Value *OpVal = PN.getIncomingValue(InValNo);
11694 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11695 break;
11696 }
11697
11698 // If we scanned over all operands, then we have one unique value plus
11699 // phi values. Scan PHI nodes to see if they all merge in each other or
11700 // the value.
11701 if (InValNo == NumOperandVals) {
11702 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11703 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11704 return ReplaceInstUsesWith(PN, NonPhiInVal);
11705 }
11706 }
11707 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011708
Dan Gohman2cc8e842009-10-31 14:22:52 +000011709 // If there are multiple PHIs, sort their operands so that they all list
11710 // the blocks in the same order. This will help identical PHIs be eliminated
11711 // by other passes. Other passes shouldn't depend on this for correctness
11712 // however.
11713 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11714 if (&PN != FirstPN)
11715 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +000011716 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +000011717 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11718 if (BBA != BBB) {
11719 Value *VA = PN.getIncomingValue(i);
11720 unsigned j = PN.getBasicBlockIndex(BBB);
11721 Value *VB = PN.getIncomingValue(j);
11722 PN.setIncomingBlock(i, BBB);
11723 PN.setIncomingValue(i, VB);
11724 PN.setIncomingBlock(j, BBA);
11725 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +000011726 // NOTE: Instcombine normally would want us to "return &PN" if we
11727 // modified any of the operands of an instruction. However, since we
11728 // aren't adding or removing uses (just rearranging them) we don't do
11729 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +000011730 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011731 }
11732
Chris Lattner1cd526b2009-11-08 19:23:30 +000011733 // If this is an integer PHI and we know that it has an illegal type, see if
11734 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11735 // PHI into the various pieces being extracted. This sort of thing is
11736 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +000011737 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +000011738 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11739 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11740 return Res;
11741
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011742 return 0;
11743}
11744
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011745Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +000011746 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11747
11748 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11749 return ReplaceInstUsesWith(GEP, V);
11750
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011751 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011752
11753 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011754 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011755
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011756 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011757 if (TD) {
11758 bool MadeChange = false;
11759 unsigned PtrSize = TD->getPointerSizeInBits();
11760
11761 gep_type_iterator GTI = gep_type_begin(GEP);
11762 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11763 I != E; ++I, ++GTI) {
11764 if (!isa<SequentialType>(*GTI)) continue;
11765
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011766 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011767 // to what we need. If narrower, sign-extend it to what we need. This
11768 // explicit cast can make subsequent optimizations more obvious.
11769 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011770 if (OpBits == PtrSize)
11771 continue;
11772
Chris Lattnerd6164c22009-08-30 20:01:10 +000011773 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011774 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011775 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011776 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011777 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011778
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011779 // Combine Indices - If the source pointer to this getelementptr instruction
11780 // is a getelementptr instruction, combine the indices of the two
11781 // getelementptr instructions into a single instruction.
11782 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011783 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011784 // Note that if our source is a gep chain itself that we wait for that
11785 // chain to be resolved before we perform this transformation. This
11786 // avoids us creating a TON of code in some cases.
11787 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011788 if (GetElementPtrInst *SrcGEP =
11789 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11790 if (SrcGEP->getNumOperands() == 2)
11791 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011792
11793 SmallVector<Value*, 8> Indices;
11794
11795 // Find out whether the last index in the source GEP is a sequential idx.
11796 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000011797 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11798 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011799 EndsWithSequential = !isa<StructType>(*I);
11800
11801 // Can we combine the two pointer arithmetics offsets?
11802 if (EndsWithSequential) {
11803 // Replace: gep (gep %P, long B), long A, ...
11804 // With: T = long A+B; gep %P, T, ...
11805 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011806 Value *Sum;
11807 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11808 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011809 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011810 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011811 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011812 Sum = SO1;
11813 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000011814 // If they aren't the same type, then the input hasn't been processed
11815 // by the loop above yet (which canonicalizes sequential index types to
11816 // intptr_t). Just avoid transforming this until the input has been
11817 // normalized.
11818 if (SO1->getType() != GO1->getType())
11819 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000011820 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011821 }
11822
Chris Lattner1c641fc2009-08-30 05:30:55 +000011823 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011824 if (Src->getNumOperands() == 2) {
11825 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011826 GEP.setOperand(1, Sum);
11827 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011828 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011829 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011830 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011831 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011832 } else if (isa<Constant>(*GEP.idx_begin()) &&
11833 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011834 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011835 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011836 Indices.append(Src->op_begin()+1, Src->op_end());
11837 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011838 }
11839
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011840 if (!Indices.empty())
11841 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11842 Src->isInBounds()) ?
11843 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11844 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011845 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011846 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011847 }
11848
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011849 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11850 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011851 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011852
Chris Lattner83288fa2009-08-30 20:38:21 +000011853 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11854 // want to change the gep until the bitcasts are eliminated.
11855 if (getBitCastOperand(X)) {
11856 Worklist.AddValue(PtrOp);
11857 return 0;
11858 }
11859
Chris Lattner5594a482009-11-27 00:29:05 +000011860 bool HasZeroPointerIndex = false;
11861 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11862 HasZeroPointerIndex = C->isZero();
11863
Chris Lattnerf3a23592009-08-30 20:36:46 +000011864 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11865 // into : GEP [10 x i8]* X, i32 0, ...
11866 //
11867 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11868 // into : GEP i8* X, ...
11869 //
11870 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011871 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011872 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11873 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011874 if (const ArrayType *CATy =
11875 dyn_cast<ArrayType>(CPTy->getElementType())) {
11876 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11877 if (CATy->getElementType() == XTy->getElementType()) {
11878 // -> GEP i8* X, ...
11879 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011880 return cast<GEPOperator>(&GEP)->isInBounds() ?
11881 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11882 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011883 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11884 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011885 }
11886
11887 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011888 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011889 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011890 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011891 // At this point, we know that the cast source type is a pointer
11892 // to an array of the same type as the destination pointer
11893 // array. Because the array type is never stepped over (there
11894 // is a leading zero) we can fold the cast into this GEP.
11895 GEP.setOperand(0, X);
11896 return &GEP;
11897 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011898 }
11899 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011900 } else if (GEP.getNumOperands() == 2) {
11901 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011902 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11903 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011904 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11905 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011906 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011907 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11908 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011909 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011910 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011911 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011912 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11913 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011914 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011915 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011916 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011917 }
11918
11919 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011920 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011921 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011922 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011923
Owen Anderson35b47072009-08-13 21:58:54 +000011924 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011925 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011926 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011927
11928 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11929 // allow either a mul, shift, or constant here.
11930 Value *NewIdx = 0;
11931 ConstantInt *Scale = 0;
11932 if (ArrayEltSize == 1) {
11933 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011934 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011935 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011936 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011937 Scale = CI;
11938 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11939 if (Inst->getOpcode() == Instruction::Shl &&
11940 isa<ConstantInt>(Inst->getOperand(1))) {
11941 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11942 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011943 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011944 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011945 NewIdx = Inst->getOperand(0);
11946 } else if (Inst->getOpcode() == Instruction::Mul &&
11947 isa<ConstantInt>(Inst->getOperand(1))) {
11948 Scale = cast<ConstantInt>(Inst->getOperand(1));
11949 NewIdx = Inst->getOperand(0);
11950 }
11951 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011952
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011953 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011954 // out, perform the transformation. Note, we don't know whether Scale is
11955 // signed or not. We'll use unsigned version of division/modulo
11956 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011957 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011958 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011959 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011960 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011961 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011962 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11963 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011964 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011965 }
11966
11967 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011968 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011969 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011970 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011971 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11972 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11973 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011974 // The NewGEP must be pointer typed, so must the old one -> BitCast
11975 return new BitCastInst(NewGEP, GEP.getType());
11976 }
11977 }
11978 }
11979 }
Chris Lattner111ea772009-01-09 04:53:57 +000011980
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011981 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011982 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011983 /// Y = gep X, <...constant indices...>
11984 /// into a gep of the original struct. This is important for SROA and alias
11985 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011986 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011987 if (TD &&
11988 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011989 // Determine how much the GEP moves the pointer. We are guaranteed to get
11990 // a constant back from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +000011991 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011992 int64_t Offset = OffsetV->getSExtValue();
11993
11994 // If this GEP instruction doesn't move the pointer, just replace the GEP
11995 // with a bitcast of the real input to the dest type.
11996 if (Offset == 0) {
11997 // If the bitcast is of an allocation, and the allocation will be
11998 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000011999 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000012000 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012001 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12002 if (Instruction *I = visitBitCast(*BCI)) {
12003 if (I != BCI) {
12004 I->takeName(BCI);
12005 BCI->getParent()->getInstList().insert(BCI, I);
12006 ReplaceInstUsesWith(*BCI, I);
12007 }
12008 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000012009 }
Chris Lattner111ea772009-01-09 04:53:57 +000012010 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012011 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000012012 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012013
12014 // Otherwise, if the offset is non-zero, we need to find out if there is a
12015 // field at Offset in 'A's type. If so, we can pull the cast through the
12016 // GEP.
12017 SmallVector<Value*, 8> NewIndices;
12018 const Type *InTy =
12019 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000012020 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012021 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12022 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12023 NewIndices.end()) :
12024 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12025 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000012026
12027 if (NGEP->getType() == GEP.getType())
12028 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012029 NGEP->takeName(&GEP);
12030 return new BitCastInst(NGEP, GEP.getType());
12031 }
Chris Lattner111ea772009-01-09 04:53:57 +000012032 }
12033 }
12034
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012035 return 0;
12036}
12037
Victor Hernandezb1687302009-10-23 21:09:37 +000012038Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +000012039 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000012040 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012041 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12042 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012043 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000012044 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000012045 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000012046 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012047
12048 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000012049 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012050 //
12051 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000012052 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012053
12054 // Now that I is pointing to the first non-allocation-inst in the block,
12055 // insert our getelementptr instruction...
12056 //
Owen Anderson35b47072009-08-13 21:58:54 +000012057 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000012058 Value *Idx[2];
12059 Idx[0] = NullIdx;
12060 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012061 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12062 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012063
12064 // Now make everything use the getelementptr instead of the original
12065 // allocation.
12066 return ReplaceInstUsesWith(AI, V);
12067 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000012068 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012069 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000012070 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012071
Dan Gohmana80e2712009-07-21 23:21:54 +000012072 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000012073 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000012074 // Note that we only do this for alloca's, because malloc should allocate
12075 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000012076 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000012077 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000012078
12079 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12080 if (AI.getAlignment() == 0)
12081 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12082 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012083
12084 return 0;
12085}
12086
Victor Hernandez93946082009-10-24 04:23:03 +000012087Instruction *InstCombiner::visitFree(Instruction &FI) {
12088 Value *Op = FI.getOperand(1);
12089
12090 // free undef -> unreachable.
12091 if (isa<UndefValue>(Op)) {
12092 // Insert a new store to null because we cannot modify the CFG here.
12093 new StoreInst(ConstantInt::getTrue(*Context),
12094 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12095 return EraseInstFromFunction(FI);
12096 }
12097
12098 // If we have 'free null' delete the instruction. This can happen in stl code
12099 // when lots of inlining happens.
12100 if (isa<ConstantPointerNull>(Op))
12101 return EraseInstFromFunction(FI);
12102
Victor Hernandezf9a7a332009-10-26 23:43:48 +000012103 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +000012104 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +000012105 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12106 if (Op->hasOneUse() && CI->hasOneUse()) {
12107 EraseInstFromFunction(FI);
12108 EraseInstFromFunction(*CI);
12109 return EraseInstFromFunction(*cast<Instruction>(Op));
12110 }
12111 } else {
12112 // Op is a call to malloc
12113 if (Op->hasOneUse()) {
12114 EraseInstFromFunction(FI);
12115 return EraseInstFromFunction(*cast<Instruction>(Op));
12116 }
12117 }
Dan Gohman1674ea52009-10-27 00:11:02 +000012118 }
Victor Hernandez93946082009-10-24 04:23:03 +000012119
12120 return 0;
12121}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012122
12123/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000012124static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000012125 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012126 User *CI = cast<User>(LI.getOperand(0));
12127 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000012128 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012129
Mon P Wangbd05ed82009-02-07 22:19:29 +000012130 const PointerType *DestTy = cast<PointerType>(CI->getType());
12131 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012132 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000012133
12134 // If the address spaces don't match, don't eliminate the cast.
12135 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12136 return 0;
12137
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012138 const Type *SrcPTy = SrcTy->getElementType();
12139
12140 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
12141 isa<VectorType>(DestPTy)) {
12142 // If the source is an array, the code below will not succeed. Check to
12143 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12144 // constants.
12145 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12146 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12147 if (ASrcTy->getNumElements() != 0) {
12148 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000012149 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12150 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000012151 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012152 SrcTy = cast<PointerType>(CastOp->getType());
12153 SrcPTy = SrcTy->getElementType();
12154 }
12155
Dan Gohmana80e2712009-07-21 23:21:54 +000012156 if (IC.getTargetData() &&
12157 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012158 isa<VectorType>(SrcPTy)) &&
12159 // Do not allow turning this into a load of an integer, which is then
12160 // casted to a pointer, this pessimizes pointer analysis a lot.
12161 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000012162 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12163 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012164
12165 // Okay, we are casting from one integer or pointer type to another of
12166 // the same size. Instead of casting the pointer before the load, cast
12167 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000012168 Value *NewLoad =
12169 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012170 // Now cast the result of the load.
12171 return new BitCastInst(NewLoad, LI.getType());
12172 }
12173 }
12174 }
12175 return 0;
12176}
12177
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012178Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12179 Value *Op = LI.getOperand(0);
12180
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012181 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012182 if (TD) {
12183 unsigned KnownAlign =
12184 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12185 if (KnownAlign >
12186 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12187 LI.getAlignment()))
12188 LI.setAlignment(KnownAlign);
12189 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012190
Chris Lattnerf3a23592009-08-30 20:36:46 +000012191 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012192 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000012193 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012194 return Res;
12195
12196 // None of the following transforms are legal for volatile loads.
12197 if (LI.isVolatile()) return 0;
12198
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012199 // Do really simple store-to-load forwarding and load CSE, to catch cases
12200 // where there are several consequtive memory accesses to the same location,
12201 // separated by a few arithmetic operations.
12202 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000012203 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12204 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012205
Chris Lattner05274832009-10-22 06:25:11 +000012206 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000012207 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12208 const Value *GEPI0 = GEPI->getOperand(0);
12209 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000012210 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012211 // Insert a new store to null instruction before the load to indicate
12212 // that this code is not reachable. We do this instead of inserting
12213 // an unreachable instruction directly because we cannot modify the
12214 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012215 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000012216 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012217 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012218 }
Christopher Lamb2c175392007-12-29 07:56:53 +000012219 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012220
Chris Lattner05274832009-10-22 06:25:11 +000012221 // load null/undef -> unreachable
12222 // TODO: Consider a target hook for valid address spaces for this xform.
12223 if (isa<UndefValue>(Op) ||
12224 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12225 // Insert a new store to null instruction before the load to indicate that
12226 // this code is not reachable. We do this instead of inserting an
12227 // unreachable instruction directly because we cannot modify the CFG.
12228 new StoreInst(UndefValue::get(LI.getType()),
12229 Constant::getNullValue(Op->getType()), &LI);
12230 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012231 }
Chris Lattner05274832009-10-22 06:25:11 +000012232
12233 // Instcombine load (constantexpr_cast global) -> cast (load global)
12234 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12235 if (CE->isCast())
12236 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12237 return Res;
12238
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012239 if (Op->hasOneUse()) {
12240 // Change select and PHI nodes to select values instead of addresses: this
12241 // helps alias analysis out a lot, allows many others simplifications, and
12242 // exposes redundancy in the code.
12243 //
12244 // Note that we cannot do the transformation unless we know that the
12245 // introduced loads cannot trap! Something like this is valid as long as
12246 // the condition is always false: load (select bool %C, int* null, int* %G),
12247 // but it would not be valid if we transformed it to load from null
12248 // unconditionally.
12249 //
12250 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12251 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
12252 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12253 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000012254 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12255 SI->getOperand(1)->getName()+".val");
12256 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12257 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000012258 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012259 }
12260
12261 // load (select (cond, null, P)) -> load P
12262 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12263 if (C->isNullValue()) {
12264 LI.setOperand(0, SI->getOperand(2));
12265 return &LI;
12266 }
12267
12268 // load (select (cond, P, null)) -> load P
12269 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12270 if (C->isNullValue()) {
12271 LI.setOperand(0, SI->getOperand(1));
12272 return &LI;
12273 }
12274 }
12275 }
12276 return 0;
12277}
12278
12279/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000012280/// when possible. This makes it generally easy to do alias analysis and/or
12281/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012282static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12283 User *CI = cast<User>(SI.getOperand(1));
12284 Value *CastOp = CI->getOperand(0);
12285
12286 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000012287 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12288 if (SrcTy == 0) return 0;
12289
12290 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012291
Chris Lattnera032c0e2009-01-16 20:08:59 +000012292 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12293 return 0;
12294
Chris Lattner54dddc72009-01-24 01:00:13 +000012295 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12296 /// to its first element. This allows us to handle things like:
12297 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12298 /// on 32-bit hosts.
12299 SmallVector<Value*, 4> NewGEPIndices;
12300
Chris Lattnera032c0e2009-01-16 20:08:59 +000012301 // If the source is an array, the code below will not succeed. Check to
12302 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12303 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000012304 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12305 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000012306 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000012307 NewGEPIndices.push_back(Zero);
12308
12309 while (1) {
12310 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000012311 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000012312 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000012313 NewGEPIndices.push_back(Zero);
12314 SrcPTy = STy->getElementType(0);
12315 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12316 NewGEPIndices.push_back(Zero);
12317 SrcPTy = ATy->getElementType();
12318 } else {
12319 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012320 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012321 }
12322
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012323 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000012324 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000012325
12326 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12327 return 0;
12328
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012329 // If the pointers point into different address spaces or if they point to
12330 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000012331 if (!IC.getTargetData() ||
12332 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012333 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000012334 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12335 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000012336 return 0;
12337
12338 // Okay, we are casting from one integer or pointer type to another of
12339 // the same size. Instead of casting the pointer before
12340 // the store, cast the value to be stored.
12341 Value *NewCast;
12342 Value *SIOp0 = SI.getOperand(0);
12343 Instruction::CastOps opcode = Instruction::BitCast;
12344 const Type* CastSrcTy = SIOp0->getType();
12345 const Type* CastDstTy = SrcPTy;
12346 if (isa<PointerType>(CastDstTy)) {
12347 if (CastSrcTy->isInteger())
12348 opcode = Instruction::IntToPtr;
12349 } else if (isa<IntegerType>(CastDstTy)) {
12350 if (isa<PointerType>(SIOp0->getType()))
12351 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012352 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012353
12354 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12355 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012356 if (!NewGEPIndices.empty())
12357 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12358 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000012359
Chris Lattnerad7516a2009-08-30 18:50:58 +000012360 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12361 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000012362 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012363}
12364
Chris Lattner6fd8c802008-11-27 08:56:30 +000012365/// equivalentAddressValues - Test if A and B will obviously have the same
12366/// value. This includes recognizing that %t0 and %t1 will have the same
12367/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000012368/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012369/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000012370/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012371/// %t2 = load i32* %t1
12372///
12373static bool equivalentAddressValues(Value *A, Value *B) {
12374 // Test if the values are trivially equivalent.
12375 if (A == B) return true;
12376
12377 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012378 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12379 // its only used to compare two uses within the same basic block, which
12380 // means that they'll always either have the same value or one of them
12381 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000012382 if (isa<BinaryOperator>(A) ||
12383 isa<CastInst>(A) ||
12384 isa<PHINode>(A) ||
12385 isa<GetElementPtrInst>(A))
12386 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012387 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000012388 return true;
12389
12390 // Otherwise they may not be equivalent.
12391 return false;
12392}
12393
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012394// If this instruction has two uses, one of which is a llvm.dbg.declare,
12395// return the llvm.dbg.declare.
12396DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12397 if (!V->hasNUses(2))
12398 return 0;
12399 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12400 UI != E; ++UI) {
12401 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12402 return DI;
12403 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12404 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12405 return DI;
12406 }
12407 }
12408 return 0;
12409}
12410
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012411Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12412 Value *Val = SI.getOperand(0);
12413 Value *Ptr = SI.getOperand(1);
12414
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012415 // If the RHS is an alloca with a single use, zapify the store, making the
12416 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012417 // If the RHS is an alloca with a two uses, the other one being a
12418 // llvm.dbg.declare, zapify the store and the declare, making the
12419 // alloca dead. We must do this to prevent declare's from affecting
12420 // codegen.
12421 if (!SI.isVolatile()) {
12422 if (Ptr->hasOneUse()) {
12423 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012424 EraseInstFromFunction(SI);
12425 ++NumCombined;
12426 return 0;
12427 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012428 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12429 if (isa<AllocaInst>(GEP->getOperand(0))) {
12430 if (GEP->getOperand(0)->hasOneUse()) {
12431 EraseInstFromFunction(SI);
12432 ++NumCombined;
12433 return 0;
12434 }
12435 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12436 EraseInstFromFunction(*DI);
12437 EraseInstFromFunction(SI);
12438 ++NumCombined;
12439 return 0;
12440 }
12441 }
12442 }
12443 }
12444 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12445 EraseInstFromFunction(*DI);
12446 EraseInstFromFunction(SI);
12447 ++NumCombined;
12448 return 0;
12449 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012450 }
12451
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012452 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012453 if (TD) {
12454 unsigned KnownAlign =
12455 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12456 if (KnownAlign >
12457 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12458 SI.getAlignment()))
12459 SI.setAlignment(KnownAlign);
12460 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012461
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012462 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012463 // stores to the same location, separated by a few arithmetic operations. This
12464 // situation often occurs with bitfield accesses.
12465 BasicBlock::iterator BBI = &SI;
12466 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12467 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000012468 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000012469 // Don't count debug info directives, lest they affect codegen,
12470 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12471 // It is necessary for correctness to skip those that feed into a
12472 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000012473 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000012474 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012475 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012476 continue;
12477 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012478
12479 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12480 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000012481 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12482 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012483 ++NumDeadStore;
12484 ++BBI;
12485 EraseInstFromFunction(*PrevSI);
12486 continue;
12487 }
12488 break;
12489 }
12490
12491 // If this is a load, we have to stop. However, if the loaded value is from
12492 // the pointer we're loading and is producing the pointer we're storing,
12493 // then *this* store is dead (X = load P; store X -> P).
12494 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012495 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12496 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012497 EraseInstFromFunction(SI);
12498 ++NumCombined;
12499 return 0;
12500 }
12501 // Otherwise, this is a load from some other location. Stores before it
12502 // may not be dead.
12503 break;
12504 }
12505
12506 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000012507 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012508 break;
12509 }
12510
12511
12512 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12513
12514 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000012515 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012516 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012517 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012518 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000012519 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012520 ++NumCombined;
12521 }
12522 return 0; // Do not modify these!
12523 }
12524
12525 // store undef, Ptr -> noop
12526 if (isa<UndefValue>(Val)) {
12527 EraseInstFromFunction(SI);
12528 ++NumCombined;
12529 return 0;
12530 }
12531
12532 // If the pointer destination is a cast, see if we can fold the cast into the
12533 // source instead.
12534 if (isa<CastInst>(Ptr))
12535 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12536 return Res;
12537 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12538 if (CE->isCast())
12539 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12540 return Res;
12541
12542
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012543 // If this store is the last instruction in the basic block (possibly
12544 // excepting debug info instructions and the pointer bitcasts that feed
12545 // into them), and if the block ends with an unconditional branch, try
12546 // to move it to the successor block.
12547 BBI = &SI;
12548 do {
12549 ++BBI;
12550 } while (isa<DbgInfoIntrinsic>(BBI) ||
12551 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012552 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12553 if (BI->isUnconditional())
12554 if (SimplifyStoreAtEndOfBlock(SI))
12555 return 0; // xform done!
12556
12557 return 0;
12558}
12559
12560/// SimplifyStoreAtEndOfBlock - Turn things like:
12561/// if () { *P = v1; } else { *P = v2 }
12562/// into a phi node with a store in the successor.
12563///
12564/// Simplify things like:
12565/// *P = v1; if () { *P = v2; }
12566/// into a phi node with a store in the successor.
12567///
12568bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12569 BasicBlock *StoreBB = SI.getParent();
12570
12571 // Check to see if the successor block has exactly two incoming edges. If
12572 // so, see if the other predecessor contains a store to the same location.
12573 // if so, insert a PHI node (if needed) and move the stores down.
12574 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12575
12576 // Determine whether Dest has exactly two predecessors and, if so, compute
12577 // the other predecessor.
12578 pred_iterator PI = pred_begin(DestBB);
12579 BasicBlock *OtherBB = 0;
12580 if (*PI != StoreBB)
12581 OtherBB = *PI;
12582 ++PI;
12583 if (PI == pred_end(DestBB))
12584 return false;
12585
12586 if (*PI != StoreBB) {
12587 if (OtherBB)
12588 return false;
12589 OtherBB = *PI;
12590 }
12591 if (++PI != pred_end(DestBB))
12592 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012593
12594 // Bail out if all the relevant blocks aren't distinct (this can happen,
12595 // for example, if SI is in an infinite loop)
12596 if (StoreBB == DestBB || OtherBB == DestBB)
12597 return false;
12598
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012599 // Verify that the other block ends in a branch and is not otherwise empty.
12600 BasicBlock::iterator BBI = OtherBB->getTerminator();
12601 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12602 if (!OtherBr || BBI == OtherBB->begin())
12603 return false;
12604
12605 // If the other block ends in an unconditional branch, check for the 'if then
12606 // else' case. there is an instruction before the branch.
12607 StoreInst *OtherStore = 0;
12608 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012609 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012610 // Skip over debugging info.
12611 while (isa<DbgInfoIntrinsic>(BBI) ||
12612 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12613 if (BBI==OtherBB->begin())
12614 return false;
12615 --BBI;
12616 }
Chris Lattner69fa3f52009-11-02 02:06:37 +000012617 // If this isn't a store, isn't a store to the same location, or if the
12618 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012619 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +000012620 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12621 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012622 return false;
12623 } else {
12624 // Otherwise, the other block ended with a conditional branch. If one of the
12625 // destinations is StoreBB, then we have the if/then case.
12626 if (OtherBr->getSuccessor(0) != StoreBB &&
12627 OtherBr->getSuccessor(1) != StoreBB)
12628 return false;
12629
12630 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12631 // if/then triangle. See if there is a store to the same ptr as SI that
12632 // lives in OtherBB.
12633 for (;; --BBI) {
12634 // Check to see if we find the matching store.
12635 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +000012636 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12637 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012638 return false;
12639 break;
12640 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012641 // If we find something that may be using or overwriting the stored
12642 // value, or if we run out of instructions, we can't do the xform.
12643 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012644 BBI == OtherBB->begin())
12645 return false;
12646 }
12647
12648 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012649 // make sure nothing reads or overwrites the stored value in
12650 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012651 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12652 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012653 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012654 return false;
12655 }
12656 }
12657
12658 // Insert a PHI node now if we need it.
12659 Value *MergedVal = OtherStore->getOperand(0);
12660 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012661 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012662 PN->reserveOperandSpace(2);
12663 PN->addIncoming(SI.getOperand(0), SI.getParent());
12664 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12665 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12666 }
12667
12668 // Advance to a place where it is safe to insert the new store and
12669 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012670 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012671 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +000012672 OtherStore->isVolatile(),
12673 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012674
12675 // Nuke the old stores.
12676 EraseInstFromFunction(SI);
12677 EraseInstFromFunction(*OtherStore);
12678 ++NumCombined;
12679 return true;
12680}
12681
12682
12683Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12684 // Change br (not X), label True, label False to: br X, label False, True
12685 Value *X = 0;
12686 BasicBlock *TrueDest;
12687 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012688 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012689 !isa<Constant>(X)) {
12690 // Swap Destinations and condition...
12691 BI.setCondition(X);
12692 BI.setSuccessor(0, FalseDest);
12693 BI.setSuccessor(1, TrueDest);
12694 return &BI;
12695 }
12696
12697 // Cannonicalize fcmp_one -> fcmp_oeq
12698 FCmpInst::Predicate FPred; Value *Y;
12699 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012700 TrueDest, FalseDest)) &&
12701 BI.getCondition()->hasOneUse())
12702 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12703 FPred == FCmpInst::FCMP_OGE) {
12704 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12705 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12706
12707 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012708 BI.setSuccessor(0, FalseDest);
12709 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012710 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012711 return &BI;
12712 }
12713
12714 // Cannonicalize icmp_ne -> icmp_eq
12715 ICmpInst::Predicate IPred;
12716 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012717 TrueDest, FalseDest)) &&
12718 BI.getCondition()->hasOneUse())
12719 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12720 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12721 IPred == ICmpInst::ICMP_SGE) {
12722 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12723 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12724 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012725 BI.setSuccessor(0, FalseDest);
12726 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012727 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012728 return &BI;
12729 }
12730
12731 return 0;
12732}
12733
12734Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12735 Value *Cond = SI.getCondition();
12736 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12737 if (I->getOpcode() == Instruction::Add)
12738 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12739 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12740 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012741 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012742 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012743 AddRHS));
12744 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012745 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012746 return &SI;
12747 }
12748 }
12749 return 0;
12750}
12751
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012752Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012753 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012754
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012755 if (!EV.hasIndices())
12756 return ReplaceInstUsesWith(EV, Agg);
12757
12758 if (Constant *C = dyn_cast<Constant>(Agg)) {
12759 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012760 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012761
12762 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012763 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012764
12765 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12766 // Extract the element indexed by the first index out of the constant
12767 Value *V = C->getOperand(*EV.idx_begin());
12768 if (EV.getNumIndices() > 1)
12769 // Extract the remaining indices out of the constant indexed by the
12770 // first index
12771 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12772 else
12773 return ReplaceInstUsesWith(EV, V);
12774 }
12775 return 0; // Can't handle other constants
12776 }
12777 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12778 // We're extracting from an insertvalue instruction, compare the indices
12779 const unsigned *exti, *exte, *insi, *inse;
12780 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12781 exte = EV.idx_end(), inse = IV->idx_end();
12782 exti != exte && insi != inse;
12783 ++exti, ++insi) {
12784 if (*insi != *exti)
12785 // The insert and extract both reference distinctly different elements.
12786 // This means the extract is not influenced by the insert, and we can
12787 // replace the aggregate operand of the extract with the aggregate
12788 // operand of the insert. i.e., replace
12789 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12790 // %E = extractvalue { i32, { i32 } } %I, 0
12791 // with
12792 // %E = extractvalue { i32, { i32 } } %A, 0
12793 return ExtractValueInst::Create(IV->getAggregateOperand(),
12794 EV.idx_begin(), EV.idx_end());
12795 }
12796 if (exti == exte && insi == inse)
12797 // Both iterators are at the end: Index lists are identical. Replace
12798 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12799 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12800 // with "i32 42"
12801 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12802 if (exti == exte) {
12803 // The extract list is a prefix of the insert list. i.e. replace
12804 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12805 // %E = extractvalue { i32, { i32 } } %I, 1
12806 // with
12807 // %X = extractvalue { i32, { i32 } } %A, 1
12808 // %E = insertvalue { i32 } %X, i32 42, 0
12809 // by switching the order of the insert and extract (though the
12810 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012811 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12812 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012813 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12814 insi, inse);
12815 }
12816 if (insi == inse)
12817 // The insert list is a prefix of the extract list
12818 // We can simply remove the common indices from the extract and make it
12819 // operate on the inserted value instead of the insertvalue result.
12820 // i.e., replace
12821 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12822 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12823 // with
12824 // %E extractvalue { i32 } { i32 42 }, 0
12825 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12826 exti, exte);
12827 }
Chris Lattner69a70752009-11-09 07:07:56 +000012828 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12829 // We're extracting from an intrinsic, see if we're the only user, which
12830 // allows us to simplify multiple result intrinsics to simpler things that
12831 // just get one value..
12832 if (II->hasOneUse()) {
12833 // Check if we're grabbing the overflow bit or the result of a 'with
12834 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12835 // and replace it with a traditional binary instruction.
12836 switch (II->getIntrinsicID()) {
12837 case Intrinsic::uadd_with_overflow:
12838 case Intrinsic::sadd_with_overflow:
12839 if (*EV.idx_begin() == 0) { // Normal result.
12840 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12841 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12842 EraseInstFromFunction(*II);
12843 return BinaryOperator::CreateAdd(LHS, RHS);
12844 }
12845 break;
12846 case Intrinsic::usub_with_overflow:
12847 case Intrinsic::ssub_with_overflow:
12848 if (*EV.idx_begin() == 0) { // Normal result.
12849 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12850 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12851 EraseInstFromFunction(*II);
12852 return BinaryOperator::CreateSub(LHS, RHS);
12853 }
12854 break;
12855 case Intrinsic::umul_with_overflow:
12856 case Intrinsic::smul_with_overflow:
12857 if (*EV.idx_begin() == 0) { // Normal result.
12858 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12859 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12860 EraseInstFromFunction(*II);
12861 return BinaryOperator::CreateMul(LHS, RHS);
12862 }
12863 break;
12864 default:
12865 break;
12866 }
12867 }
12868 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012869 // Can't simplify extracts from other values. Note that nested extracts are
12870 // already simplified implicitely by the above (extract ( extract (insert) )
12871 // will be translated into extract ( insert ( extract ) ) first and then just
12872 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012873 return 0;
12874}
12875
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012876/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12877/// is to leave as a vector operation.
12878static bool CheapToScalarize(Value *V, bool isConstant) {
12879 if (isa<ConstantAggregateZero>(V))
12880 return true;
12881 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12882 if (isConstant) return true;
12883 // If all elts are the same, we can extract.
12884 Constant *Op0 = C->getOperand(0);
12885 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12886 if (C->getOperand(i) != Op0)
12887 return false;
12888 return true;
12889 }
12890 Instruction *I = dyn_cast<Instruction>(V);
12891 if (!I) return false;
12892
12893 // Insert element gets simplified to the inserted element or is deleted if
12894 // this is constant idx extract element and its a constant idx insertelt.
12895 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12896 isa<ConstantInt>(I->getOperand(2)))
12897 return true;
12898 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12899 return true;
12900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12901 if (BO->hasOneUse() &&
12902 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12903 CheapToScalarize(BO->getOperand(1), isConstant)))
12904 return true;
12905 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12906 if (CI->hasOneUse() &&
12907 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12908 CheapToScalarize(CI->getOperand(1), isConstant)))
12909 return true;
12910
12911 return false;
12912}
12913
12914/// Read and decode a shufflevector mask.
12915///
12916/// It turns undef elements into values that are larger than the number of
12917/// elements in the input.
12918static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12919 unsigned NElts = SVI->getType()->getNumElements();
12920 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12921 return std::vector<unsigned>(NElts, 0);
12922 if (isa<UndefValue>(SVI->getOperand(2)))
12923 return std::vector<unsigned>(NElts, 2*NElts);
12924
12925 std::vector<unsigned> Result;
12926 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012927 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12928 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012929 Result.push_back(NElts*2); // undef -> 8
12930 else
Gabor Greif17396002008-06-12 21:37:33 +000012931 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012932 return Result;
12933}
12934
12935/// FindScalarElement - Given a vector and an element number, see if the scalar
12936/// value is already around as a register, for example if it were inserted then
12937/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012938static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012939 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012940 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12941 const VectorType *PTy = cast<VectorType>(V->getType());
12942 unsigned Width = PTy->getNumElements();
12943 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012944 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012945
12946 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012947 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012948 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012949 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012950 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12951 return CP->getOperand(EltNo);
12952 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12953 // If this is an insert to a variable element, we don't know what it is.
12954 if (!isa<ConstantInt>(III->getOperand(2)))
12955 return 0;
12956 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12957
12958 // If this is an insert to the element we are looking for, return the
12959 // inserted value.
12960 if (EltNo == IIElt)
12961 return III->getOperand(1);
12962
12963 // Otherwise, the insertelement doesn't modify the value, recurse on its
12964 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012965 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012966 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012967 unsigned LHSWidth =
12968 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012969 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012970 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012971 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012972 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012973 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012974 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012975 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012976 }
12977
12978 // Otherwise, we don't know.
12979 return 0;
12980}
12981
12982Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012983 // If vector val is undef, replace extract with scalar undef.
12984 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012985 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012986
12987 // If vector val is constant 0, replace extract with scalar 0.
12988 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012989 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012990
12991 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012992 // If vector val is constant with all elements the same, replace EI with
12993 // that element. When the elements are not identical, we cannot replace yet
12994 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012995 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012996 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012997 if (C->getOperand(i) != op0) {
12998 op0 = 0;
12999 break;
13000 }
13001 if (op0)
13002 return ReplaceInstUsesWith(EI, op0);
13003 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000013004
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013005 // If extracting a specified index from the vector, see if we can recursively
13006 // find a previously computed scalar that was inserted into the vector.
13007 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13008 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000013009 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013010
13011 // If this is extracting an invalid index, turn this into undef, to avoid
13012 // crashing the code below.
13013 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000013014 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013015
13016 // This instruction only demands the single element from the input vector.
13017 // If the input vector has a single use, simplify it based on this use
13018 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000013019 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000013020 APInt UndefElts(VectorWidth, 0);
13021 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013022 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000013023 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013024 EI.setOperand(0, V);
13025 return &EI;
13026 }
13027 }
13028
Owen Anderson24be4c12009-07-03 00:17:18 +000013029 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013030 return ReplaceInstUsesWith(EI, Elt);
13031
13032 // If the this extractelement is directly using a bitcast from a vector of
13033 // the same number of elements, see if we can find the source element from
13034 // it. In this case, we will end up needing to bitcast the scalars.
13035 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13036 if (const VectorType *VT =
13037 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13038 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000013039 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13040 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013041 return new BitCastInst(Elt, EI.getType());
13042 }
13043 }
13044
13045 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000013046 // Push extractelement into predecessor operation if legal and
13047 // profitable to do so
13048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13049 if (I->hasOneUse() &&
13050 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13051 Value *newEI0 =
13052 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13053 EI.getName()+".lhs");
13054 Value *newEI1 =
13055 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13056 EI.getName()+".rhs");
13057 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013058 }
Chris Lattnera97bc602009-09-08 18:48:01 +000013059 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013060 // Extracting the inserted element?
13061 if (IE->getOperand(2) == EI.getOperand(1))
13062 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13063 // If the inserted and extracted elements are constants, they must not
13064 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000013065 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000013066 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013067 EI.setOperand(0, IE->getOperand(0));
13068 return &EI;
13069 }
13070 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13071 // If this is extracting an element from a shufflevector, figure out where
13072 // it came from and extract from the appropriate input element instead.
13073 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13074 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
13075 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013076 unsigned LHSWidth =
13077 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13078
13079 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013080 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013081 else if (SrcIdx < LHSWidth*2) {
13082 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013083 Src = SVI->getOperand(1);
13084 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000013085 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013086 }
Eric Christopher1ba36872009-07-25 02:28:41 +000013087 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000013088 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13089 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013090 }
13091 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000013092 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013093 }
13094 return 0;
13095}
13096
13097/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13098/// elements from either LHS or RHS, return the shuffle mask and true.
13099/// Otherwise, return false.
13100static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000013101 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013102 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013103 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13104 "Invalid CollectSingleShuffleElements");
13105 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13106
13107 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013108 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013109 return true;
13110 } else if (V == LHS) {
13111 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013112 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013113 return true;
13114 } else if (V == RHS) {
13115 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013116 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013117 return true;
13118 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13119 // If this is an insert of an extract from some other vector, include it.
13120 Value *VecOp = IEI->getOperand(0);
13121 Value *ScalarOp = IEI->getOperand(1);
13122 Value *IdxOp = IEI->getOperand(2);
13123
13124 if (!isa<ConstantInt>(IdxOp))
13125 return false;
13126 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13127
13128 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13129 // Okay, we can handle this if the vector we are insertinting into is
13130 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000013131 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013132 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013133 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013134 return true;
13135 }
13136 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13137 if (isa<ConstantInt>(EI->getOperand(1)) &&
13138 EI->getOperand(0)->getType() == V->getType()) {
13139 unsigned ExtractedIdx =
13140 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13141
13142 // This must be extracting from either LHS or RHS.
13143 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13144 // Okay, we can handle this if the vector we are insertinting into is
13145 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000013146 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013147 // If so, update the mask to reflect the inserted value.
13148 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013149 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013150 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013151 } else {
13152 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013153 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013154 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013155
13156 }
13157 return true;
13158 }
13159 }
13160 }
13161 }
13162 }
13163 // TODO: Handle shufflevector here!
13164
13165 return false;
13166}
13167
13168/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13169/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13170/// that computes V and the LHS value of the shuffle.
13171static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013172 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013173 assert(isa<VectorType>(V->getType()) &&
13174 (RHS == 0 || V->getType() == RHS->getType()) &&
13175 "Invalid shuffle!");
13176 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13177
13178 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013179 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013180 return V;
13181 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013182 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013183 return V;
13184 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13185 // If this is an insert of an extract from some other vector, include it.
13186 Value *VecOp = IEI->getOperand(0);
13187 Value *ScalarOp = IEI->getOperand(1);
13188 Value *IdxOp = IEI->getOperand(2);
13189
13190 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13191 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13192 EI->getOperand(0)->getType() == V->getType()) {
13193 unsigned ExtractedIdx =
13194 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13195 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13196
13197 // Either the extracted from or inserted into vector must be RHSVec,
13198 // otherwise we'd end up with a shuffle of three inputs.
13199 if (EI->getOperand(0) == RHS || RHS == 0) {
13200 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000013201 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013202 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013203 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013204 return V;
13205 }
13206
13207 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000013208 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13209 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013210 // Everything but the extracted element is replaced with the RHS.
13211 for (unsigned i = 0; i != NumElts; ++i) {
13212 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000013213 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013214 }
13215 return V;
13216 }
13217
13218 // If this insertelement is a chain that comes from exactly these two
13219 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000013220 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13221 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013222 return EI->getOperand(0);
13223
13224 }
13225 }
13226 }
13227 // TODO: Handle shufflevector here!
13228
13229 // Otherwise, can't do anything fancy. Return an identity vector.
13230 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013231 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013232 return V;
13233}
13234
13235Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13236 Value *VecOp = IE.getOperand(0);
13237 Value *ScalarOp = IE.getOperand(1);
13238 Value *IdxOp = IE.getOperand(2);
13239
13240 // Inserting an undef or into an undefined place, remove this.
13241 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13242 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000013243
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013244 // If the inserted element was extracted from some other vector, and if the
13245 // indexes are constant, try to turn this into a shufflevector operation.
13246 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13247 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13248 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000013249 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013250 unsigned ExtractedIdx =
13251 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13252 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13253
13254 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13255 return ReplaceInstUsesWith(IE, VecOp);
13256
13257 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000013258 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013259
13260 // If we are extracting a value from a vector, then inserting it right
13261 // back into the same place, just use the input vector.
13262 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13263 return ReplaceInstUsesWith(IE, VecOp);
13264
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013265 // If this insertelement isn't used by some other insertelement, turn it
13266 // (and any insertelements it points to), into one big shuffle.
13267 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13268 std::vector<Constant*> Mask;
13269 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000013270 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000013271 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013272 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000013273 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000013274 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013275 }
13276 }
13277 }
13278
Eli Friedmanbefee262009-06-06 20:08:03 +000013279 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13280 APInt UndefElts(VWidth, 0);
13281 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13282 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13283 return &IE;
13284
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013285 return 0;
13286}
13287
13288
13289Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13290 Value *LHS = SVI.getOperand(0);
13291 Value *RHS = SVI.getOperand(1);
13292 std::vector<unsigned> Mask = getShuffleMask(&SVI);
13293
13294 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013295
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013296 // Undefined shuffle mask -> undefined value.
13297 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013298 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013299
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013300 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013301
13302 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13303 return 0;
13304
Evan Cheng63295ab2009-02-03 10:05:09 +000013305 APInt UndefElts(VWidth, 0);
13306 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13307 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000013308 LHS = SVI.getOperand(0);
13309 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013310 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000013311 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013312
13313 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13314 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13315 if (LHS == RHS || isa<UndefValue>(LHS)) {
13316 if (isa<UndefValue>(LHS) && LHS == RHS) {
13317 // shuffle(undef,undef,mask) -> undef.
13318 return ReplaceInstUsesWith(SVI, LHS);
13319 }
13320
13321 // Remap any references to RHS to use LHS.
13322 std::vector<Constant*> Elts;
13323 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13324 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000013325 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013326 else {
13327 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000013328 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013329 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013330 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013331 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013332 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000013333 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013334 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013335 }
13336 }
13337 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000013338 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000013339 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013340 LHS = SVI.getOperand(0);
13341 RHS = SVI.getOperand(1);
13342 MadeChange = true;
13343 }
13344
13345 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13346 bool isLHSID = true, isRHSID = true;
13347
13348 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13349 if (Mask[i] >= e*2) continue; // Ignore undef values.
13350 // Is this an identity shuffle of the LHS value?
13351 isLHSID &= (Mask[i] == i);
13352
13353 // Is this an identity shuffle of the RHS value?
13354 isRHSID &= (Mask[i]-e == i);
13355 }
13356
13357 // Eliminate identity shuffles.
13358 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13359 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13360
13361 // If the LHS is a shufflevector itself, see if we can combine it with this
13362 // one without producing an unusual shuffle. Here we are really conservative:
13363 // we are absolutely afraid of producing a shuffle mask not in the input
13364 // program, because the code gen may not be smart enough to turn a merged
13365 // shuffle into two specific shuffles: it may produce worse code. As such,
13366 // we only merge two shuffles if the result is one of the two input shuffle
13367 // masks. In this case, merging the shuffles just removes one instruction,
13368 // which we know is safe. This is good for things like turning:
13369 // (splat(splat)) -> splat.
13370 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13371 if (isa<UndefValue>(RHS)) {
13372 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13373
David Greeneb736b5d2009-11-16 21:52:23 +000013374 if (LHSMask.size() == Mask.size()) {
13375 std::vector<unsigned> NewMask;
13376 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sandse7f89b02009-11-20 13:19:51 +000013377 if (Mask[i] >= e)
David Greeneb736b5d2009-11-16 21:52:23 +000013378 NewMask.push_back(2*e);
13379 else
13380 NewMask.push_back(LHSMask[Mask[i]]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013381
David Greeneb736b5d2009-11-16 21:52:23 +000013382 // If the result mask is equal to the src shuffle or this
13383 // shuffle mask, do the replacement.
13384 if (NewMask == LHSMask || NewMask == Mask) {
13385 unsigned LHSInNElts =
13386 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13387 getNumElements();
13388 std::vector<Constant*> Elts;
13389 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13390 if (NewMask[i] >= LHSInNElts*2) {
13391 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13392 } else {
13393 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13394 NewMask[i]));
13395 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013396 }
David Greeneb736b5d2009-11-16 21:52:23 +000013397 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13398 LHSSVI->getOperand(1),
13399 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013400 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013401 }
13402 }
13403 }
13404
13405 return MadeChange ? &SVI : 0;
13406}
13407
13408
13409
13410
13411/// TryToSinkInstruction - Try to move the specified instruction from its
13412/// current block into the beginning of DestBlock, which can only happen if it's
13413/// safe to move the instruction past all of the instructions between it and the
13414/// end of its block.
13415static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13416 assert(I->hasOneUse() && "Invariants didn't hold!");
13417
13418 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000013419 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000013420 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013421
13422 // Do not sink alloca instructions out of the entry block.
13423 if (isa<AllocaInst>(I) && I->getParent() ==
13424 &DestBlock->getParent()->getEntryBlock())
13425 return false;
13426
13427 // We can only sink load instructions if there is nothing between the load and
13428 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000013429 if (I->mayReadFromMemory()) {
13430 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013431 Scan != E; ++Scan)
13432 if (Scan->mayWriteToMemory())
13433 return false;
13434 }
13435
Dan Gohman514277c2008-05-23 21:05:58 +000013436 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013437
Dale Johannesen24339f12009-03-03 01:09:07 +000013438 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013439 I->moveBefore(InsertPos);
13440 ++NumSunkInst;
13441 return true;
13442}
13443
13444
13445/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13446/// all reachable code to the worklist.
13447///
13448/// This has a couple of tricks to make the code faster and more powerful. In
13449/// particular, we constant fold and DCE instructions as we go, to avoid adding
13450/// them to the worklist (this significantly speeds up instcombine on code where
13451/// many instructions are dead or constant). Additionally, if we find a branch
13452/// whose condition is a known constant, we only visit the reachable successors.
13453///
Chris Lattnerc4269e52009-10-15 04:59:28 +000013454static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013455 SmallPtrSet<BasicBlock*, 64> &Visited,
13456 InstCombiner &IC,
13457 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000013458 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000013459 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013460 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000013461
13462 std::vector<Instruction*> InstrsForInstCombineWorklist;
13463 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013464
Chris Lattnerc4269e52009-10-15 04:59:28 +000013465 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13466
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013467 while (!Worklist.empty()) {
13468 BB = Worklist.back();
13469 Worklist.pop_back();
13470
13471 // We have now visited this block! If we've already been here, ignore it.
13472 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000013473
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013474 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13475 Instruction *Inst = BBI++;
13476
13477 // DCE instruction if trivially dead.
13478 if (isInstructionTriviallyDead(Inst)) {
13479 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000013480 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013481 Inst->eraseFromParent();
13482 continue;
13483 }
13484
13485 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000013486 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013487 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013488 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13489 << *Inst << '\n');
13490 Inst->replaceAllUsesWith(C);
13491 ++NumConstProp;
13492 Inst->eraseFromParent();
13493 continue;
13494 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000013495
13496
13497
13498 if (TD) {
13499 // See if we can constant fold its operands.
13500 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13501 i != e; ++i) {
13502 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13503 if (CE == 0) continue;
13504
13505 // If we already folded this constant, don't try again.
13506 if (!FoldedConstants.insert(CE))
13507 continue;
13508
Chris Lattner6070c012009-11-06 04:27:31 +000013509 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +000013510 if (NewC && NewC != CE) {
13511 *i = NewC;
13512 MadeIRChange = true;
13513 }
13514 }
13515 }
13516
Devang Patel794140c2008-11-19 18:56:50 +000013517
Chris Lattnerb5663c72009-10-12 03:58:40 +000013518 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013519 }
13520
13521 // Recursively visit successors. If this is a branch or switch on a
13522 // constant, only visit the reachable successor.
13523 TerminatorInst *TI = BB->getTerminator();
13524 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13525 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13526 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013527 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013528 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013529 continue;
13530 }
13531 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13532 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13533 // See if this is an explicit destination.
13534 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13535 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013536 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013537 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013538 continue;
13539 }
13540
13541 // Otherwise it is the default destination.
13542 Worklist.push_back(SI->getSuccessor(0));
13543 continue;
13544 }
13545 }
13546
13547 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13548 Worklist.push_back(TI->getSuccessor(i));
13549 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000013550
13551 // Once we've found all of the instructions to add to instcombine's worklist,
13552 // add them in reverse order. This way instcombine will visit from the top
13553 // of the function down. This jives well with the way that it adds all uses
13554 // of instructions to the worklist after doing a transformation, thus avoiding
13555 // some N^2 behavior in pathological cases.
13556 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13557 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000013558
13559 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013560}
13561
13562bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000013563 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013564
Daniel Dunbar005975c2009-07-25 00:23:56 +000013565 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13566 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013567
13568 {
13569 // Do a depth-first traversal of the function, populate the worklist with
13570 // the reachable instructions. Ignore blocks that are not reachable. Keep
13571 // track of which blocks we visit.
13572 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000013573 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013574
13575 // Do a quick scan over the function. If we find any blocks that are
13576 // unreachable, remove any instructions inside of them. This prevents
13577 // the instcombine code from having to deal with some bad special cases.
13578 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13579 if (!Visited.count(BB)) {
13580 Instruction *Term = BB->getTerminator();
13581 while (Term != BB->begin()) { // Remove instrs bottom-up
13582 BasicBlock::iterator I = Term; --I;
13583
Chris Lattner8a6411c2009-08-23 04:37:46 +000013584 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013585 // A debug intrinsic shouldn't force another iteration if we weren't
13586 // going to do one without it.
13587 if (!isa<DbgInfoIntrinsic>(I)) {
13588 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013589 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000013590 }
Devang Patele3829c82009-10-13 22:56:32 +000013591
Devang Patele3829c82009-10-13 22:56:32 +000013592 // If I is not void type then replaceAllUsesWith undef.
13593 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000013594 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000013595 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013596 I->eraseFromParent();
13597 }
13598 }
13599 }
13600
Chris Lattner5119c702009-08-30 05:55:36 +000013601 while (!Worklist.isEmpty()) {
13602 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013603 if (I == 0) continue; // skip null values.
13604
13605 // Check to see if we can DCE the instruction.
13606 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013607 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000013608 EraseInstFromFunction(*I);
13609 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013610 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013611 continue;
13612 }
13613
13614 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000013615 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013616 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013617 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013618
Chris Lattneree5839b2009-10-15 04:13:44 +000013619 // Add operands to the worklist.
13620 ReplaceInstUsesWith(*I, C);
13621 ++NumConstProp;
13622 EraseInstFromFunction(*I);
13623 MadeIRChange = true;
13624 continue;
13625 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013626
13627 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013628 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013629 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000013630 Instruction *UserInst = cast<Instruction>(I->use_back());
13631 BasicBlock *UserParent;
13632
13633 // Get the block the use occurs in.
13634 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13635 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13636 else
13637 UserParent = UserInst->getParent();
13638
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013639 if (UserParent != BB) {
13640 bool UserIsSuccessor = false;
13641 // See if the user is one of our successors.
13642 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13643 if (*SI == UserParent) {
13644 UserIsSuccessor = true;
13645 break;
13646 }
13647
13648 // If the user is one of our immediate successors, and if that successor
13649 // only has us as a predecessors (we'd have to split the critical edge
13650 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000013651 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013652 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000013653 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013654 }
13655 }
13656
Chris Lattnerc7694852009-08-30 07:44:24 +000013657 // Now that we have an instruction, try combining it to simplify it.
13658 Builder->SetInsertPoint(I->getParent(), I);
13659
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013660#ifndef NDEBUG
13661 std::string OrigI;
13662#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013663 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000013664 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13665
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013666 if (Instruction *Result = visit(*I)) {
13667 ++NumCombined;
13668 // Should we replace the old instruction with a new one?
13669 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013670 DEBUG(errs() << "IC: Old = " << *I << '\n'
13671 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013672
13673 // Everything uses the new instruction now.
13674 I->replaceAllUsesWith(Result);
13675
13676 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000013677 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000013678 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013679
13680 // Move the name to the new instruction first.
13681 Result->takeName(I);
13682
13683 // Insert the new instruction into the basic block...
13684 BasicBlock *InstParent = I->getParent();
13685 BasicBlock::iterator InsertPos = I;
13686
13687 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13688 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13689 ++InsertPos;
13690
13691 InstParent->getInstList().insert(InsertPos, Result);
13692
Chris Lattner3183fb62009-08-30 06:13:40 +000013693 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013694 } else {
13695#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013696 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13697 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013698#endif
13699
13700 // If the instruction was modified, it's possible that it is now dead.
13701 // if so, remove it.
13702 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000013703 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013704 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000013705 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000013706 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013707 }
13708 }
Chris Lattner21d79e22009-08-31 06:57:37 +000013709 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013710 }
13711 }
13712
Chris Lattner5119c702009-08-30 05:55:36 +000013713 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000013714 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013715}
13716
13717
13718bool InstCombiner::runOnFunction(Function &F) {
13719 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013720 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000013721 TD = getAnalysisIfAvailable<TargetData>();
13722
Chris Lattnerc7694852009-08-30 07:44:24 +000013723
13724 /// Builder - This is an IRBuilder that automatically inserts new
13725 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000013726 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000013727 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000013728 InstCombineIRInserter(Worklist));
13729 Builder = &TheBuilder;
13730
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013731 bool EverMadeChange = false;
13732
13733 // Iterate while there is work to do.
13734 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013735 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013736 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000013737
13738 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013739 return EverMadeChange;
13740}
13741
13742FunctionPass *llvm::createInstructionCombiningPass() {
13743 return new InstCombiner();
13744}