blob: 527d28e20974cd4b21d1aae7c6582abcfaf0f77c [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;
Chris Lattner08be8ff2010-01-01 22:42:29 +00002773 GetElementPtrInst *GEP = 0;
2774 ConstantExpr *CstGEP = 0;
Chris Lattner93e6ff92009-11-04 08:05:20 +00002775
Chris Lattner08be8ff2010-01-01 22:42:29 +00002776 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2777 // For now we require one side to be the base pointer "A" or a constant
2778 // expression derived from it.
2779 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2780 // (gep X, ...) - X
2781 if (LHSGEP->getOperand(0) == RHS) {
2782 GEP = LHSGEP;
2783 Swapped = false;
2784 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2785 // (gep X, ...) - (ce_gep X, ...)
2786 if (CE->getOpcode() == Instruction::GetElementPtr &&
2787 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2788 CstGEP = CE;
2789 GEP = LHSGEP;
2790 Swapped = false;
2791 }
2792 }
2793 }
2794
2795 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2796 // X - (gep X, ...)
2797 if (RHSGEP->getOperand(0) == LHS) {
2798 GEP = RHSGEP;
2799 Swapped = true;
2800 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2801 // (ce_gep X, ...) - (gep X, ...)
2802 if (CE->getOpcode() == Instruction::GetElementPtr &&
2803 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2804 CstGEP = CE;
2805 GEP = RHSGEP;
2806 Swapped = true;
2807 }
2808 }
2809 }
2810
2811 if (GEP == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00002812 return 0;
2813
Chris Lattner93e6ff92009-11-04 08:05:20 +00002814 // Emit the offset of the GEP and an intptr_t.
2815 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner08be8ff2010-01-01 22:42:29 +00002816
2817 // If we had a constant expression GEP on the other side offsetting the
2818 // pointer, subtract it from the offset we have.
2819 if (CstGEP) {
2820 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2821 Result = Builder->CreateSub(Result, CstOffset);
2822 }
2823
Chris Lattner93e6ff92009-11-04 08:05:20 +00002824
2825 // If we have p - gep(p, ...) then we have to negate the result.
2826 if (Swapped)
2827 Result = Builder->CreateNeg(Result, "diff.neg");
2828
2829 return Builder->CreateIntCast(Result, Ty, true);
2830}
2831
2832
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002833Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
Dan Gohman7ce405e2009-06-04 22:49:04 +00002836 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002838
Chris Lattnera54b96b2009-12-21 04:04:05 +00002839 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2840 if (Value *V = dyn_castNegVal(Op1)) {
2841 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2842 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2843 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2844 return Res;
2845 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846
2847 if (isa<UndefValue>(Op0))
2848 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2849 if (isa<UndefValue>(Op1))
2850 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner93e6ff92009-11-04 08:05:20 +00002851 if (I.getType() == Type::getInt1Ty(*Context))
2852 return BinaryOperator::CreateXor(Op0, Op1);
2853
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002854 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00002855 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002857 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858
2859 // C - ~X == X + (1+C)
2860 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002861 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002862 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863
2864 // -(X >>u 31) -> (X >>s 31)
2865 // -(X >>s 31) -> (X >>u 31)
2866 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002867 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 if (SI->getOpcode() == Instruction::LShr) {
2869 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2870 // Check to see if we are shifting out everything but the sign bit.
2871 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2872 SI->getType()->getPrimitiveSizeInBits()-1) {
2873 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002874 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002875 SI->getOperand(0), CU, SI->getName());
2876 }
2877 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002878 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2880 // Check to see if we are shifting out everything but the sign bit.
2881 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2882 SI->getType()->getPrimitiveSizeInBits()-1) {
2883 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002884 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885 SI->getOperand(0), CU, SI->getName());
2886 }
2887 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002888 }
2889 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890 }
2891
2892 // Try to fold constant sub into select arguments.
2893 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2894 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2895 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002896
2897 // C - zext(bool) -> bool ? C - 1 : C
2898 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002899 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002900 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002901 }
2902
2903 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002904 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002906 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002907 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002909 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002910 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2912 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2913 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002914 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002915 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916 }
2917 }
2918
2919 if (Op1I->hasOneUse()) {
2920 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2921 // is not used by anyone else...
2922 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002923 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002924 // Swap the two operands of the subexpr...
2925 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2926 Op1I->setOperand(0, IIOp1);
2927 Op1I->setOperand(1, IIOp0);
2928
2929 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002930 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931 }
2932
2933 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2934 //
2935 if (Op1I->getOpcode() == Instruction::And &&
2936 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2937 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2938
Chris Lattnerc7694852009-08-30 07:44:24 +00002939 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002940 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002941 }
2942
2943 // 0 - (X sdiv C) -> (X sdiv -C)
2944 if (Op1I->getOpcode() == Instruction::SDiv)
2945 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2946 if (CSI->isZero())
2947 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002948 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002949 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950
2951 // X - X*C --> X * (1-C)
2952 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002953 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002954 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002955 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002956 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002957 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002958 }
2959 }
2960 }
2961
Dan Gohman7ce405e2009-06-04 22:49:04 +00002962 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2963 if (Op0I->getOpcode() == Instruction::Add) {
2964 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2965 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2966 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2967 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2968 } else if (Op0I->getOpcode() == Instruction::Sub) {
2969 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002970 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002971 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002972 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002973 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974
2975 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002976 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002978 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979
2980 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002981 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002982 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002984
2985 // Optimize pointer differences into the same array into a size. Consider:
2986 // &A[10] - &A[0]: we should compile this to "10".
2987 if (TD) {
Chris Lattnerc49d68a2010-01-01 22:12:03 +00002988 Value *LHSOp, *RHSOp;
Chris Lattnerc93843f2010-01-01 22:29:12 +00002989 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2990 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattnerc49d68a2010-01-01 22:12:03 +00002991 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2992 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00002993
2994 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerc93843f2010-01-01 22:29:12 +00002995 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2996 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2997 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2998 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00002999 }
3000
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 return 0;
3002}
3003
Dan Gohman7ce405e2009-06-04 22:49:04 +00003004Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3006
3007 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003008 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003009 return BinaryOperator::CreateFAdd(Op0, V);
3010
3011 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3012 if (Op1I->getOpcode() == Instruction::FAdd) {
3013 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00003014 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00003015 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00003016 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00003017 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00003018 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00003019 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00003020 }
3021
3022 return 0;
3023}
3024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3026/// comparison only checks the sign bit. If it only checks the sign bit, set
3027/// TrueIfSigned if the result of the comparison is true when the input value is
3028/// signed.
3029static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3030 bool &TrueIfSigned) {
3031 switch (pred) {
3032 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3033 TrueIfSigned = true;
3034 return RHS->isZero();
3035 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3036 TrueIfSigned = true;
3037 return RHS->isAllOnesValue();
3038 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3039 TrueIfSigned = false;
3040 return RHS->isAllOnesValue();
3041 case ICmpInst::ICMP_UGT:
3042 // True if LHS u> RHS and RHS == high-bit-mask - 1
3043 TrueIfSigned = true;
3044 return RHS->getValue() ==
3045 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3046 case ICmpInst::ICMP_UGE:
3047 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3048 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00003049 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003050 default:
3051 return false;
3052 }
3053}
3054
3055Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3056 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058
Chris Lattner3508c5c2009-10-11 21:36:10 +00003059 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00003060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003061
Chris Lattner6438c582009-10-11 07:53:15 +00003062 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003063 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003065
3066 // ((X << C1)*C2) == (X * (C2 << C1))
3067 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3068 if (SI->getOpcode() == Instruction::Shl)
3069 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003070 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003071 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072
3073 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00003074 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 if (CI->equalsInt(1)) // X * 1 == X
3076 return ReplaceInstUsesWith(I, Op0);
3077 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00003078 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003079
3080 const APInt& Val = cast<ConstantInt>(CI)->getValue();
3081 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00003082 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003083 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003084 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003085 } else if (isa<VectorType>(Op1C->getType())) {
3086 if (Op1C->isNullValue())
3087 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00003088
Chris Lattner3508c5c2009-10-11 21:36:10 +00003089 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00003090 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00003091 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00003092
3093 // As above, vector X*splat(1.0) -> X in all defined cases.
3094 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00003095 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3096 if (CI->equalsInt(1))
3097 return ReplaceInstUsesWith(I, Op0);
3098 }
3099 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100 }
3101
3102 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3103 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003104 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003105 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003106 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3107 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003108 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109
3110 }
3111
3112 // Try to fold constant mul into select arguments.
3113 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3115 return R;
3116
3117 if (isa<PHINode>(Op0))
3118 if (Instruction *NV = FoldOpIntoPhi(I))
3119 return NV;
3120 }
3121
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003122 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003123 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00003124 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003125
Nick Lewycky1c246402008-11-21 07:33:58 +00003126 // (X / Y) * Y = X - (X % Y)
3127 // (X / Y) * -Y = (X % Y) - X
3128 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003129 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00003130 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3131 if (!BO ||
3132 (BO->getOpcode() != Instruction::UDiv &&
3133 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003134 Op1C = Op0;
3135 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00003136 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003137 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00003138 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003139 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00003140 (BO->getOpcode() == Instruction::UDiv ||
3141 BO->getOpcode() == Instruction::SDiv)) {
3142 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3143
Dan Gohman07878902009-08-12 16:33:09 +00003144 // If the division is exact, X % Y is zero.
3145 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3146 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003147 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00003148 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003149 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00003150 }
3151
Chris Lattnerc7694852009-08-30 07:44:24 +00003152 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00003153 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00003154 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003155 else
Chris Lattnerc7694852009-08-30 07:44:24 +00003156 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003157 Rem->takeName(BO);
3158
Chris Lattner3508c5c2009-10-11 21:36:10 +00003159 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00003160 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00003161 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003162 }
3163 }
3164
Chris Lattner6438c582009-10-11 07:53:15 +00003165 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00003166 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003167 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003168
Chris Lattner6438c582009-10-11 07:53:15 +00003169 // X*(1 << Y) --> X << Y
3170 // (1 << Y)*X --> X << Y
3171 {
3172 Value *Y;
3173 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003174 return BinaryOperator::CreateShl(Op1, Y);
3175 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00003176 return BinaryOperator::CreateShl(Op0, Y);
3177 }
3178
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179 // If one of the operands of the multiply is a cast from a boolean value, then
3180 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00003181 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3182 if (!isa<VectorType>(I.getType())) {
3183 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00003184 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00003185
Chris Lattner4ca76f72009-10-11 21:29:45 +00003186 Value *BoolCast = 0, *OtherOp = 0;
3187 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003188 BoolCast = Op0, OtherOp = Op1;
3189 else if (MaskedValueIsZero(Op1, Negative2))
3190 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00003191
Chris Lattner291872e2009-10-11 21:22:21 +00003192 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00003193 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3194 BoolCast, "tmp");
3195 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196 }
3197 }
3198
3199 return Changed ? &I : 0;
3200}
3201
Dan Gohman7ce405e2009-06-04 22:49:04 +00003202Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3203 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00003205
3206 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00003207 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3208 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003209 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3210 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3211 if (Op1F->isExactlyValue(1.0))
3212 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00003213 } else if (isa<VectorType>(Op1C->getType())) {
3214 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003215 // As above, vector X*splat(1.0) -> X in all defined cases.
3216 if (Constant *Splat = Op1V->getSplatValue()) {
3217 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3218 if (F->isExactlyValue(1.0))
3219 return ReplaceInstUsesWith(I, Op0);
3220 }
3221 }
3222 }
3223
3224 // Try to fold constant mul into select arguments.
3225 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3226 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3227 return R;
3228
3229 if (isa<PHINode>(Op0))
3230 if (Instruction *NV = FoldOpIntoPhi(I))
3231 return NV;
3232 }
3233
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003234 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003235 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003236 return BinaryOperator::CreateFMul(Op0v, Op1v);
3237
3238 return Changed ? &I : 0;
3239}
3240
Chris Lattner76972db2008-07-14 00:15:52 +00003241/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3242/// instruction.
3243bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3244 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3245
3246 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3247 int NonNullOperand = -1;
3248 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3249 if (ST->isNullValue())
3250 NonNullOperand = 2;
3251 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3252 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3253 if (ST->isNullValue())
3254 NonNullOperand = 1;
3255
3256 if (NonNullOperand == -1)
3257 return false;
3258
3259 Value *SelectCond = SI->getOperand(0);
3260
3261 // Change the div/rem to use 'Y' instead of the select.
3262 I.setOperand(1, SI->getOperand(NonNullOperand));
3263
3264 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3265 // problem. However, the select, or the condition of the select may have
3266 // multiple uses. Based on our knowledge that the operand must be non-zero,
3267 // propagate the known value for the select into other uses of it, and
3268 // propagate a known value of the condition into its other users.
3269
3270 // If the select and condition only have a single use, don't bother with this,
3271 // early exit.
3272 if (SI->use_empty() && SelectCond->hasOneUse())
3273 return true;
3274
3275 // Scan the current block backward, looking for other uses of SI.
3276 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3277
3278 while (BBI != BBFront) {
3279 --BBI;
3280 // If we found a call to a function, we can't assume it will return, so
3281 // information from below it cannot be propagated above it.
3282 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3283 break;
3284
3285 // Replace uses of the select or its condition with the known values.
3286 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3287 I != E; ++I) {
3288 if (*I == SI) {
3289 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00003290 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003291 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00003292 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3293 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00003294 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003295 }
3296 }
3297
3298 // If we past the instruction, quit looking for it.
3299 if (&*BBI == SI)
3300 SI = 0;
3301 if (&*BBI == SelectCond)
3302 SelectCond = 0;
3303
3304 // If we ran out of things to eliminate, break out of the loop.
3305 if (SelectCond == 0 && SI == 0)
3306 break;
3307
3308 }
3309 return true;
3310}
3311
3312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003313/// This function implements the transforms on div instructions that work
3314/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3315/// used by the visitors to those instructions.
3316/// @brief Transforms common to all three div instructions
3317Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3318 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3319
Chris Lattner653ef3c2008-02-19 06:12:18 +00003320 // undef / X -> 0 for integer.
3321 // undef / X -> undef for FP (the undef could be a snan).
3322 if (isa<UndefValue>(Op0)) {
3323 if (Op0->getType()->isFPOrFPVector())
3324 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00003325 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003326 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327
3328 // X / undef -> undef
3329 if (isa<UndefValue>(Op1))
3330 return ReplaceInstUsesWith(I, Op1);
3331
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332 return 0;
3333}
3334
3335/// This function implements the transforms common to both integer division
3336/// instructions (udiv and sdiv). It is called by the visitors to those integer
3337/// division instructions.
3338/// @brief Common integer divide transforms
3339Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3340 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3341
Chris Lattnercefb36c2008-05-16 02:59:42 +00003342 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003343 if (Op0 == Op1) {
3344 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003345 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003346 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003347 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003348 }
3349
Owen Andersoneacb44d2009-07-24 23:12:02 +00003350 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003351 return ReplaceInstUsesWith(I, CI);
3352 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003353
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003354 if (Instruction *Common = commonDivTransforms(I))
3355 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003356
3357 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3358 // This does not apply for fdiv.
3359 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3360 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003361
3362 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3363 // div X, 1 == X
3364 if (RHS->equalsInt(1))
3365 return ReplaceInstUsesWith(I, Op0);
3366
3367 // (X / C1) / C2 -> X / (C1*C2)
3368 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3369 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3370 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003371 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003372 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003374 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003375 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003376 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 }
3378
3379 if (!RHS->isZero()) { // avoid X udiv 0
3380 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3381 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3382 return R;
3383 if (isa<PHINode>(Op0))
3384 if (Instruction *NV = FoldOpIntoPhi(I))
3385 return NV;
3386 }
3387 }
3388
3389 // 0 / X == 0, we don't need to preserve faults!
3390 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3391 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003392 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003394 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003395 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003396 return ReplaceInstUsesWith(I, Op0);
3397
Nick Lewycky94418732008-11-27 20:21:08 +00003398 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3399 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3400 // div X, 1 == X
3401 if (X->isOne())
3402 return ReplaceInstUsesWith(I, Op0);
3403 }
3404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 return 0;
3406}
3407
3408Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3410
3411 // Handle the integer div common cases
3412 if (Instruction *Common = commonIDivTransforms(I))
3413 return Common;
3414
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003415 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003416 // X udiv C^2 -> X >> C
3417 // Check to see if this is an unsigned division with an exact power of 2,
3418 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003420 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003421 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003422
3423 // X udiv C, where C >= signbit
3424 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003425 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003426 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003427 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003428 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429 }
3430
3431 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3432 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3433 if (RHSI->getOpcode() == Instruction::Shl &&
3434 isa<ConstantInt>(RHSI->getOperand(0))) {
3435 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3436 if (C1.isPowerOf2()) {
3437 Value *N = RHSI->getOperand(1);
3438 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003439 if (uint32_t C2 = C1.logBase2())
3440 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003441 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 }
3443 }
3444 }
3445
3446 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3447 // where C1&C2 are powers of two.
3448 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3449 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3450 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3451 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3452 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3453 // Compute the shift amounts
3454 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3455 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003456 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003457 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458
3459 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003460 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003461 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003462
3463 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003464 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003465 }
3466 }
3467 return 0;
3468}
3469
3470Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3472
3473 // Handle the integer div common cases
3474 if (Instruction *Common = commonIDivTransforms(I))
3475 return Common;
3476
3477 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3478 // sdiv X, -1 == -X
3479 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003480 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003481
Dan Gohman07878902009-08-12 16:33:09 +00003482 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003483 if (cast<SDivOperator>(&I)->isExact() &&
3484 RHS->getValue().isNonNegative() &&
3485 RHS->getValue().isPowerOf2()) {
3486 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3487 RHS->getValue().exactLogBase2());
3488 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3489 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003490
3491 // -X/C --> X/-C provided the negation doesn't overflow.
3492 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3493 if (isa<Constant>(Sub->getOperand(0)) &&
3494 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003495 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003496 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3497 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498 }
3499
3500 // If the sign bits of both operands are zero (i.e. we can prove they are
3501 // unsigned inputs), turn this into a udiv.
3502 if (I.getType()->isInteger()) {
3503 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003504 if (MaskedValueIsZero(Op0, Mask)) {
3505 if (MaskedValueIsZero(Op1, Mask)) {
3506 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3507 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3508 }
3509 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003510 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003511 ShiftedInt->getValue().isPowerOf2()) {
3512 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3513 // Safe because the only negative value (1 << Y) can take on is
3514 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3515 // the sign bit set.
3516 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3517 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520
3521 return 0;
3522}
3523
3524Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3525 return commonDivTransforms(I);
3526}
3527
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003528/// This function implements the transforms on rem instructions that work
3529/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3530/// is used by the visitors to those instructions.
3531/// @brief Transforms common to all three rem instructions
3532Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3534
Chris Lattner653ef3c2008-02-19 06:12:18 +00003535 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3536 if (I.getType()->isFPOrFPVector())
3537 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003538 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003539 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003540 if (isa<UndefValue>(Op1))
3541 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3542
3543 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003544 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3545 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546
3547 return 0;
3548}
3549
3550/// This function implements the transforms common to both integer remainder
3551/// instructions (urem and srem). It is called by the visitors to those integer
3552/// remainder instructions.
3553/// @brief Common integer remainder transforms
3554Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3555 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3556
3557 if (Instruction *common = commonRemTransforms(I))
3558 return common;
3559
Dale Johannesena51f7372009-01-21 00:35:19 +00003560 // 0 % X == 0 for integer, we don't need to preserve faults!
3561 if (Constant *LHS = dyn_cast<Constant>(Op0))
3562 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003563 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003564
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3566 // X % 0 == undef, we don't need to preserve faults!
3567 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003568 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003569
3570 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572
3573 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3574 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3575 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3576 return R;
3577 } else if (isa<PHINode>(Op0I)) {
3578 if (Instruction *NV = FoldOpIntoPhi(I))
3579 return NV;
3580 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003581
3582 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003583 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003584 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003585 }
3586 }
3587
3588 return 0;
3589}
3590
3591Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3593
3594 if (Instruction *common = commonIRemTransforms(I))
3595 return common;
3596
3597 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3598 // X urem C^2 -> X and C
3599 // Check to see if this is an unsigned remainder with an exact power of 2,
3600 // if so, convert to a bitwise and.
3601 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3602 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003603 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604 }
3605
3606 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3607 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3608 if (RHSI->getOpcode() == Instruction::Shl &&
3609 isa<ConstantInt>(RHSI->getOperand(0))) {
3610 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003611 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003612 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003613 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 }
3615 }
3616 }
3617
3618 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3619 // where C1&C2 are powers of two.
3620 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3621 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3622 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3623 // STO == 0 and SFO == 0 handled above.
3624 if ((STO->getValue().isPowerOf2()) &&
3625 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003626 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3627 SI->getName()+".t");
3628 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3629 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003630 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003631 }
3632 }
3633 }
3634
3635 return 0;
3636}
3637
3638Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3639 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3640
Dan Gohmandb3dd962007-11-05 23:16:33 +00003641 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003642 if (Instruction *Common = commonIRemTransforms(I))
3643 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003645 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003646 if (!isa<Constant>(RHSNeg) ||
3647 (isa<ConstantInt>(RHSNeg) &&
3648 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003650 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003651 I.setOperand(1, RHSNeg);
3652 return &I;
3653 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003654
Dan Gohmandb3dd962007-11-05 23:16:33 +00003655 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003656 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003657 if (I.getType()->isInteger()) {
3658 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3659 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3660 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003661 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663 }
3664
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003665 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003666 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3667 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003668
Nick Lewyckyfd746832008-12-20 16:48:00 +00003669 bool hasNegative = false;
3670 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3671 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3672 if (RHS->getValue().isNegative())
3673 hasNegative = true;
3674
3675 if (hasNegative) {
3676 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003677 for (unsigned i = 0; i != VWidth; ++i) {
3678 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3679 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003680 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003681 else
3682 Elts[i] = RHS;
3683 }
3684 }
3685
Owen Anderson2f422e02009-07-28 21:19:26 +00003686 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003687 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003688 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003689 I.setOperand(1, NewRHSV);
3690 return &I;
3691 }
3692 }
3693 }
3694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695 return 0;
3696}
3697
3698Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3699 return commonRemTransforms(I);
3700}
3701
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702// isOneBitSet - Return true if there is exactly one bit set in the specified
3703// constant.
3704static bool isOneBitSet(const ConstantInt *CI) {
3705 return CI->getValue().isPowerOf2();
3706}
3707
3708// isHighOnes - Return true if the constant is of the form 1+0+.
3709// This is the same as lowones(~X).
3710static bool isHighOnes(const ConstantInt *CI) {
3711 return (~CI->getValue() + 1).isPowerOf2();
3712}
3713
3714/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3715/// are carefully arranged to allow folding of expressions such as:
3716///
3717/// (A < B) | (A > B) --> (A != B)
3718///
3719/// Note that this is only valid if the first and second predicates have the
3720/// same sign. Is illegal to do: (A u< B) | (A s> B)
3721///
3722/// Three bits are used to represent the condition, as follows:
3723/// 0 A > B
3724/// 1 A == B
3725/// 2 A < B
3726///
3727/// <=> Value Definition
3728/// 000 0 Always false
3729/// 001 1 A > B
3730/// 010 2 A == B
3731/// 011 3 A >= B
3732/// 100 4 A < B
3733/// 101 5 A != B
3734/// 110 6 A <= B
3735/// 111 7 Always true
3736///
3737static unsigned getICmpCode(const ICmpInst *ICI) {
3738 switch (ICI->getPredicate()) {
3739 // False -> 0
3740 case ICmpInst::ICMP_UGT: return 1; // 001
3741 case ICmpInst::ICMP_SGT: return 1; // 001
3742 case ICmpInst::ICMP_EQ: return 2; // 010
3743 case ICmpInst::ICMP_UGE: return 3; // 011
3744 case ICmpInst::ICMP_SGE: return 3; // 011
3745 case ICmpInst::ICMP_ULT: return 4; // 100
3746 case ICmpInst::ICMP_SLT: return 4; // 100
3747 case ICmpInst::ICMP_NE: return 5; // 101
3748 case ICmpInst::ICMP_ULE: return 6; // 110
3749 case ICmpInst::ICMP_SLE: return 6; // 110
3750 // True -> 7
3751 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003752 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003753 return 0;
3754 }
3755}
3756
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003757/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3758/// predicate into a three bit mask. It also returns whether it is an ordered
3759/// predicate by reference.
3760static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3761 isOrdered = false;
3762 switch (CC) {
3763 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3764 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003765 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3766 case FCmpInst::FCMP_UGT: return 1; // 001
3767 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3768 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003769 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3770 case FCmpInst::FCMP_UGE: return 3; // 011
3771 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3772 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003773 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3774 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003775 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3776 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003777 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003778 default:
3779 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003780 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003781 return 0;
3782 }
3783}
3784
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003785/// getICmpValue - This is the complement of getICmpCode, which turns an
3786/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003787/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003788/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003789static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003790 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003791 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003792 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003793 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003794 case 1:
3795 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003796 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003798 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3799 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003800 case 3:
3801 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003802 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003804 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 case 4:
3806 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003807 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003808 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003809 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3810 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003811 case 6:
3812 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003813 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003814 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003815 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003816 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003817 }
3818}
3819
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003820/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3821/// opcode and two operands into either a FCmp instruction. isordered is passed
3822/// in to determine which kind of predicate to use in the new fcmp instruction.
3823static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003824 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003825 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003826 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003827 case 0:
3828 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003829 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003830 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003831 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003832 case 1:
3833 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003834 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003835 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003836 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003837 case 2:
3838 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003839 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003840 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003841 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003842 case 3:
3843 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003844 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003845 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003846 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003847 case 4:
3848 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003849 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003850 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003851 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003852 case 5:
3853 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003854 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003855 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003856 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003857 case 6:
3858 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003859 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003860 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003861 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003862 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003863 }
3864}
3865
Chris Lattner2972b822008-11-16 04:55:20 +00003866/// PredicatesFoldable - Return true if both predicates match sign or if at
3867/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003868static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003869 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3870 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3871 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003872}
3873
3874namespace {
3875// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3876struct FoldICmpLogical {
3877 InstCombiner &IC;
3878 Value *LHS, *RHS;
3879 ICmpInst::Predicate pred;
3880 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3881 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3882 pred(ICI->getPredicate()) {}
3883 bool shouldApply(Value *V) const {
3884 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3885 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003886 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3887 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003888 return false;
3889 }
3890 Instruction *apply(Instruction &Log) const {
3891 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3892 if (ICI->getOperand(0) != LHS) {
3893 assert(ICI->getOperand(1) == LHS);
3894 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3895 }
3896
3897 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3898 unsigned LHSCode = getICmpCode(ICI);
3899 unsigned RHSCode = getICmpCode(RHSICI);
3900 unsigned Code;
3901 switch (Log.getOpcode()) {
3902 case Instruction::And: Code = LHSCode & RHSCode; break;
3903 case Instruction::Or: Code = LHSCode | RHSCode; break;
3904 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003905 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003906 }
3907
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003908 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003909 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003910 if (Instruction *I = dyn_cast<Instruction>(RV))
3911 return I;
3912 // Otherwise, it's a constant boolean value...
3913 return IC.ReplaceInstUsesWith(Log, RV);
3914 }
3915};
3916} // end anonymous namespace
3917
3918// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3919// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3920// guaranteed to be a binary operator.
3921Instruction *InstCombiner::OptAndOp(Instruction *Op,
3922 ConstantInt *OpRHS,
3923 ConstantInt *AndRHS,
3924 BinaryOperator &TheAnd) {
3925 Value *X = Op->getOperand(0);
3926 Constant *Together = 0;
3927 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003928 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003929
3930 switch (Op->getOpcode()) {
3931 case Instruction::Xor:
3932 if (Op->hasOneUse()) {
3933 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003934 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003935 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003936 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 }
3938 break;
3939 case Instruction::Or:
3940 if (Together == AndRHS) // (X | C) & C --> C
3941 return ReplaceInstUsesWith(TheAnd, AndRHS);
3942
3943 if (Op->hasOneUse() && Together != OpRHS) {
3944 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003945 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003946 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003947 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003948 }
3949 break;
3950 case Instruction::Add:
3951 if (Op->hasOneUse()) {
3952 // Adding a one to a single bit bit-field should be turned into an XOR
3953 // of the bit. First thing to check is to see if this AND is with a
3954 // single bit constant.
3955 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3956
3957 // If there is only one bit set...
3958 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3959 // Ok, at this point, we know that we are masking the result of the
3960 // ADD down to exactly one bit. If the constant we are adding has
3961 // no bits set below this bit, then we can eliminate the ADD.
3962 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3963
3964 // Check to see if any bits below the one bit set in AndRHSV are set.
3965 if ((AddRHS & (AndRHSV-1)) == 0) {
3966 // If not, the only thing that can effect the output of the AND is
3967 // the bit specified by AndRHSV. If that bit is set, the effect of
3968 // the XOR is to toggle the bit. If it is clear, then the ADD has
3969 // no effect.
3970 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3971 TheAnd.setOperand(0, X);
3972 return &TheAnd;
3973 } else {
3974 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003975 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003976 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003977 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003978 }
3979 }
3980 }
3981 }
3982 break;
3983
3984 case Instruction::Shl: {
3985 // We know that the AND will not produce any of the bits shifted in, so if
3986 // the anded constant includes them, clear them now!
3987 //
3988 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3989 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3990 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003991 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003992
3993 if (CI->getValue() == ShlMask) {
3994 // Masking out bits that the shift already masks
3995 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3996 } else if (CI != AndRHS) { // Reducing bits set in and.
3997 TheAnd.setOperand(1, CI);
3998 return &TheAnd;
3999 }
4000 break;
4001 }
4002 case Instruction::LShr:
4003 {
4004 // We know that the AND will not produce any of the bits shifted in, so if
4005 // the anded constant includes them, clear them now! This only applies to
4006 // unsigned shifts, because a signed shr may bring in set bits!
4007 //
4008 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4009 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4010 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004011 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004012
4013 if (CI->getValue() == ShrMask) {
4014 // Masking out bits that the shift already masks.
4015 return ReplaceInstUsesWith(TheAnd, Op);
4016 } else if (CI != AndRHS) {
4017 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
4018 return &TheAnd;
4019 }
4020 break;
4021 }
4022 case Instruction::AShr:
4023 // Signed shr.
4024 // See if this is shifting in some sign extension, then masking it out
4025 // with an and.
4026 if (Op->hasOneUse()) {
4027 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4028 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4029 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004030 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004031 if (C == AndRHS) { // Masking out bits shifted in.
4032 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
4033 // Make the argument unsigned.
4034 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00004035 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004036 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004037 }
4038 }
4039 break;
4040 }
4041 return 0;
4042}
4043
4044
4045/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4046/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
4047/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4048/// whether to treat the V, Lo and HI as signed or not. IB is the location to
4049/// insert new instructions.
4050Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
4051 bool isSigned, bool Inside,
4052 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00004053 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004054 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
4055 "Lo is not <= Hi in range emission code!");
4056
4057 if (Inside) {
4058 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00004059 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004060
4061 // V >= Min && V < Hi --> V < Hi
4062 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4063 ICmpInst::Predicate pred = (isSigned ?
4064 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00004065 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004066 }
4067
4068 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00004069 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00004070 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00004071 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00004072 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004073 }
4074
4075 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00004076 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004077
4078 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004079 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004080 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4081 ICmpInst::Predicate pred = (isSigned ?
4082 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00004083 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 }
4085
4086 // Emit V-Lo >u Hi-1-Lo
4087 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00004088 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00004089 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00004090 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00004091 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092}
4093
4094// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4095// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4096// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4097// not, since all 1s are not contiguous.
4098static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4099 const APInt& V = Val->getValue();
4100 uint32_t BitWidth = Val->getType()->getBitWidth();
4101 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4102
4103 // look for the first zero bit after the run of ones
4104 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4105 // look for the first non-zero bit
4106 ME = V.getActiveBits();
4107 return true;
4108}
4109
4110/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4111/// where isSub determines whether the operator is a sub. If we can fold one of
4112/// the following xforms:
4113///
4114/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4115/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4116/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4117///
4118/// return (A +/- B).
4119///
4120Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4121 ConstantInt *Mask, bool isSub,
4122 Instruction &I) {
4123 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4124 if (!LHSI || LHSI->getNumOperands() != 2 ||
4125 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4126
4127 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4128
4129 switch (LHSI->getOpcode()) {
4130 default: return 0;
4131 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00004132 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004133 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4134 if ((Mask->getValue().countLeadingZeros() +
4135 Mask->getValue().countPopulation()) ==
4136 Mask->getValue().getBitWidth())
4137 break;
4138
4139 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4140 // part, we don't need any explicit masks to take them out of A. If that
4141 // is all N is, ignore it.
4142 uint32_t MB = 0, ME = 0;
4143 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4144 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4145 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4146 if (MaskedValueIsZero(RHS, Mask))
4147 break;
4148 }
4149 }
4150 return 0;
4151 case Instruction::Or:
4152 case Instruction::Xor:
4153 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4154 if ((Mask->getValue().countLeadingZeros() +
4155 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00004156 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 break;
4158 return 0;
4159 }
4160
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004161 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00004162 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4163 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004164}
4165
Chris Lattner0631ea72008-11-16 05:06:21 +00004166/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4167Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4168 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner163e6ab2009-11-29 00:51:17 +00004169 // (icmp eq A, null) & (icmp eq B, null) -->
4170 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4171 if (TD &&
4172 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4173 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4174 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4175 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4176 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4177 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4178 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4179 Value *NewOr = Builder->CreateOr(A, B);
4180 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4181 Constant::getNullValue(IntPtrTy));
4182 }
4183
Chris Lattnerf3803482008-11-16 05:10:52 +00004184 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00004185 ConstantInt *LHSCst, *RHSCst;
4186 ICmpInst::Predicate LHSCC, RHSCC;
4187
Chris Lattnerf3803482008-11-16 05:10:52 +00004188 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004189 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004190 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004191 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004192 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00004193 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00004194
Chris Lattner163e6ab2009-11-29 00:51:17 +00004195 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4196 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4197 // where C is a power of 2
4198 if (LHSCC == ICmpInst::ICMP_ULT &&
4199 LHSCst->getValue().isPowerOf2()) {
4200 Value *NewOr = Builder->CreateOr(Val, Val2);
4201 return new ICmpInst(LHSCC, NewOr, LHSCst);
4202 }
4203
4204 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4205 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4206 Value *NewOr = Builder->CreateOr(Val, Val2);
4207 return new ICmpInst(LHSCC, NewOr, LHSCst);
4208 }
Chris Lattnerf3803482008-11-16 05:10:52 +00004209 }
4210
4211 // From here on, we only handle:
4212 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4213 if (Val != Val2) return 0;
4214
Chris Lattner0631ea72008-11-16 05:06:21 +00004215 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4216 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4217 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4218 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4219 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4220 return 0;
4221
4222 // We can't fold (ugt x, C) & (sgt x, C2).
4223 if (!PredicatesFoldable(LHSCC, RHSCC))
4224 return 0;
4225
4226 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00004227 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004228 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00004229 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004230 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00004231 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00004232 else
Chris Lattner665298f2008-11-16 05:14:43 +00004233 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4234
4235 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00004236 std::swap(LHS, RHS);
4237 std::swap(LHSCst, RHSCst);
4238 std::swap(LHSCC, RHSCC);
4239 }
4240
4241 // At this point, we know we have have two icmp instructions
4242 // comparing a value against two constants and and'ing the result
4243 // together. Because of the above check, we know that we only have
4244 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4245 // (from the FoldICmpLogical check above), that the two constants
4246 // are not equal and that the larger constant is on the RHS
4247 assert(LHSCst != RHSCst && "Compares not folded above?");
4248
4249 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004250 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004251 case ICmpInst::ICMP_EQ:
4252 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004253 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004254 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4255 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4256 case ICmpInst::ICMP_SGT: // (X == 13 & X > 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_NE: // (X == 13 & X != 15) -> X == 13
4259 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4260 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4261 return ReplaceInstUsesWith(I, LHS);
4262 }
4263 case ICmpInst::ICMP_NE:
4264 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004265 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004266 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004267 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004268 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004269 break; // (X != 13 & X u< 15) -> no change
4270 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004271 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004272 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004273 break; // (X != 13 & X s< 15) -> no change
4274 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4275 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4276 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4277 return ReplaceInstUsesWith(I, RHS);
4278 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004279 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00004280 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004281 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00004282 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004283 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00004284 }
4285 break; // (X != 13 & X != 15) -> no change
4286 }
4287 break;
4288 case ICmpInst::ICMP_ULT:
4289 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004290 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004291 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4292 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004293 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004294 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4295 break;
4296 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4297 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4298 return ReplaceInstUsesWith(I, LHS);
4299 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4300 break;
4301 }
4302 break;
4303 case ICmpInst::ICMP_SLT:
4304 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004305 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004306 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4307 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004308 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004309 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4310 break;
4311 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4312 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4313 return ReplaceInstUsesWith(I, LHS);
4314 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4315 break;
4316 }
4317 break;
4318 case ICmpInst::ICMP_UGT:
4319 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004320 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004321 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4322 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4323 return ReplaceInstUsesWith(I, RHS);
4324 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4325 break;
4326 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004327 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004328 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004329 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004330 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004331 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004332 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004333 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4334 break;
4335 }
4336 break;
4337 case ICmpInst::ICMP_SGT:
4338 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004339 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004340 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4341 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4342 return ReplaceInstUsesWith(I, RHS);
4343 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4344 break;
4345 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004346 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004347 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004348 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004349 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004350 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004351 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004352 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4353 break;
4354 }
4355 break;
4356 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004357
4358 return 0;
4359}
4360
Chris Lattner93a359a2009-07-23 05:14:02 +00004361Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4362 FCmpInst *RHS) {
4363
4364 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4365 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4366 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4367 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4368 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4369 // If either of the constants are nans, then the whole thing returns
4370 // false.
4371 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004372 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004373 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004374 LHS->getOperand(0), RHS->getOperand(0));
4375 }
Chris Lattnercf373552009-07-23 05:32:17 +00004376
4377 // Handle vector zeros. This occurs because the canonical form of
4378 // "fcmp ord x,x" is "fcmp ord x, 0".
4379 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4380 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004381 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004382 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004383 return 0;
4384 }
4385
4386 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4387 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4388 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4389
4390
4391 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4392 // Swap RHS operands to match LHS.
4393 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4394 std::swap(Op1LHS, Op1RHS);
4395 }
4396
4397 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4398 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4399 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004400 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004401
4402 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004403 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004404 if (Op0CC == FCmpInst::FCMP_TRUE)
4405 return ReplaceInstUsesWith(I, RHS);
4406 if (Op1CC == FCmpInst::FCMP_TRUE)
4407 return ReplaceInstUsesWith(I, LHS);
4408
4409 bool Op0Ordered;
4410 bool Op1Ordered;
4411 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4412 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4413 if (Op1Pred == 0) {
4414 std::swap(LHS, RHS);
4415 std::swap(Op0Pred, Op1Pred);
4416 std::swap(Op0Ordered, Op1Ordered);
4417 }
4418 if (Op0Pred == 0) {
4419 // uno && ueq -> uno && (uno || eq) -> ueq
4420 // ord && olt -> ord && (ord && lt) -> olt
4421 if (Op0Ordered == Op1Ordered)
4422 return ReplaceInstUsesWith(I, RHS);
4423
4424 // uno && oeq -> uno && (ord && eq) -> false
4425 // uno && ord -> false
4426 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004427 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004428 // ord && ueq -> ord && (uno || eq) -> oeq
4429 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4430 Op0LHS, Op0RHS, Context));
4431 }
4432 }
4433
4434 return 0;
4435}
4436
Chris Lattner0631ea72008-11-16 05:06:21 +00004437
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004438Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4439 bool Changed = SimplifyCommutative(I);
4440 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4441
Chris Lattnera3e46f62009-11-10 00:55:12 +00004442 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4443 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004444
4445 // See if we can simplify any instructions used by the instruction whose sole
4446 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004447 if (SimplifyDemandedInstructionBits(I))
4448 return &I;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004449
Dan Gohman8fd520a2009-06-15 22:12:54 +00004450
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004451 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004452 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004453 APInt NotAndRHS(~AndRHSMask);
4454
4455 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004456 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004457 Value *Op0LHS = Op0I->getOperand(0);
4458 Value *Op0RHS = Op0I->getOperand(1);
4459 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004460 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004461 case Instruction::Xor:
4462 case Instruction::Or:
4463 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004464 if (!Op0I->hasOneUse()) break;
4465
4466 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4467 // Not masking anything out for the LHS, move to RHS.
4468 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4469 Op0RHS->getName()+".masked");
4470 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4471 }
4472 if (!isa<Constant>(Op0RHS) &&
4473 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4474 // Not masking anything out for the RHS, move to LHS.
4475 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4476 Op0LHS->getName()+".masked");
4477 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004478 }
4479
4480 break;
4481 case Instruction::Add:
4482 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4483 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4484 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4485 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004486 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004487 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004488 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004489 break;
4490
4491 case Instruction::Sub:
4492 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4493 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4494 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4495 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004496 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004497
Nick Lewyckya349ba42008-07-10 05:51:40 +00004498 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4499 // has 1's for all bits that the subtraction with A might affect.
4500 if (Op0I->hasOneUse()) {
4501 uint32_t BitWidth = AndRHSMask.getBitWidth();
4502 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4503 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4504
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004505 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004506 if (!(A && A->isZero()) && // avoid infinite recursion.
4507 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004508 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004509 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4510 }
4511 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004513
4514 case Instruction::Shl:
4515 case Instruction::LShr:
4516 // (1 << x) & 1 --> zext(x == 0)
4517 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004518 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004519 Value *NewICmp =
4520 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004521 return new ZExtInst(NewICmp, I.getType());
4522 }
4523 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004524 }
4525
4526 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4527 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4528 return Res;
4529 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4530 // If this is an integer truncation or change from signed-to-unsigned, and
4531 // if the source is an and/or with immediate, transform it. This
4532 // frequently occurs for bitfield accesses.
4533 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4534 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4535 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00004536 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004537 if (CastOp->getOpcode() == Instruction::And) {
4538 // Change: and (cast (and X, C1) to T), C2
4539 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4540 // This will fold the two constants together, which may allow
4541 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004542 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004543 CastOp->getOperand(0), I.getType(),
4544 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004545 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004546 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004547 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004548 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549 } else if (CastOp->getOpcode() == Instruction::Or) {
4550 // Change: and (cast (or X, C1) to T), C2
4551 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004552 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004553 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004554 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004555 return ReplaceInstUsesWith(I, AndRHS);
4556 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004557 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004558 }
4559 }
4560
4561 // Try to fold constant and into select arguments.
4562 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4563 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4564 return R;
4565 if (isa<PHINode>(Op0))
4566 if (Instruction *NV = FoldOpIntoPhi(I))
4567 return NV;
4568 }
4569
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004570
4571 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00004572 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4573 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4574 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4575 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4576 I.getName()+".demorgan");
4577 return BinaryOperator::CreateNot(Or);
4578 }
4579
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004580 {
4581 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004582 // (A|B) & ~(A&B) -> A^B
4583 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4584 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4585 ((A == C && B == D) || (A == D && B == C)))
4586 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004587
Chris Lattnera3e46f62009-11-10 00:55:12 +00004588 // ~(A&B) & (A|B) -> A^B
4589 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4590 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4591 ((A == C && B == D) || (A == D && B == C)))
4592 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004593
4594 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004595 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004596 if (A == Op1) { // (A^B)&A -> A&(A^B)
4597 I.swapOperands(); // Simplify below
4598 std::swap(Op0, Op1);
4599 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4600 cast<BinaryOperator>(Op0)->swapOperands();
4601 I.swapOperands(); // Simplify below
4602 std::swap(Op0, Op1);
4603 }
4604 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004605
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004606 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004607 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004608 if (B == Op0) { // B&(A^B) -> B&(B^A)
4609 cast<BinaryOperator>(Op1)->swapOperands();
4610 std::swap(A, B);
4611 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004612 if (A == Op0) // A&(A^B) -> A & ~B
4613 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004614 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004615
4616 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004617 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4618 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004619 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004620 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4621 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004622 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004623 }
4624
4625 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4626 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004627 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004628 return R;
4629
Chris Lattner0631ea72008-11-16 05:06:21 +00004630 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4631 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4632 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004633 }
4634
4635 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4636 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4637 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4638 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4639 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004640 if (SrcTy == Op1C->getOperand(0)->getType() &&
4641 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004642 // Only do this if the casts both really cause code to be generated.
4643 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4644 I.getType(), TD) &&
4645 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4646 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004647 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4648 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004649 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004650 }
4651 }
4652
4653 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4654 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4655 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4656 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4657 SI0->getOperand(1) == SI1->getOperand(1) &&
4658 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004659 Value *NewOp =
4660 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4661 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004662 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004663 SI1->getOperand(1));
4664 }
4665 }
4666
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004667 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004668 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004669 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4670 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4671 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004672 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004673
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004674 return Changed ? &I : 0;
4675}
4676
Chris Lattner567f5112008-10-05 02:13:19 +00004677/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4678/// capable of providing pieces of a bswap. The subexpression provides pieces
4679/// of a bswap if it is proven that each of the non-zero bytes in the output of
4680/// the expression came from the corresponding "byte swapped" byte in some other
4681/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4682/// we know that the expression deposits the low byte of %X into the high byte
4683/// of the bswap result and that all other bytes are zero. This expression is
4684/// accepted, the high byte of ByteValues is set to X to indicate a correct
4685/// match.
4686///
4687/// This function returns true if the match was unsuccessful and false if so.
4688/// On entry to the function the "OverallLeftShift" is a signed integer value
4689/// indicating the number of bytes that the subexpression is later shifted. For
4690/// example, if the expression is later right shifted by 16 bits, the
4691/// OverallLeftShift value would be -2 on entry. This is used to specify which
4692/// byte of ByteValues is actually being set.
4693///
4694/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4695/// byte is masked to zero by a user. For example, in (X & 255), X will be
4696/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4697/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4698/// always in the local (OverallLeftShift) coordinate space.
4699///
4700static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4701 SmallVector<Value*, 8> &ByteValues) {
4702 if (Instruction *I = dyn_cast<Instruction>(V)) {
4703 // If this is an or instruction, it may be an inner node of the bswap.
4704 if (I->getOpcode() == Instruction::Or) {
4705 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4706 ByteValues) ||
4707 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4708 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004709 }
Chris Lattner567f5112008-10-05 02:13:19 +00004710
4711 // If this is a logical shift by a constant multiple of 8, recurse with
4712 // OverallLeftShift and ByteMask adjusted.
4713 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4714 unsigned ShAmt =
4715 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4716 // Ensure the shift amount is defined and of a byte value.
4717 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4718 return true;
4719
4720 unsigned ByteShift = ShAmt >> 3;
4721 if (I->getOpcode() == Instruction::Shl) {
4722 // X << 2 -> collect(X, +2)
4723 OverallLeftShift += ByteShift;
4724 ByteMask >>= ByteShift;
4725 } else {
4726 // X >>u 2 -> collect(X, -2)
4727 OverallLeftShift -= ByteShift;
4728 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004729 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004730 }
4731
4732 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4733 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4734
4735 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4736 ByteValues);
4737 }
4738
4739 // If this is a logical 'and' with a mask that clears bytes, clear the
4740 // corresponding bytes in ByteMask.
4741 if (I->getOpcode() == Instruction::And &&
4742 isa<ConstantInt>(I->getOperand(1))) {
4743 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4744 unsigned NumBytes = ByteValues.size();
4745 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4746 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4747
4748 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4749 // If this byte is masked out by a later operation, we don't care what
4750 // the and mask is.
4751 if ((ByteMask & (1 << i)) == 0)
4752 continue;
4753
4754 // If the AndMask is all zeros for this byte, clear the bit.
4755 APInt MaskB = AndMask & Byte;
4756 if (MaskB == 0) {
4757 ByteMask &= ~(1U << i);
4758 continue;
4759 }
4760
4761 // If the AndMask is not all ones for this byte, it's not a bytezap.
4762 if (MaskB != Byte)
4763 return true;
4764
4765 // Otherwise, this byte is kept.
4766 }
4767
4768 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4769 ByteValues);
4770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004771 }
4772
Chris Lattner567f5112008-10-05 02:13:19 +00004773 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4774 // the input value to the bswap. Some observations: 1) if more than one byte
4775 // is demanded from this input, then it could not be successfully assembled
4776 // into a byteswap. At least one of the two bytes would not be aligned with
4777 // their ultimate destination.
4778 if (!isPowerOf2_32(ByteMask)) return true;
4779 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004780
Chris Lattner567f5112008-10-05 02:13:19 +00004781 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4782 // is demanded, it needs to go into byte 0 of the result. This means that the
4783 // byte needs to be shifted until it lands in the right byte bucket. The
4784 // shift amount depends on the position: if the byte is coming from the high
4785 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4786 // low part, it must be shifted left.
4787 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4788 if (InputByteNo < ByteValues.size()/2) {
4789 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4790 return true;
4791 } else {
4792 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4793 return true;
4794 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004795
4796 // If the destination byte value is already defined, the values are or'd
4797 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004798 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004799 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004800 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004801 return false;
4802}
4803
4804/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4805/// If so, insert the new bswap intrinsic and return it.
4806Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4807 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004808 if (!ITy || ITy->getBitWidth() % 16 ||
4809 // ByteMask only allows up to 32-byte values.
4810 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004811 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4812
4813 /// ByteValues - For each byte of the result, we keep track of which value
4814 /// defines each byte.
4815 SmallVector<Value*, 8> ByteValues;
4816 ByteValues.resize(ITy->getBitWidth()/8);
4817
4818 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004819 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4820 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004821 return 0;
4822
4823 // Check to see if all of the bytes come from the same value.
4824 Value *V = ByteValues[0];
4825 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4826
4827 // Check to make sure that all of the bytes come from the same value.
4828 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4829 if (ByteValues[i] != V)
4830 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004831 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004832 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004833 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004834 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004835}
4836
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004837/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4838/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4839/// we can simplify this expression to "cond ? C : D or B".
4840static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004841 Value *C, Value *D,
4842 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004843 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004844 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004845 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004846 return 0;
4847
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004848 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004849 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004850 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004851 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004852 return SelectInst::Create(Cond, C, B);
4853 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004854 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004855 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004856 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004857 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004858 return 0;
4859}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004860
Chris Lattner0c678e52008-11-16 05:20:07 +00004861/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4862Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4863 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner163e6ab2009-11-29 00:51:17 +00004864 // (icmp ne A, null) | (icmp ne B, null) -->
4865 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4866 if (TD &&
4867 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4868 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4869 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4870 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4871 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4872 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4873 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4874 Value *NewOr = Builder->CreateOr(A, B);
4875 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4876 Constant::getNullValue(IntPtrTy));
4877 }
4878
Chris Lattner0c678e52008-11-16 05:20:07 +00004879 Value *Val, *Val2;
4880 ConstantInt *LHSCst, *RHSCst;
4881 ICmpInst::Predicate LHSCC, RHSCC;
4882
4883 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner163e6ab2009-11-29 00:51:17 +00004884 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4885 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004886 return 0;
Chris Lattner163e6ab2009-11-29 00:51:17 +00004887
4888
4889 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4890 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4891 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4892 Value *NewOr = Builder->CreateOr(Val, Val2);
4893 return new ICmpInst(LHSCC, NewOr, LHSCst);
4894 }
Chris Lattner0c678e52008-11-16 05:20:07 +00004895
4896 // From here on, we only handle:
4897 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4898 if (Val != Val2) return 0;
4899
4900 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4901 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4902 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4903 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4904 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4905 return 0;
4906
4907 // We can't fold (ugt x, C) | (sgt x, C2).
4908 if (!PredicatesFoldable(LHSCC, RHSCC))
4909 return 0;
4910
4911 // Ensure that the larger constant is on the RHS.
4912 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004913 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004914 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004915 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004916 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4917 else
4918 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4919
4920 if (ShouldSwap) {
4921 std::swap(LHS, RHS);
4922 std::swap(LHSCst, RHSCst);
4923 std::swap(LHSCC, RHSCC);
4924 }
4925
4926 // At this point, we know we have have two icmp instructions
4927 // comparing a value against two constants and or'ing the result
4928 // together. Because of the above check, we know that we only have
4929 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4930 // FoldICmpLogical check above), that the two constants are not
4931 // equal.
4932 assert(LHSCst != RHSCst && "Compares not folded above?");
4933
4934 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004935 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004936 case ICmpInst::ICMP_EQ:
4937 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004938 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004939 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004940 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004941 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004942 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004943 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004944 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004945 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004946 }
4947 break; // (X == 13 | X == 15) -> no change
4948 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4949 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4950 break;
4951 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4952 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4953 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4954 return ReplaceInstUsesWith(I, RHS);
4955 }
4956 break;
4957 case ICmpInst::ICMP_NE:
4958 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004959 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004960 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4961 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4962 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4963 return ReplaceInstUsesWith(I, LHS);
4964 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4965 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4966 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004967 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004968 }
4969 break;
4970 case ICmpInst::ICMP_ULT:
4971 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004972 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004973 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4974 break;
4975 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4976 // If RHSCst is [us]MAXINT, it is always false. Not handling
4977 // this can cause overflow.
4978 if (RHSCst->isMaxValue(false))
4979 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004980 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004981 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004982 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4983 break;
4984 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4985 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4986 return ReplaceInstUsesWith(I, RHS);
4987 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4988 break;
4989 }
4990 break;
4991 case ICmpInst::ICMP_SLT:
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 == 14) -> no change
4995 break;
4996 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4997 // If RHSCst is [us]MAXINT, it is always false. Not handling
4998 // this can cause overflow.
4999 if (RHSCst->isMaxValue(true))
5000 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005001 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00005002 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00005003 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
5004 break;
5005 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
5006 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
5007 return ReplaceInstUsesWith(I, RHS);
5008 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
5009 break;
5010 }
5011 break;
5012 case ICmpInst::ICMP_UGT:
5013 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005014 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00005015 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
5016 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
5017 return ReplaceInstUsesWith(I, LHS);
5018 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
5019 break;
5020 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
5021 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005022 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00005023 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
5024 break;
5025 }
5026 break;
5027 case ICmpInst::ICMP_SGT:
5028 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005029 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00005030 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
5031 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5032 return ReplaceInstUsesWith(I, LHS);
5033 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5034 break;
5035 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5036 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005037 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00005038 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5039 break;
5040 }
5041 break;
5042 }
5043 return 0;
5044}
5045
Chris Lattner57e66fa2009-07-23 05:46:22 +00005046Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5047 FCmpInst *RHS) {
5048 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5049 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5050 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5051 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5052 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5053 // If either of the constants are nans, then the whole thing returns
5054 // true.
5055 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005056 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00005057
5058 // Otherwise, no need to compare the two constants, compare the
5059 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00005060 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005061 LHS->getOperand(0), RHS->getOperand(0));
5062 }
5063
5064 // Handle vector zeros. This occurs because the canonical form of
5065 // "fcmp uno x,x" is "fcmp uno x, 0".
5066 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5067 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00005068 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005069 LHS->getOperand(0), RHS->getOperand(0));
5070
5071 return 0;
5072 }
5073
5074 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5075 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5076 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5077
5078 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5079 // Swap RHS operands to match LHS.
5080 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5081 std::swap(Op1LHS, Op1RHS);
5082 }
5083 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5084 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5085 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00005086 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005087 Op0LHS, Op0RHS);
5088 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005089 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00005090 if (Op0CC == FCmpInst::FCMP_FALSE)
5091 return ReplaceInstUsesWith(I, RHS);
5092 if (Op1CC == FCmpInst::FCMP_FALSE)
5093 return ReplaceInstUsesWith(I, LHS);
5094 bool Op0Ordered;
5095 bool Op1Ordered;
5096 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5097 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5098 if (Op0Ordered == Op1Ordered) {
5099 // If both are ordered or unordered, return a new fcmp with
5100 // or'ed predicates.
5101 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5102 Op0LHS, Op0RHS, Context);
5103 if (Instruction *I = dyn_cast<Instruction>(RV))
5104 return I;
5105 // Otherwise, it's a constant boolean value...
5106 return ReplaceInstUsesWith(I, RV);
5107 }
5108 }
5109 return 0;
5110}
5111
Bill Wendlingdae376a2008-12-01 08:23:25 +00005112/// FoldOrWithConstants - This helper function folds:
5113///
Bill Wendling236a1192008-12-02 05:09:00 +00005114/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00005115///
5116/// into:
5117///
Bill Wendling236a1192008-12-02 05:09:00 +00005118/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00005119///
Bill Wendling236a1192008-12-02 05:09:00 +00005120/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00005121Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00005122 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00005123 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5124 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005125
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005126 Value *V1 = 0;
5127 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005128 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005129
Bill Wendling86ee3162008-12-02 06:18:11 +00005130 APInt Xor = CI1->getValue() ^ CI2->getValue();
5131 if (!Xor.isAllOnesValue()) return 0;
5132
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005133 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005134 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00005135 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005136 }
5137
5138 return 0;
5139}
5140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005141Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5142 bool Changed = SimplifyCommutative(I);
5143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5144
Chris Lattnera3e46f62009-11-10 00:55:12 +00005145 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5146 return ReplaceInstUsesWith(I, V);
5147
5148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005149 // See if we can simplify any instructions used by the instruction whose sole
5150 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005151 if (SimplifyDemandedInstructionBits(I))
5152 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005154 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5155 ConstantInt *C1 = 0; Value *X = 0;
5156 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005157 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005158 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005159 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005160 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005161 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005162 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005163 }
5164
5165 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005166 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005167 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005168 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005169 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005170 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005171 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005172 }
5173
5174 // Try to fold constant and into select arguments.
5175 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5176 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5177 return R;
5178 if (isa<PHINode>(Op0))
5179 if (Instruction *NV = FoldOpIntoPhi(I))
5180 return NV;
5181 }
5182
5183 Value *A = 0, *B = 0;
5184 ConstantInt *C1 = 0, *C2 = 0;
5185
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005186 // (A | B) | C and A | (B | C) -> bswap if possible.
5187 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00005188 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5189 match(Op1, m_Or(m_Value(), m_Value())) ||
5190 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5191 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192 if (Instruction *BSwap = MatchBSwap(I))
5193 return BSwap;
5194 }
5195
5196 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005197 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005198 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005199 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005200 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005201 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005202 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005203 }
5204
5205 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005206 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005207 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005208 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005209 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005210 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005211 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005212 }
5213
5214 // (A & C)|(B & D)
5215 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005216 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5217 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005218 Value *V1 = 0, *V2 = 0, *V3 = 0;
5219 C1 = dyn_cast<ConstantInt>(C);
5220 C2 = dyn_cast<ConstantInt>(D);
5221 if (C1 && C2) { // (A & C1)|(B & C2)
5222 // If we have: ((V + N) & C1) | (V & C2)
5223 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5224 // replace with V+N.
5225 if (C1->getValue() == ~C2->getValue()) {
5226 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00005227 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005228 // Add commutes, try both ways.
5229 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5230 return ReplaceInstUsesWith(I, A);
5231 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5232 return ReplaceInstUsesWith(I, A);
5233 }
5234 // Or commutes, try both ways.
5235 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005236 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 // Add commutes, try both ways.
5238 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5239 return ReplaceInstUsesWith(I, B);
5240 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5241 return ReplaceInstUsesWith(I, B);
5242 }
5243 }
5244 V1 = 0; V2 = 0; V3 = 0;
5245 }
5246
5247 // Check to see if we have any common things being and'ed. If so, find the
5248 // terms for V1 & (V2|V3).
5249 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5250 if (A == B) // (A & C)|(A & D) == A & (C|D)
5251 V1 = A, V2 = C, V3 = D;
5252 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5253 V1 = A, V2 = B, V3 = C;
5254 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5255 V1 = C, V2 = A, V3 = D;
5256 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5257 V1 = C, V2 = A, V3 = B;
5258
5259 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005260 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005261 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005262 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005263 }
Dan Gohman279952c2008-10-28 22:38:57 +00005264
Dan Gohman35b76162008-10-30 20:40:10 +00005265 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00005266 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005267 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005268 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005269 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005270 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005271 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005272 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005273 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00005274
Bill Wendling22ca8352008-11-30 13:52:49 +00005275 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005276 if ((match(C, m_Not(m_Specific(D))) &&
5277 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005278 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005279 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005280 if ((match(A, m_Not(m_Specific(D))) &&
5281 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005282 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005283 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005284 if ((match(C, m_Not(m_Specific(B))) &&
5285 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005286 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00005287 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005288 if ((match(A, m_Not(m_Specific(B))) &&
5289 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005290 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005291 }
5292
5293 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5294 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5295 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5296 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5297 SI0->getOperand(1) == SI1->getOperand(1) &&
5298 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005299 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5300 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005301 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005302 SI1->getOperand(1));
5303 }
5304 }
5305
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005306 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005307 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5308 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005309 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005310 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005311 }
5312 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005313 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5314 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005315 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005316 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005317 }
5318
Chris Lattnera3e46f62009-11-10 00:55:12 +00005319 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5320 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5321 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5322 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5323 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5324 I.getName()+".demorgan");
5325 return BinaryOperator::CreateNot(And);
5326 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005327
5328 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5329 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005330 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005331 return R;
5332
Chris Lattner0c678e52008-11-16 05:20:07 +00005333 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5334 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5335 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005336 }
5337
5338 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005339 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005340 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5341 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005342 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5343 !isa<ICmpInst>(Op1C->getOperand(0))) {
5344 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005345 if (SrcTy == Op1C->getOperand(0)->getType() &&
5346 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005347 // Only do this if the casts both really cause code to be
5348 // generated.
5349 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5350 I.getType(), TD) &&
5351 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5352 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005353 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5354 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005355 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005356 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005357 }
5358 }
Chris Lattner91882432007-10-24 05:38:08 +00005359 }
5360
5361
5362 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5363 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005364 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5365 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5366 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005367 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005368
5369 return Changed ? &I : 0;
5370}
5371
Dan Gohman089efff2008-05-13 00:00:25 +00005372namespace {
5373
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005374// XorSelf - Implements: X ^ X --> 0
5375struct XorSelf {
5376 Value *RHS;
5377 XorSelf(Value *rhs) : RHS(rhs) {}
5378 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5379 Instruction *apply(BinaryOperator &Xor) const {
5380 return &Xor;
5381 }
5382};
5383
Dan Gohman089efff2008-05-13 00:00:25 +00005384}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005385
5386Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5387 bool Changed = SimplifyCommutative(I);
5388 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5389
Evan Chenge5cd8032008-03-25 20:07:13 +00005390 if (isa<UndefValue>(Op1)) {
5391 if (isa<UndefValue>(Op0))
5392 // Handle undef ^ undef -> 0 special case. This is a common
5393 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005394 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005395 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005396 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005397
5398 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005399 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005400 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005401 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005402 }
5403
5404 // See if we can simplify any instructions used by the instruction whose sole
5405 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005406 if (SimplifyDemandedInstructionBits(I))
5407 return &I;
5408 if (isa<VectorType>(I.getType()))
5409 if (isa<ConstantAggregateZero>(Op1))
5410 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005411
5412 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005413 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005414 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5415 if (Op0I->getOpcode() == Instruction::And ||
5416 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00005417 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5418 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5419 if (dyn_castNotVal(Op0I->getOperand(1)))
5420 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005421 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005422 Value *NotY =
5423 Builder->CreateNot(Op0I->getOperand(1),
5424 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005425 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005426 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005427 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005428 }
Chris Lattner6e060db2009-10-26 15:40:07 +00005429
5430 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5431 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5432 if (isFreeToInvert(Op0I->getOperand(0)) &&
5433 isFreeToInvert(Op0I->getOperand(1))) {
5434 Value *NotX =
5435 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5436 Value *NotY =
5437 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5438 if (Op0I->getOpcode() == Instruction::And)
5439 return BinaryOperator::CreateOr(NotX, NotY);
5440 return BinaryOperator::CreateAnd(NotX, NotY);
5441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005442 }
5443 }
5444 }
5445
5446
5447 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005448 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005449 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005450 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005451 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005452 ICI->getOperand(0), ICI->getOperand(1));
5453
Nick Lewycky1405e922007-08-06 20:04:16 +00005454 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005455 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005456 FCI->getOperand(0), FCI->getOperand(1));
5457 }
5458
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005459 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5460 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5461 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5462 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5463 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005464 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5465 (RHS == ConstantExpr::getCast(Opcode,
5466 ConstantInt::getTrue(*Context),
5467 Op0C->getDestTy()))) {
5468 CI->setPredicate(CI->getInversePredicate());
5469 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005470 }
5471 }
5472 }
5473 }
5474
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005475 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5476 // ~(c-X) == X-c-1 == X+(-c-1)
5477 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5478 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005479 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5480 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005481 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005482 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005483 }
5484
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005485 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005486 if (Op0I->getOpcode() == Instruction::Add) {
5487 // ~(X-c) --> (-c-1)-X
5488 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005489 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005490 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005491 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005492 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005493 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005494 } else if (RHS->getValue().isSignBit()) {
5495 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005496 Constant *C = ConstantInt::get(*Context,
5497 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005498 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005499
5500 }
5501 } else if (Op0I->getOpcode() == Instruction::Or) {
5502 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5503 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005504 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005505 // Anything in both C1 and C2 is known to be zero, remove it from
5506 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005507 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5508 NewRHS = ConstantExpr::getAnd(NewRHS,
5509 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005510 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511 I.setOperand(0, Op0I->getOperand(0));
5512 I.setOperand(1, NewRHS);
5513 return &I;
5514 }
5515 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005516 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005517 }
5518
5519 // Try to fold constant and into select arguments.
5520 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5521 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5522 return R;
5523 if (isa<PHINode>(Op0))
5524 if (Instruction *NV = FoldOpIntoPhi(I))
5525 return NV;
5526 }
5527
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005528 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005529 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005530 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005531
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005532 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005533 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005534 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005535
5536
5537 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5538 if (Op1I) {
5539 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005540 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005541 if (A == Op0) { // B^(B|A) == (A|B)^B
5542 Op1I->swapOperands();
5543 I.swapOperands();
5544 std::swap(Op0, Op1);
5545 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5546 I.swapOperands(); // Simplified below.
5547 std::swap(Op0, Op1);
5548 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005549 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005550 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005551 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005552 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005553 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005554 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005555 if (A == Op0) { // A^(A&B) -> A^(B&A)
5556 Op1I->swapOperands();
5557 std::swap(A, B);
5558 }
5559 if (B == Op0) { // A^(B&A) -> (B&A)^A
5560 I.swapOperands(); // Simplified below.
5561 std::swap(Op0, Op1);
5562 }
5563 }
5564 }
5565
5566 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5567 if (Op0I) {
5568 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005569 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005570 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005571 if (A == Op1) // (B|A)^B == (A|B)^B
5572 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005573 if (B == Op1) // (A|B)^B == A & ~B
5574 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005575 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005576 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005577 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005578 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005579 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005580 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005581 if (A == Op1) // (A&B)^A -> (B&A)^A
5582 std::swap(A, B);
5583 if (B == Op1 && // (B&A)^A == ~B & A
5584 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005585 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005586 }
5587 }
5588 }
5589
5590 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5591 if (Op0I && Op1I && Op0I->isShift() &&
5592 Op0I->getOpcode() == Op1I->getOpcode() &&
5593 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5594 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005595 Value *NewOp =
5596 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5597 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005598 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005599 Op1I->getOperand(1));
5600 }
5601
5602 if (Op0I && Op1I) {
5603 Value *A, *B, *C, *D;
5604 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005605 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5606 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005607 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005608 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005609 }
5610 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005611 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5612 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005613 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005614 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005615 }
5616
5617 // (A & B)^(C & D)
5618 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005619 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5620 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005621 // (X & Y)^(X & Y) -> (Y^Z) & X
5622 Value *X = 0, *Y = 0, *Z = 0;
5623 if (A == C)
5624 X = A, Y = B, Z = D;
5625 else if (A == D)
5626 X = A, Y = B, Z = C;
5627 else if (B == C)
5628 X = B, Y = A, Z = D;
5629 else if (B == D)
5630 X = B, Y = A, Z = C;
5631
5632 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005633 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005634 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005635 }
5636 }
5637 }
5638
5639 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5640 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005641 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005642 return R;
5643
5644 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005645 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005646 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5647 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5648 const Type *SrcTy = Op0C->getOperand(0)->getType();
5649 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5650 // Only do this if the casts both really cause code to be generated.
5651 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5652 I.getType(), TD) &&
5653 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5654 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005655 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5656 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005657 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005658 }
5659 }
Chris Lattner91882432007-10-24 05:38:08 +00005660 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005661
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005662 return Changed ? &I : 0;
5663}
5664
Owen Anderson24be4c12009-07-03 00:17:18 +00005665static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005666 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005667 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005668}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005669
Dan Gohman8fd520a2009-06-15 22:12:54 +00005670static bool HasAddOverflow(ConstantInt *Result,
5671 ConstantInt *In1, ConstantInt *In2,
5672 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005673 if (IsSigned)
5674 if (In2->getValue().isNegative())
5675 return Result->getValue().sgt(In1->getValue());
5676 else
5677 return Result->getValue().slt(In1->getValue());
5678 else
5679 return Result->getValue().ult(In1->getValue());
5680}
5681
Dan Gohman8fd520a2009-06-15 22:12:54 +00005682/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005683/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005684static bool AddWithOverflow(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::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005688
Dan Gohman8fd520a2009-06-15 22:12:54 +00005689 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 (HasAddOverflow(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 HasAddOverflow(cast<ConstantInt>(Result),
5702 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5703 IsSigned);
5704}
5705
5706static bool HasSubOverflow(ConstantInt *Result,
5707 ConstantInt *In1, ConstantInt *In2,
5708 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005709 if (IsSigned)
5710 if (In2->getValue().isNegative())
5711 return Result->getValue().slt(In1->getValue());
5712 else
5713 return Result->getValue().sgt(In1->getValue());
5714 else
5715 return Result->getValue().ugt(In1->getValue());
5716}
5717
Dan Gohman8fd520a2009-06-15 22:12:54 +00005718/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5719/// overflowed for this type.
5720static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005721 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005722 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005723 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005724
5725 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5726 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005727 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005728 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5729 ExtractElement(In1, Idx, Context),
5730 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005731 IsSigned))
5732 return true;
5733 }
5734 return false;
5735 }
5736
5737 return HasSubOverflow(cast<ConstantInt>(Result),
5738 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5739 IsSigned);
5740}
5741
Chris Lattnereba75862008-04-22 02:53:33 +00005742
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005743/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5744/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005745Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005746 ICmpInst::Predicate Cond,
5747 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005748 // Look through bitcasts.
5749 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5750 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005751
5752 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005753 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005754 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005755 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005756 // know pointers can't overflow since the gep is inbounds. See if we can
5757 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005758 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5759
5760 // If not, synthesize the offset the hard way.
5761 if (Offset == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005762 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005763 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005764 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005765 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005766 // If the base pointers are different, but the indices are the same, just
5767 // compare the base pointer.
5768 if (PtrBase != GEPRHS->getOperand(0)) {
5769 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5770 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5771 GEPRHS->getOperand(0)->getType();
5772 if (IndicesTheSame)
5773 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5774 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5775 IndicesTheSame = false;
5776 break;
5777 }
5778
5779 // If all indices are the same, just compare the base pointers.
5780 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005781 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005782 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5783
5784 // Otherwise, the base pointers are different and the indices are
5785 // different, bail out.
5786 return 0;
5787 }
5788
5789 // If one of the GEPs has all zero indices, recurse.
5790 bool AllZeros = true;
5791 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5792 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5793 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5794 AllZeros = false;
5795 break;
5796 }
5797 if (AllZeros)
5798 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5799 ICmpInst::getSwappedPredicate(Cond), I);
5800
5801 // If the other GEP has all zero indices, recurse.
5802 AllZeros = true;
5803 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5804 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5805 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5806 AllZeros = false;
5807 break;
5808 }
5809 if (AllZeros)
5810 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5811
5812 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5813 // If the GEPs only differ by one index, compare it.
5814 unsigned NumDifferences = 0; // Keep track of # differences.
5815 unsigned DiffOperand = 0; // The operand that differs.
5816 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5817 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5818 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5819 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5820 // Irreconcilable differences.
5821 NumDifferences = 2;
5822 break;
5823 } else {
5824 if (NumDifferences++) break;
5825 DiffOperand = i;
5826 }
5827 }
5828
5829 if (NumDifferences == 0) // SAME GEP?
5830 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005831 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005832 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005833
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005834 else if (NumDifferences == 1) {
5835 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5836 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5837 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005838 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005839 }
5840 }
5841
5842 // Only lower this if the icmp is the only user of the GEP or if we expect
5843 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005844 if (TD &&
5845 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005846 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5847 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005848 Value *L = EmitGEPOffset(GEPLHS, *this);
5849 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005850 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005851 }
5852 }
5853 return 0;
5854}
5855
Chris Lattnere6b62d92008-05-19 20:18:56 +00005856/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5857///
5858Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5859 Instruction *LHSI,
5860 Constant *RHSC) {
5861 if (!isa<ConstantFP>(RHSC)) return 0;
5862 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5863
5864 // Get the width of the mantissa. We don't want to hack on conversions that
5865 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005866 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005867 if (MantissaWidth == -1) return 0; // Unknown.
5868
5869 // Check to see that the input is converted from an integer type that is small
5870 // enough that preserves all bits. TODO: check here for "known" sign bits.
5871 // 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 +00005872 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005873
5874 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005875 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5876 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005877 ++InputSize;
5878
5879 // If the conversion would lose info, don't hack on this.
5880 if ((int)InputSize > MantissaWidth)
5881 return 0;
5882
5883 // Otherwise, we can potentially simplify the comparison. We know that it
5884 // will always come through as an integer value and we know the constant is
5885 // not a NAN (it would have been previously simplified).
5886 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5887
5888 ICmpInst::Predicate Pred;
5889 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005890 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005891 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005892 case FCmpInst::FCMP_OEQ:
5893 Pred = ICmpInst::ICMP_EQ;
5894 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005895 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005896 case FCmpInst::FCMP_OGT:
5897 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5898 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005899 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005900 case FCmpInst::FCMP_OGE:
5901 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5902 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005903 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005904 case FCmpInst::FCMP_OLT:
5905 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5906 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005907 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005908 case FCmpInst::FCMP_OLE:
5909 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5910 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005911 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005912 case FCmpInst::FCMP_ONE:
5913 Pred = ICmpInst::ICMP_NE;
5914 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005915 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005916 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005917 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005918 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005919 }
5920
5921 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5922
5923 // Now we know that the APFloat is a normal number, zero or inf.
5924
Chris Lattnerf13ff492008-05-20 03:50:52 +00005925 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005926 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005927 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005928
Bill Wendling20636df2008-11-09 04:26:50 +00005929 if (!LHSUnsigned) {
5930 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5931 // and large values.
5932 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5933 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5934 APFloat::rmNearestTiesToEven);
5935 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5936 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5937 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5939 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005940 }
5941 } else {
5942 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5943 // +INF and large values.
5944 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5945 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5946 APFloat::rmNearestTiesToEven);
5947 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5948 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5949 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005950 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5951 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005952 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005953 }
5954
Bill Wendling20636df2008-11-09 04:26:50 +00005955 if (!LHSUnsigned) {
5956 // See if the RHS value is < SignedMin.
5957 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5958 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5959 APFloat::rmNearestTiesToEven);
5960 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5961 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5962 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005963 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5964 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005965 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005966 }
5967
Bill Wendling20636df2008-11-09 04:26:50 +00005968 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5969 // [0, UMAX], but it may still be fractional. See if it is fractional by
5970 // casting the FP value to the integer value and back, checking for equality.
5971 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005972 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005973 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5974 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005975 if (!RHS.isZero()) {
5976 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005977 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5978 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005979 if (!Equal) {
5980 // If we had a comparison against a fractional value, we have to adjust
5981 // the compare predicate and sometimes the value. RHSC is rounded towards
5982 // zero at this point.
5983 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005984 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005985 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005986 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005987 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005988 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005989 case ICmpInst::ICMP_ULE:
5990 // (float)int <= 4.4 --> int <= 4
5991 // (float)int <= -4.4 --> false
5992 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005993 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005994 break;
5995 case ICmpInst::ICMP_SLE:
5996 // (float)int <= 4.4 --> int <= 4
5997 // (float)int <= -4.4 --> int < -4
5998 if (RHS.isNegative())
5999 Pred = ICmpInst::ICMP_SLT;
6000 break;
6001 case ICmpInst::ICMP_ULT:
6002 // (float)int < -4.4 --> false
6003 // (float)int < 4.4 --> int <= 4
6004 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00006005 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00006006 Pred = ICmpInst::ICMP_ULE;
6007 break;
6008 case ICmpInst::ICMP_SLT:
6009 // (float)int < -4.4 --> int < -4
6010 // (float)int < 4.4 --> int <= 4
6011 if (!RHS.isNegative())
6012 Pred = ICmpInst::ICMP_SLE;
6013 break;
6014 case ICmpInst::ICMP_UGT:
6015 // (float)int > 4.4 --> int > 4
6016 // (float)int > -4.4 --> true
6017 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00006018 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00006019 break;
6020 case ICmpInst::ICMP_SGT:
6021 // (float)int > 4.4 --> int > 4
6022 // (float)int > -4.4 --> int >= -4
6023 if (RHS.isNegative())
6024 Pred = ICmpInst::ICMP_SGE;
6025 break;
6026 case ICmpInst::ICMP_UGE:
6027 // (float)int >= -4.4 --> true
6028 // (float)int >= 4.4 --> int > 4
6029 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00006030 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00006031 Pred = ICmpInst::ICMP_UGT;
6032 break;
6033 case ICmpInst::ICMP_SGE:
6034 // (float)int >= -4.4 --> int >= -4
6035 // (float)int >= 4.4 --> int > 4
6036 if (!RHS.isNegative())
6037 Pred = ICmpInst::ICMP_SGT;
6038 break;
6039 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00006040 }
6041 }
6042
6043 // Lower this FP comparison into an appropriate integer version of the
6044 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00006045 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00006046}
6047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006048Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006049 bool Changed = false;
6050
6051 /// Orders the operands of the compare so that they are listed from most
6052 /// complex to least complex. This puts constants before unary operators,
6053 /// before binary operators.
6054 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6055 I.swapOperands();
6056 Changed = true;
6057 }
6058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006060
Chris Lattner54c21352009-11-09 23:55:12 +00006061 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6062 return ReplaceInstUsesWith(I, V);
6063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006064 // Simplify 'fcmp pred X, X'
6065 if (Op0 == Op1) {
6066 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006067 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006068 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6069 case FCmpInst::FCMP_ULT: // True if unordered or less than
6070 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6071 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6072 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6073 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00006074 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006075 return &I;
6076
6077 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6078 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6079 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6080 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6081 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6082 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00006083 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006084 return &I;
6085 }
6086 }
6087
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088 // Handle fcmp with constant RHS
6089 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6090 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6091 switch (LHSI->getOpcode()) {
6092 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006093 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6094 // block. If in the same block, we're encouraging jump threading. If
6095 // not, we are just pessimizing the code by making an i1 phi.
6096 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006097 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006098 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006099 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00006100 case Instruction::SIToFP:
6101 case Instruction::UIToFP:
6102 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6103 return NV;
6104 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006105 case Instruction::Select:
6106 // If either operand of the select is a constant, we can fold the
6107 // comparison into the select arms, which will cause one to be
6108 // constant folded and the select turned into a bitwise or.
6109 Value *Op1 = 0, *Op2 = 0;
6110 if (LHSI->hasOneUse()) {
6111 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6112 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006113 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006114 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006115 Op2 = Builder->CreateFCmp(I.getPredicate(),
6116 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6118 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006119 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006120 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006121 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6122 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006123 }
6124 }
6125
6126 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006127 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006128 break;
6129 }
6130 }
6131
6132 return Changed ? &I : 0;
6133}
6134
6135Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006136 bool Changed = false;
6137
6138 /// Orders the operands of the compare so that they are listed from most
6139 /// complex to least complex. This puts constants before unary operators,
6140 /// before binary operators.
6141 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6142 I.swapOperands();
6143 Changed = true;
6144 }
6145
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006146 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lambf78cd322007-12-18 21:32:20 +00006147
Chris Lattner54c21352009-11-09 23:55:12 +00006148 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6149 return ReplaceInstUsesWith(I, V);
6150
6151 const Type *Ty = Op0->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006152
6153 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006154 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006155 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006156 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006157 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006158 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006159 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006160 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006161 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006162 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006163
6164 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006165 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006166 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006167 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006168 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006169 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006170 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006171 case ICmpInst::ICMP_SGT:
6172 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006173 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006174 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006175 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006176 return BinaryOperator::CreateAnd(Not, Op0);
6177 }
6178 case ICmpInst::ICMP_UGE:
6179 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6180 // FALL THROUGH
6181 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006182 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006183 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006184 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006185 case ICmpInst::ICMP_SGE:
6186 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6187 // FALL THROUGH
6188 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006189 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006190 return BinaryOperator::CreateOr(Not, Op0);
6191 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006192 }
6193 }
6194
Dan Gohman7934d592009-04-25 17:12:48 +00006195 unsigned BitWidth = 0;
6196 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006197 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6198 else if (Ty->isIntOrIntVector())
6199 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006200
6201 bool isSignBit = false;
6202
Dan Gohman58c09632008-09-16 18:46:06 +00006203 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006204 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006205 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006206
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006207 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6208 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006209 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006210 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006211 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006212 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006213
Dan Gohman58c09632008-09-16 18:46:06 +00006214 // If we have an icmp le or icmp ge instruction, turn it into the
6215 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner54c21352009-11-09 23:55:12 +00006216 // them being folded in the code below. The SimplifyICmpInst code has
6217 // already handled the edge cases for us, so we just assert on them.
Chris Lattner62d0f232008-07-11 05:08:55 +00006218 switch (I.getPredicate()) {
6219 default: break;
6220 case ICmpInst::ICMP_ULE:
Chris Lattner54c21352009-11-09 23:55:12 +00006221 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006222 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006223 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006224 case ICmpInst::ICMP_SLE:
Chris Lattner54c21352009-11-09 23:55:12 +00006225 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006226 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006227 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006228 case ICmpInst::ICMP_UGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006229 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006230 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006231 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006232 case ICmpInst::ICMP_SGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006233 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006234 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006235 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006236 }
6237
Chris Lattnera1308652008-07-11 05:40:05 +00006238 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006239 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006240 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006241 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6242 }
6243
6244 // See if we can fold the comparison based on range information we can get
6245 // by checking whether bits are known to be zero or one in the input.
6246 if (BitWidth != 0) {
6247 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6248 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6249
6250 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006251 isSignBit ? APInt::getSignBit(BitWidth)
6252 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006253 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006254 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006255 if (SimplifyDemandedBits(I.getOperandUse(1),
6256 APInt::getAllOnesValue(BitWidth),
6257 Op1KnownZero, Op1KnownOne, 0))
6258 return &I;
6259
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006260 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006261 // in. Compute the Min, Max and RHS values based on the known bits. For the
6262 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006263 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6264 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006265 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006266 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6267 Op0Min, Op0Max);
6268 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6269 Op1Min, Op1Max);
6270 } else {
6271 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6272 Op0Min, Op0Max);
6273 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6274 Op1Min, Op1Max);
6275 }
6276
Chris Lattnera1308652008-07-11 05:40:05 +00006277 // If Min and Max are known to be the same, then SimplifyDemandedBits
6278 // figured out that the LHS is a constant. Just constant fold this now so
6279 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006280 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006281 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006282 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006283 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006284 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006285 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006286
Chris Lattnera1308652008-07-11 05:40:05 +00006287 // Based on the range information we know about the LHS, see if we can
6288 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006289 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006290 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006291 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006292 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006293 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006294 break;
6295 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006296 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006297 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006298 break;
6299 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006300 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006301 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006302 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006303 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006304 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006305 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006306 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6307 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006308 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006309 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006310
6311 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6312 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006313 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006314 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006315 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006316 break;
6317 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006318 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006319 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006320 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006321 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006322
6323 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006324 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6326 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006327 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006328 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006329
6330 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6331 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006332 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006333 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006334 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006335 break;
6336 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006337 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006338 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006339 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006340 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006341 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006342 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006343 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6344 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006345 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006346 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006347 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006348 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006349 case ICmpInst::ICMP_SGT:
6350 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006351 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006352 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006353 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006354
6355 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006356 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006357 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6358 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006359 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006360 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006361 }
6362 break;
6363 case ICmpInst::ICMP_SGE:
6364 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6365 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006366 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006367 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006368 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006369 break;
6370 case ICmpInst::ICMP_SLE:
6371 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6372 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006373 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006374 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006375 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006376 break;
6377 case ICmpInst::ICMP_UGE:
6378 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6379 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006380 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006381 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006382 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006383 break;
6384 case ICmpInst::ICMP_ULE:
6385 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6386 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006387 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006388 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006389 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006390 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006391 }
Dan Gohman7934d592009-04-25 17:12:48 +00006392
6393 // Turn a signed comparison into an unsigned one if both operands
6394 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006395 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006396 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6397 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006398 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006399 }
6400
6401 // Test if the ICmpInst instruction is used exclusively by a select as
6402 // part of a minimum or maximum operation. If so, refrain from doing
6403 // any other folding. This helps out other analyses which understand
6404 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6405 // and CodeGen. And in this case, at least one of the comparison
6406 // operands has at least one user besides the compare (the select),
6407 // which would often largely negate the benefit of folding anyway.
6408 if (I.hasOneUse())
6409 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6410 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6411 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6412 return 0;
6413
6414 // See if we are doing a comparison between a constant and an instruction that
6415 // can be folded into the comparison.
6416 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006417 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6418 // instruction, see if that instruction also has constants so that the
6419 // instruction can be folded into the icmp
6420 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6421 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6422 return Res;
6423 }
6424
6425 // Handle icmp with constant (but not simple integer constant) RHS
6426 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6427 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6428 switch (LHSI->getOpcode()) {
6429 case Instruction::GetElementPtr:
6430 if (RHSC->isNullValue()) {
6431 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6432 bool isAllZeros = true;
6433 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6434 if (!isa<Constant>(LHSI->getOperand(i)) ||
6435 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6436 isAllZeros = false;
6437 break;
6438 }
6439 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006440 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006441 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006442 }
6443 break;
6444
6445 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006446 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006447 // block. If in the same block, we're encouraging jump threading. If
6448 // not, we are just pessimizing the code by making an i1 phi.
6449 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006450 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006451 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006452 break;
6453 case Instruction::Select: {
6454 // If either operand of the select is a constant, we can fold the
6455 // comparison into the select arms, which will cause one to be
6456 // constant folded and the select turned into a bitwise or.
6457 Value *Op1 = 0, *Op2 = 0;
Eli Friedman4779a952009-12-18 08:22:35 +00006458 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6459 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6460 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6461 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6462
6463 // We only want to perform this transformation if it will not lead to
6464 // additional code. This is true if either both sides of the select
6465 // fold to a constant (in which case the icmp is replaced with a select
6466 // which will usually simplify) or this is the only user of the
6467 // select (in which case we are trading a select+icmp for a simpler
6468 // select+icmp).
6469 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6470 if (!Op1)
Chris Lattnerc7694852009-08-30 07:44:24 +00006471 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6472 RHSC, I.getName());
Eli Friedman4779a952009-12-18 08:22:35 +00006473 if (!Op2)
6474 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6475 RHSC, I.getName());
Gabor Greifd6da1d02008-04-06 20:25:17 +00006476 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman4779a952009-12-18 08:22:35 +00006477 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006478 break;
6479 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006480 case Instruction::Call:
6481 // If we have (malloc != null), and if the malloc has a single use, we
6482 // can assume it is successful and remove the malloc.
6483 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6484 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006485 // Need to explicitly erase malloc call here, instead of adding it to
6486 // Worklist, because it won't get DCE'd from the Worklist since
6487 // isInstructionTriviallyDead() returns false for function calls.
6488 // It is OK to replace LHSI/MallocCall with Undef because the
6489 // instruction that uses it will be erased via Worklist.
6490 if (extractMallocCall(LHSI)) {
6491 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6492 EraseInstFromFunction(*LHSI);
6493 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006494 ConstantInt::get(Type::getInt1Ty(*Context),
6495 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006496 }
6497 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6498 if (MallocCall->hasOneUse()) {
6499 MallocCall->replaceAllUsesWith(
6500 UndefValue::get(MallocCall->getType()));
6501 EraseInstFromFunction(*MallocCall);
6502 Worklist.Add(LHSI); // The malloc's bitcast use.
6503 return ReplaceInstUsesWith(I,
6504 ConstantInt::get(Type::getInt1Ty(*Context),
6505 !I.isTrueWhenEqual()));
6506 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006507 }
6508 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006509 }
6510 }
6511
6512 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006513 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006514 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6515 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006516 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006517 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6518 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6519 return NI;
6520
6521 // Test to see if the operands of the icmp are casted versions of other
6522 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6523 // now.
6524 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6525 if (isa<PointerType>(Op0->getType()) &&
6526 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6527 // We keep moving the cast from the left operand over to the right
6528 // operand, where it can often be eliminated completely.
6529 Op0 = CI->getOperand(0);
6530
6531 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6532 // so eliminate it as well.
6533 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6534 Op1 = CI2->getOperand(0);
6535
6536 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006537 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006538 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006539 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006540 } else {
6541 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006542 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006543 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006544 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006545 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006546 }
6547 }
6548
6549 if (isa<CastInst>(Op0)) {
6550 // Handle the special case of: icmp (cast bool to X), <cst>
6551 // This comes up when you have code like
6552 // int X = A < B;
6553 // if (X) ...
6554 // For generality, we handle any zero-extension of any operand comparison
6555 // with a constant or another cast from the same type.
Eli Friedmanbb8954b2009-12-17 21:27:47 +00006556 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6558 return R;
6559 }
6560
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006561 // See if it's the same type of instruction on the left and right.
6562 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6563 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006564 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006565 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006566 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006567 default: break;
6568 case Instruction::Add:
6569 case Instruction::Sub:
6570 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006571 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006572 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006573 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006574 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6575 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6576 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006577 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006578 ? I.getUnsignedPredicate()
6579 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006580 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006581 Op1I->getOperand(0));
6582 }
6583
6584 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006585 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006586 ? I.getUnsignedPredicate()
6587 : I.getSignedPredicate();
6588 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006589 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006590 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006591 }
6592 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006593 break;
6594 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006595 if (!I.isEquality())
6596 break;
6597
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006598 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6599 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6600 // Mask = -1 >> count-trailing-zeros(Cst).
6601 if (!CI->isZero() && !CI->isOne()) {
6602 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006603 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006604 APInt::getLowBitsSet(AP.getBitWidth(),
6605 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006606 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006607 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6608 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006609 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006610 }
6611 }
6612 break;
6613 }
6614 }
6615 }
6616 }
6617
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006618 // ~x < ~y --> y < x
6619 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006620 if (match(Op0, m_Not(m_Value(A))) &&
6621 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006622 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006623 }
6624
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006625 if (I.isEquality()) {
6626 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006627
6628 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006629 if (match(Op0, m_Neg(m_Value(A))) &&
6630 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006631 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006632
Dan Gohmancdff2122009-08-12 16:23:25 +00006633 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6635 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006636 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006637 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006638 }
6639
Dan Gohmancdff2122009-08-12 16:23:25 +00006640 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006641 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006642 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006643 if (match(B, m_ConstantInt(C1)) &&
6644 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006645 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006646 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006647 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6648 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006649 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006650
6651 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006652 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6653 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6654 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6655 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 }
6657 }
6658
Dan Gohmancdff2122009-08-12 16:23:25 +00006659 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006660 (A == Op0 || B == Op0)) {
6661 // A == (A^B) -> B == 0
6662 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006663 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006664 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006665 }
Chris Lattner3b874082008-11-16 05:38:51 +00006666
6667 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006668 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006669 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006670 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006671
6672 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006673 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006674 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006675 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006676
6677 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6678 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006679 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6680 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006681 Value *X = 0, *Y = 0, *Z = 0;
6682
6683 if (A == C) {
6684 X = B; Y = D; Z = A;
6685 } else if (A == D) {
6686 X = B; Y = C; Z = A;
6687 } else if (B == C) {
6688 X = A; Y = D; Z = B;
6689 } else if (B == D) {
6690 X = A; Y = C; Z = B;
6691 }
6692
6693 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006694 Op1 = Builder->CreateXor(X, Y, "tmp");
6695 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006696 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006697 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006698 return &I;
6699 }
6700 }
6701 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006702
6703 {
6704 Value *X; ConstantInt *Cst;
Chris Lattnera54b96b2009-12-21 04:04:05 +00006705 // icmp X+Cst, X
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006706 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattnera54b96b2009-12-21 04:04:05 +00006707 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6708
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006709 // icmp X, X+Cst
6710 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattnera54b96b2009-12-21 04:04:05 +00006711 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006712 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006713 return Changed ? &I : 0;
6714}
6715
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006716/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6717Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6718 Value *X, ConstantInt *CI,
Chris Lattnera54b96b2009-12-21 04:04:05 +00006719 ICmpInst::Predicate Pred,
6720 Value *TheAdd) {
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006721 // If we have X+0, exit early (simplifying logic below) and let it get folded
6722 // elsewhere. icmp X+0, X -> icmp X, X
6723 if (CI->isZero()) {
6724 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6725 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6726 }
6727
6728 // (X+4) == X -> false.
6729 if (Pred == ICmpInst::ICMP_EQ)
6730 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6731
6732 // (X+4) != X -> true.
6733 if (Pred == ICmpInst::ICMP_NE)
6734 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006735
6736 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6737 bool isNUW = false, isNSW = false;
6738 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6739 isNUW = Add->hasNoUnsignedWrap();
6740 isNSW = Add->hasNoSignedWrap();
6741 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006742
6743 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6744 // so the values can never be equal. Similiarly for all other "or equals"
6745 // operators.
6746
6747 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6748 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6749 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6750 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattnera54b96b2009-12-21 04:04:05 +00006751 // If this is an NUW add, then this is always false.
6752 if (isNUW)
6753 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6754
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006755 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6756 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6757 }
6758
6759 // (X+1) >u X --> X <u (0-1) --> X != 255
6760 // (X+2) >u X --> X <u (0-2) --> X <u 254
6761 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattnera54b96b2009-12-21 04:04:05 +00006762 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6763 // If this is an NUW add, then this is always true.
6764 if (isNUW)
6765 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006766 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006767 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006768
6769 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6770 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6771 APInt::getSignedMaxValue(BitWidth));
6772
6773 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6774 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6775 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6776 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6777 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6778 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattnera54b96b2009-12-21 04:04:05 +00006779 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6780 // If this is an NSW add, then we have two cases: if the constant is
6781 // positive, then this is always false, if negative, this is always true.
6782 if (isNSW) {
6783 bool isTrue = CI->getValue().isNegative();
6784 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6785 }
6786
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006787 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006788 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006789
6790 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6791 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6792 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6793 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6794 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6795 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattnera54b96b2009-12-21 04:04:05 +00006796
6797 // If this is an NSW add, then we have two cases: if the constant is
6798 // positive, then this is always true, if negative, this is always false.
6799 if (isNSW) {
6800 bool isTrue = !CI->getValue().isNegative();
6801 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6802 }
6803
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006804 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6805 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6806 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6807}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006808
6809/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6810/// and CmpRHS are both known to be integer constants.
6811Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6812 ConstantInt *DivRHS) {
6813 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6814 const APInt &CmpRHSV = CmpRHS->getValue();
6815
6816 // FIXME: If the operand types don't match the type of the divide
6817 // then don't attempt this transform. The code below doesn't have the
6818 // logic to deal with a signed divide and an unsigned compare (and
6819 // vice versa). This is because (x /s C1) <s C2 produces different
6820 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6821 // (x /u C1) <u C2. Simply casting the operands and result won't
6822 // work. :( The if statement below tests that condition and bails
6823 // if it finds it.
6824 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006825 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006826 return 0;
6827 if (DivRHS->isZero())
6828 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006829 if (DivIsSigned && DivRHS->isAllOnesValue())
6830 return 0; // The overflow computation also screws up here
6831 if (DivRHS->isOne())
6832 return 0; // Not worth bothering, and eliminates some funny cases
6833 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006834
6835 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6836 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6837 // C2 (CI). By solving for X we can turn this into a range check
6838 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006839 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006840
6841 // Determine if the product overflows by seeing if the product is
6842 // not equal to the divide. Make sure we do the same kind of divide
6843 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006844 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6845 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006846
6847 // Get the ICmp opcode
6848 ICmpInst::Predicate Pred = ICI.getPredicate();
6849
6850 // Figure out the interval that is being checked. For example, a comparison
6851 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6852 // Compute this interval based on the constants involved and the signedness of
6853 // the compare/divide. This computes a half-open interval, keeping track of
6854 // whether either value in the interval overflows. After analysis each
6855 // overflow variable is set to 0 if it's corresponding bound variable is valid
6856 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6857 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006858 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006859
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006860 if (!DivIsSigned) { // udiv
6861 // e.g. X/5 op 3 --> [15, 20)
6862 LoBound = Prod;
6863 HiOverflow = LoOverflow = ProdOV;
6864 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006865 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006866 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006867 if (CmpRHSV == 0) { // (X / pos) op 0
6868 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006869 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006870 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006871 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006872 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6873 HiOverflow = LoOverflow = ProdOV;
6874 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006875 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006876 } else { // (X / pos) op neg
6877 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006878 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006879 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6880 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006881 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006882 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006883 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006884 true) ? -1 : 0;
6885 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006886 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006887 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006888 if (CmpRHSV == 0) { // (X / neg) op 0
6889 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006890 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006891 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006892 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6893 HiOverflow = 1; // [INTMIN+1, overflow)
6894 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6895 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006896 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006897 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006898 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006899 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6900 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006901 LoOverflow = AddWithOverflow(LoBound, HiBound,
6902 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006903 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006904 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6905 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006906 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006907 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006908 }
6909
6910 // Dividing by a negative swaps the condition. LT <-> GT
6911 Pred = ICmpInst::getSwappedPredicate(Pred);
6912 }
6913
6914 Value *X = DivI->getOperand(0);
6915 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006916 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006917 case ICmpInst::ICMP_EQ:
6918 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006919 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006920 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006921 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006922 ICmpInst::ICMP_UGE, X, LoBound);
6923 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006924 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006925 ICmpInst::ICMP_ULT, X, HiBound);
6926 else
6927 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6928 case ICmpInst::ICMP_NE:
6929 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006930 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006931 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006932 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006933 ICmpInst::ICMP_ULT, X, LoBound);
6934 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006935 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006936 ICmpInst::ICMP_UGE, X, HiBound);
6937 else
6938 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6939 case ICmpInst::ICMP_ULT:
6940 case ICmpInst::ICMP_SLT:
6941 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006942 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006943 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006944 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006945 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006946 case ICmpInst::ICMP_UGT:
6947 case ICmpInst::ICMP_SGT:
6948 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006949 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006950 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006951 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006952 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006953 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006954 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006955 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006956 }
6957}
6958
6959
6960/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6961///
6962Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6963 Instruction *LHSI,
6964 ConstantInt *RHS) {
6965 const APInt &RHSV = RHS->getValue();
6966
6967 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006968 case Instruction::Trunc:
6969 if (ICI.isEquality() && LHSI->hasOneUse()) {
6970 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6971 // of the high bits truncated out of x are known.
6972 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6973 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6974 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6975 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6976 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6977
6978 // If all the high bits are known, we can do this xform.
6979 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6980 // Pull in the high bits from known-ones set.
6981 APInt NewRHS(RHS->getValue());
6982 NewRHS.zext(SrcBits);
6983 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006984 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006985 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006986 }
6987 }
6988 break;
6989
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006990 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6991 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6992 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6993 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006994 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6995 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006996 Value *CompareVal = LHSI->getOperand(0);
6997
6998 // If the sign bit of the XorCST is not set, there is no change to
6999 // the operation, just stop using the Xor.
7000 if (!XorCST->getValue().isNegative()) {
7001 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00007002 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007003 return &ICI;
7004 }
7005
7006 // Was the old condition true if the operand is positive?
7007 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7008
7009 // If so, the new one isn't.
7010 isTrueIfPositive ^= true;
7011
7012 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00007013 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007014 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007015 else
Dan Gohmane6803b82009-08-25 23:17:54 +00007016 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007017 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007018 }
Nick Lewyckydac84332009-01-31 21:30:05 +00007019
7020 if (LHSI->hasOneUse()) {
7021 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7022 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7023 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007024 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00007025 ? ICI.getUnsignedPredicate()
7026 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00007027 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007028 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00007029 }
7030
7031 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00007032 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00007033 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007034 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00007035 ? ICI.getUnsignedPredicate()
7036 : ICI.getSignedPredicate();
7037 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00007038 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007039 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00007040 }
7041 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007042 }
7043 break;
7044 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7045 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7046 LHSI->getOperand(0)->hasOneUse()) {
7047 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7048
7049 // If the LHS is an AND of a truncating cast, we can widen the
7050 // and/compare to be the input width without changing the value
7051 // produced, eliminating a cast.
7052 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7053 // We can do this transformation if either the AND constant does not
7054 // have its sign bit set or if it is an equality comparison.
7055 // Extending a relational comparison when we're checking the sign
7056 // bit would not work.
7057 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00007058 (ICI.isEquality() ||
7059 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007060 uint32_t BitWidth =
7061 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7062 APInt NewCST = AndCST->getValue();
7063 NewCST.zext(BitWidth);
7064 APInt NewCI = RHSV;
7065 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00007066 Value *NewAnd =
7067 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007068 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007069 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007070 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007071 }
7072 }
7073
7074 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7075 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7076 // happens a LOT in code produced by the C front-end, for bitfield
7077 // access.
7078 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7079 if (Shift && !Shift->isShift())
7080 Shift = 0;
7081
7082 ConstantInt *ShAmt;
7083 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7084 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7085 const Type *AndTy = AndCST->getType(); // Type of the and.
7086
7087 // We can fold this as long as we can't shift unknown bits
7088 // into the mask. This can only happen with signed shift
7089 // rights, as they sign-extend.
7090 if (ShAmt) {
7091 bool CanFold = Shift->isLogicalShift();
7092 if (!CanFold) {
7093 // To test for the bad case of the signed shr, see if any
7094 // of the bits shifted in could be tested after the mask.
7095 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7096 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7097
7098 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7099 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7100 AndCST->getValue()) == 0)
7101 CanFold = true;
7102 }
7103
7104 if (CanFold) {
7105 Constant *NewCst;
7106 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00007107 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007108 else
Owen Anderson02b48c32009-07-29 18:55:55 +00007109 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007110
7111 // Check to see if we are shifting out any of the bits being
7112 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00007113 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007114 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007115 // If we shifted bits out, the fold is not going to work out.
7116 // As a special case, check to see if this means that the
7117 // result is always true or false now.
7118 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007119 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007120 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007121 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007122 } else {
7123 ICI.setOperand(1, NewCst);
7124 Constant *NewAndCST;
7125 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00007126 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007127 else
Owen Anderson02b48c32009-07-29 18:55:55 +00007128 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007129 LHSI->setOperand(1, NewAndCST);
7130 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00007131 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007132 return &ICI;
7133 }
7134 }
7135 }
7136
7137 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7138 // preferable because it allows the C<<Y expression to be hoisted out
7139 // of a loop if Y is invariant and X is not.
7140 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00007141 ICI.isEquality() && !Shift->isArithmeticShift() &&
7142 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 // Compute C << Y.
7144 Value *NS;
7145 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007146 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 } else {
7148 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00007149 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007150 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007151
7152 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00007153 Value *NewAnd =
7154 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007155
7156 ICI.setOperand(0, NewAnd);
7157 return &ICI;
7158 }
7159 }
7160 break;
7161
7162 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7163 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7164 if (!ShAmt) break;
7165
7166 uint32_t TypeBits = RHSV.getBitWidth();
7167
7168 // Check that the shift amount is in range. If not, don't perform
7169 // undefined shifts. When the shift is visited it will be
7170 // simplified.
7171 if (ShAmt->uge(TypeBits))
7172 break;
7173
7174 if (ICI.isEquality()) {
7175 // If we are comparing against bits always shifted out, the
7176 // comparison cannot succeed.
7177 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00007178 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00007179 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007180 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7181 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007182 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007183 return ReplaceInstUsesWith(ICI, Cst);
7184 }
7185
7186 if (LHSI->hasOneUse()) {
7187 // Otherwise strength reduce the shift into an and.
7188 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7189 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007190 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00007191 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192
Chris Lattnerc7694852009-08-30 07:44:24 +00007193 Value *And =
7194 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007195 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007196 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007197 }
7198 }
7199
7200 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7201 bool TrueIfSigned = false;
7202 if (LHSI->hasOneUse() &&
7203 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7204 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00007205 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007206 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00007207 Value *And =
7208 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007209 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00007210 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007211 }
7212 break;
7213 }
7214
7215 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
7216 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007217 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007218 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007219 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007220
Chris Lattner5ee84f82008-03-21 05:19:58 +00007221 // Check that the shift amount is in range. If not, don't perform
7222 // undefined shifts. When the shift is visited it will be
7223 // simplified.
7224 uint32_t TypeBits = RHSV.getBitWidth();
7225 if (ShAmt->uge(TypeBits))
7226 break;
7227
7228 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007229
Chris Lattner5ee84f82008-03-21 05:19:58 +00007230 // If we are comparing against bits always shifted out, the
7231 // comparison cannot succeed.
7232 APInt Comp = RHSV << ShAmtVal;
7233 if (LHSI->getOpcode() == Instruction::LShr)
7234 Comp = Comp.lshr(ShAmtVal);
7235 else
7236 Comp = Comp.ashr(ShAmtVal);
7237
7238 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7239 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007240 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007241 return ReplaceInstUsesWith(ICI, Cst);
7242 }
7243
7244 // Otherwise, check to see if the bits shifted out are known to be zero.
7245 // If so, we can compare against the unshifted value:
7246 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007247 if (LHSI->hasOneUse() &&
7248 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007249 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007250 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007251 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007252 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007253
Evan Chengfb9292a2008-04-23 00:38:06 +00007254 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007255 // Otherwise strength reduce the shift into an and.
7256 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007257 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007258
Chris Lattnerc7694852009-08-30 07:44:24 +00007259 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7260 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007261 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007262 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007263 }
7264 break;
7265 }
7266
7267 case Instruction::SDiv:
7268 case Instruction::UDiv:
7269 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7270 // Fold this div into the comparison, producing a range check.
7271 // Determine, based on the divide type, what the range is being
7272 // checked. If there is an overflow on the low or high side, remember
7273 // it, otherwise compute the range [low, hi) bounding the new value.
7274 // See: InsertRangeTest above for the kinds of replacements possible.
7275 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7276 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7277 DivRHS))
7278 return R;
7279 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007280
7281 case Instruction::Add:
Chris Lattner258a2ffb2009-12-21 03:19:28 +00007282 // Fold: icmp pred (add X, C1), C2
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007283 if (!ICI.isEquality()) {
7284 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7285 if (!LHSC) break;
7286 const APInt &LHSV = LHSC->getValue();
7287
7288 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7289 .subtract(LHSV);
7290
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007291 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007292 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007293 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007294 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007295 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007296 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007297 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007298 }
7299 } else {
7300 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007301 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007302 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007303 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007304 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007305 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007306 }
7307 }
7308 }
7309 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007310 }
7311
7312 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7313 if (ICI.isEquality()) {
7314 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7315
7316 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7317 // the second operand is a constant, simplify a bit.
7318 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7319 switch (BO->getOpcode()) {
7320 case Instruction::SRem:
7321 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7322 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7323 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7324 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007325 Value *NewRem =
7326 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7327 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007328 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007329 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007330 }
7331 }
7332 break;
7333 case Instruction::Add:
7334 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7335 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7336 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007337 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007338 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007339 } else if (RHSV == 0) {
7340 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7341 // efficiently invertible, or if the add has just this one use.
7342 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7343
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007344 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007345 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007346 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007347 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007348 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007349 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007350 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007351 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007352 }
7353 }
7354 break;
7355 case Instruction::Xor:
7356 // For the xor case, we can xor two constants together, eliminating
7357 // the explicit xor.
7358 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007359 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007360 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007361
7362 // FALLTHROUGH
7363 case Instruction::Sub:
7364 // Replace (([sub|xor] A, B) != 0) with (A != B)
7365 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007366 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007367 BO->getOperand(1));
7368 break;
7369
7370 case Instruction::Or:
7371 // If bits are being or'd in that are not present in the constant we
7372 // are comparing against, then the comparison could never succeed!
7373 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007374 Constant *NotCI = ConstantExpr::getNot(RHS);
7375 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007376 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007377 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007378 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007379 }
7380 break;
7381
7382 case Instruction::And:
7383 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7384 // If bits are being compared against that are and'd out, then the
7385 // comparison can never succeed!
7386 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007387 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007388 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007389 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390
7391 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7392 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007393 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007394 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007395 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007396
7397 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007398 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007399 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007400 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007401 ICmpInst::Predicate pred = isICMP_NE ?
7402 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007403 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007404 }
7405
7406 // ((X & ~7) == 0) --> X < 8
7407 if (RHSV == 0 && isHighOnes(BOC)) {
7408 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007409 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007410 ICmpInst::Predicate pred = isICMP_NE ?
7411 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007412 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007413 }
7414 }
7415 default: break;
7416 }
7417 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7418 // Handle icmp {eq|ne} <intrinsic>, intcst.
7419 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007420 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007421 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007422 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007423 return &ICI;
7424 }
7425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007426 }
7427 return 0;
7428}
7429
7430/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7431/// We only handle extending casts so far.
7432///
7433Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7434 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7435 Value *LHSCIOp = LHSCI->getOperand(0);
7436 const Type *SrcTy = LHSCIOp->getType();
7437 const Type *DestTy = LHSCI->getType();
7438 Value *RHSCIOp;
7439
7440 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7441 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007442 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7443 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007444 cast<IntegerType>(DestTy)->getBitWidth()) {
7445 Value *RHSOp = 0;
7446 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007447 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007448 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7449 RHSOp = RHSC->getOperand(0);
7450 // If the pointer types don't match, insert a bitcast.
7451 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007452 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007453 }
7454
7455 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007456 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007457 }
7458
7459 // The code below only handles extension cast instructions, so far.
7460 // Enforce this.
7461 if (LHSCI->getOpcode() != Instruction::ZExt &&
7462 LHSCI->getOpcode() != Instruction::SExt)
7463 return 0;
7464
7465 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007466 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007467
7468 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7469 // Not an extension from the same type?
7470 RHSCIOp = CI->getOperand(0);
7471 if (RHSCIOp->getType() != LHSCIOp->getType())
7472 return 0;
7473
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007474 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007475 // and the other is a zext), then we can't handle this.
7476 if (CI->getOpcode() != LHSCI->getOpcode())
7477 return 0;
7478
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007479 // Deal with equality cases early.
7480 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007481 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007482
7483 // A signed comparison of sign extended values simplifies into a
7484 // signed comparison.
7485 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007486 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007487
7488 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007489 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007490 }
7491
7492 // If we aren't dealing with a constant on the RHS, exit early
7493 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7494 if (!CI)
7495 return 0;
7496
7497 // Compute the constant that would happen if we truncated to SrcTy then
7498 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007499 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7500 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007501 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502
7503 // If the re-extended constant didn't change...
7504 if (Res2 == CI) {
Eli Friedman96438472009-12-17 22:42:29 +00007505 // Deal with equality cases early.
7506 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007507 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedman96438472009-12-17 22:42:29 +00007508
7509 // A signed comparison of sign extended values simplifies into a
7510 // signed comparison.
7511 if (isSignedExt && isSignedCmp)
7512 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7513
7514 // The other three cases all fold into an unsigned comparison.
7515 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007516 }
7517
7518 // The re-extended constant changed so the constant cannot be represented
7519 // in the shorter type. Consequently, we cannot emit a simple comparison.
7520
7521 // First, handle some easy cases. We know the result cannot be equal at this
7522 // point so handle the ICI.isEquality() cases
7523 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007524 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007525 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007526 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007527
7528 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7529 // should have been folded away previously and not enter in here.
7530 Value *Result;
7531 if (isSignedCmp) {
7532 // We're performing a signed comparison.
7533 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007534 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007535 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007536 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007537 } else {
7538 // We're performing an unsigned comparison.
7539 if (isSignedExt) {
7540 // We're performing an unsigned comp with a sign extended value.
7541 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007542 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007543 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007544 } else {
7545 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007546 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007547 }
7548 }
7549
7550 // Finally, return the value computed.
7551 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007552 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007553 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007554
7555 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7556 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7557 "ICmp should be folded!");
7558 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007559 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007560 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007561}
7562
7563Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7564 return commonShiftTransforms(I);
7565}
7566
7567Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7568 return commonShiftTransforms(I);
7569}
7570
7571Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007572 if (Instruction *R = commonShiftTransforms(I))
7573 return R;
7574
7575 Value *Op0 = I.getOperand(0);
7576
7577 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7578 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7579 if (CSI->isAllOnesValue())
7580 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007581
Dan Gohman2526aea2009-06-16 19:55:29 +00007582 // See if we can turn a signed shr into an unsigned shr.
7583 if (MaskedValueIsZero(Op0,
7584 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7585 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7586
7587 // Arithmetic shifting an all-sign-bit value is a no-op.
7588 unsigned NumSignBits = ComputeNumSignBits(Op0);
7589 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7590 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007591
Chris Lattnere3c504f2007-12-06 01:59:46 +00007592 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007593}
7594
7595Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7596 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7597 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7598
7599 // shl X, 0 == X and shr X, 0 == X
7600 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007601 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7602 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603 return ReplaceInstUsesWith(I, Op0);
7604
7605 if (isa<UndefValue>(Op0)) {
7606 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7607 return ReplaceInstUsesWith(I, Op0);
7608 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007609 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007610 }
7611 if (isa<UndefValue>(Op1)) {
7612 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7613 return ReplaceInstUsesWith(I, Op0);
7614 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007615 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007616 }
7617
Dan Gohman2bc21562009-05-21 02:28:33 +00007618 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007619 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007620 return &I;
7621
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007622 // Try to fold constant and into select arguments.
7623 if (isa<Constant>(Op0))
7624 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7625 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7626 return R;
7627
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007628 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7629 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7630 return Res;
7631 return 0;
7632}
7633
7634Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7635 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007636 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637
7638 // See if we can simplify any instructions used by the instruction whose sole
7639 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007640 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007641
Dan Gohman9e1657f2009-06-14 23:30:43 +00007642 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7643 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007644 //
7645 if (Op1->uge(TypeBits)) {
7646 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007647 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007648 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007649 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007650 return &I;
7651 }
7652 }
7653
7654 // ((X*C1) << C2) == (X * (C1 << C2))
7655 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7656 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7657 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007658 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007659 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007660
7661 // Try to fold constant and into select arguments.
7662 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7663 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7664 return R;
7665 if (isa<PHINode>(Op0))
7666 if (Instruction *NV = FoldOpIntoPhi(I))
7667 return NV;
7668
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007669 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7670 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7671 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7672 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7673 // place. Don't try to do this transformation in this case. Also, we
7674 // require that the input operand is a shift-by-constant so that we have
7675 // confidence that the shifts will get folded together. We could do this
7676 // xform in more cases, but it is unlikely to be profitable.
7677 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7678 isa<ConstantInt>(TrOp->getOperand(1))) {
7679 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007680 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007681 // (shift2 (shift1 & 0x00FF), c2)
7682 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007683
7684 // For logical shifts, the truncation has the effect of making the high
7685 // part of the register be zeros. Emulate this by inserting an AND to
7686 // clear the top bits as needed. This 'and' will usually be zapped by
7687 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007688 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7689 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007690 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7691
7692 // The mask we constructed says what the trunc would do if occurring
7693 // between the shifts. We want to know the effect *after* the second
7694 // shift. We know that it is a logical shift by a constant, so adjust the
7695 // mask as appropriate.
7696 if (I.getOpcode() == Instruction::Shl)
7697 MaskV <<= Op1->getZExtValue();
7698 else {
7699 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7700 MaskV = MaskV.lshr(Op1->getZExtValue());
7701 }
7702
Chris Lattnerc7694852009-08-30 07:44:24 +00007703 // shift1 & 0x00FF
7704 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7705 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007706
7707 // Return the value truncated to the interesting size.
7708 return new TruncInst(And, I.getType());
7709 }
7710 }
7711
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007712 if (Op0->hasOneUse()) {
7713 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7714 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7715 Value *V1, *V2;
7716 ConstantInt *CC;
7717 switch (Op0BO->getOpcode()) {
7718 default: break;
7719 case Instruction::Add:
7720 case Instruction::And:
7721 case Instruction::Or:
7722 case Instruction::Xor: {
7723 // These operators commute.
7724 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7725 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007726 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007727 m_Specific(Op1)))) {
7728 Value *YS = // (Y << C)
7729 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7730 // (X + (Y << C))
7731 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7732 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007733 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007734 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007735 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7736 }
7737
7738 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7739 Value *Op0BOOp1 = Op0BO->getOperand(1);
7740 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7741 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007742 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007743 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007744 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007745 Value *YS = // (Y << C)
7746 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7747 Op0BO->getName());
7748 // X & (CC << C)
7749 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7750 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007751 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007752 }
7753 }
7754
7755 // FALL THROUGH.
7756 case Instruction::Sub: {
7757 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7758 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007759 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007760 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007761 Value *YS = // (Y << C)
7762 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7763 // (X + (Y << C))
7764 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7765 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007766 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007767 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007768 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7769 }
7770
7771 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7772 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7773 match(Op0BO->getOperand(0),
7774 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007775 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007776 cast<BinaryOperator>(Op0BO->getOperand(0))
7777 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007778 Value *YS = // (Y << C)
7779 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7780 // X & (CC << C)
7781 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7782 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007783
Gabor Greifa645dd32008-05-16 19:29:10 +00007784 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007785 }
7786
7787 break;
7788 }
7789 }
7790
7791
7792 // If the operand is an bitwise operator with a constant RHS, and the
7793 // shift is the only use, we can pull it out of the shift.
7794 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7795 bool isValid = true; // Valid only for And, Or, Xor
7796 bool highBitSet = false; // Transform if high bit of constant set?
7797
7798 switch (Op0BO->getOpcode()) {
7799 default: isValid = false; break; // Do not perform transform!
7800 case Instruction::Add:
7801 isValid = isLeftShift;
7802 break;
7803 case Instruction::Or:
7804 case Instruction::Xor:
7805 highBitSet = false;
7806 break;
7807 case Instruction::And:
7808 highBitSet = true;
7809 break;
7810 }
7811
7812 // If this is a signed shift right, and the high bit is modified
7813 // by the logical operation, do not perform the transformation.
7814 // The highBitSet boolean indicates the value of the high bit of
7815 // the constant which would cause it to be modified for this
7816 // operation.
7817 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007818 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007819 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007820
7821 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007822 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007823
Chris Lattnerad7516a2009-08-30 18:50:58 +00007824 Value *NewShift =
7825 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007826 NewShift->takeName(Op0BO);
7827
Gabor Greifa645dd32008-05-16 19:29:10 +00007828 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007829 NewRHS);
7830 }
7831 }
7832 }
7833 }
7834
7835 // Find out if this is a shift of a shift by a constant.
7836 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7837 if (ShiftOp && !ShiftOp->isShift())
7838 ShiftOp = 0;
7839
7840 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7841 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7842 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7843 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7844 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7845 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7846 Value *X = ShiftOp->getOperand(0);
7847
7848 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007849
7850 const IntegerType *Ty = cast<IntegerType>(I.getType());
7851
7852 // Check for (X << c1) << c2 and (X >> c1) >> c2
7853 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007854 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7855 // saturates.
7856 if (AmtSum >= TypeBits) {
7857 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007858 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007859 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7860 }
7861
Gabor Greifa645dd32008-05-16 19:29:10 +00007862 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007863 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007864 }
7865
7866 if (ShiftOp->getOpcode() == Instruction::LShr &&
7867 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007868 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007869 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007871 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007872 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007873 }
7874
7875 if (ShiftOp->getOpcode() == Instruction::AShr &&
7876 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007877 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007878 if (AmtSum >= TypeBits)
7879 AmtSum = TypeBits-1;
7880
Chris Lattnerad7516a2009-08-30 18:50:58 +00007881 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007882
7883 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007884 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885 }
7886
7887 // Okay, if we get here, one shift must be left, and the other shift must be
7888 // right. See if the amounts are equal.
7889 if (ShiftAmt1 == ShiftAmt2) {
7890 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7891 if (I.getOpcode() == Instruction::Shl) {
7892 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007893 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007894 }
7895 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7896 if (I.getOpcode() == Instruction::LShr) {
7897 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007898 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007899 }
7900 // We can simplify ((X << C) >>s C) into a trunc + sext.
7901 // NOTE: we could do this for any C, but that would make 'unusual' integer
7902 // types. For now, just stick to ones well-supported by the code
7903 // generators.
7904 const Type *SExtType = 0;
7905 switch (Ty->getBitWidth() - ShiftAmt1) {
7906 case 1 :
7907 case 8 :
7908 case 16 :
7909 case 32 :
7910 case 64 :
7911 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007912 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007913 break;
7914 default: break;
7915 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007916 if (SExtType)
7917 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007918 // Otherwise, we can't handle it yet.
7919 } else if (ShiftAmt1 < ShiftAmt2) {
7920 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7921
7922 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7923 if (I.getOpcode() == Instruction::Shl) {
7924 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7925 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007926 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007927
7928 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007929 return BinaryOperator::CreateAnd(Shift,
7930 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007931 }
7932
7933 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7934 if (I.getOpcode() == Instruction::LShr) {
7935 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007936 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007937
7938 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007939 return BinaryOperator::CreateAnd(Shift,
7940 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007941 }
7942
7943 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7944 } else {
7945 assert(ShiftAmt2 < ShiftAmt1);
7946 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7947
7948 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7949 if (I.getOpcode() == Instruction::Shl) {
7950 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7951 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007952 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7953 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007954
7955 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007956 return BinaryOperator::CreateAnd(Shift,
7957 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958 }
7959
7960 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7961 if (I.getOpcode() == Instruction::LShr) {
7962 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007963 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007964
7965 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007966 return BinaryOperator::CreateAnd(Shift,
7967 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007968 }
7969
7970 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7971 }
7972 }
7973 return 0;
7974}
7975
7976
7977/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7978/// expression. If so, decompose it, returning some value X, such that Val is
7979/// X*Scale+Offset.
7980///
7981static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007982 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007983 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7984 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7986 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007987 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007988 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007989 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7990 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7991 if (I->getOpcode() == Instruction::Shl) {
7992 // This is a value scaled by '1 << the shift amt'.
7993 Scale = 1U << RHS->getZExtValue();
7994 Offset = 0;
7995 return I->getOperand(0);
7996 } else if (I->getOpcode() == Instruction::Mul) {
7997 // This value is scaled by 'RHS'.
7998 Scale = RHS->getZExtValue();
7999 Offset = 0;
8000 return I->getOperand(0);
8001 } else if (I->getOpcode() == Instruction::Add) {
8002 // We have X+C. Check to see if we really have (X*C2)+C1,
8003 // where C1 is divisible by C2.
8004 unsigned SubScale;
8005 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00008006 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8007 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00008008 Offset += RHS->getZExtValue();
8009 Scale = SubScale;
8010 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008011 }
8012 }
8013 }
8014
8015 // Otherwise, we can't look past this.
8016 Scale = 1;
8017 Offset = 0;
8018 return Val;
8019}
8020
8021
8022/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8023/// try to eliminate the cast by moving the type information into the alloc.
8024Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00008025 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008026 const PointerType *PTy = cast<PointerType>(CI.getType());
8027
Chris Lattnerad7516a2009-08-30 18:50:58 +00008028 BuilderTy AllocaBuilder(*Builder);
8029 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8030
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 // Remove any uses of AI that are dead.
8032 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
8033
8034 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8035 Instruction *User = cast<Instruction>(*UI++);
8036 if (isInstructionTriviallyDead(User)) {
8037 while (UI != E && *UI == User)
8038 ++UI; // If this instruction uses AI more than once, don't break UI.
8039
8040 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00008041 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008042 EraseInstFromFunction(*User);
8043 }
8044 }
Dan Gohmana80e2712009-07-21 23:21:54 +00008045
8046 // This requires TargetData to get the alloca alignment and size information.
8047 if (!TD) return 0;
8048
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008049 // Get the type really allocated and the type casted to.
8050 const Type *AllocElTy = AI.getAllocatedType();
8051 const Type *CastElTy = PTy->getElementType();
8052 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
8053
8054 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8055 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
8056 if (CastElTyAlign < AllocElTyAlign) return 0;
8057
8058 // If the allocation has multiple uses, only promote it if we are strictly
8059 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00008060 // same, we open the door to infinite loops of various kinds. (A reference
8061 // from a dbg.declare doesn't count as a use for this purpose.)
8062 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8063 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008064
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008065 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8066 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008067 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
8068
8069 // See if we can satisfy the modulus by pulling a scale out of the array
8070 // size argument.
8071 unsigned ArraySizeScale;
8072 int ArrayOffset;
8073 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00008074 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8075 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008076
8077 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8078 // do the xform.
8079 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8080 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
8081
8082 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8083 Value *Amt = 0;
8084 if (Scale == 1) {
8085 Amt = NumElements;
8086 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00008087 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008088 // Insert before the alloca, not before the cast.
8089 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008090 }
8091
8092 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00008093 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008094 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008095 }
8096
Victor Hernandezb1687302009-10-23 21:09:37 +00008097 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008098 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008099 New->takeName(&AI);
8100
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00008101 // If the allocation has one real use plus a dbg.declare, just remove the
8102 // declare.
8103 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8104 EraseInstFromFunction(*DI);
8105 }
8106 // If the allocation has multiple real uses, insert a cast and change all
8107 // things that used it to use the new cast. This will also hack on CI, but it
8108 // will die soon.
8109 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008110 // New is the allocation instruction, pointer typed. AI is the original
8111 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008112 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008113 AI.replaceAllUsesWith(NewCast);
8114 }
8115 return ReplaceInstUsesWith(CI, New);
8116}
8117
8118/// CanEvaluateInDifferentType - Return true if we can take the specified value
8119/// and return it as type Ty without inserting any new casts and without
8120/// changing the computed value. This is used by code that tries to decide
8121/// whether promoting or shrinking integer operations to wider or smaller types
8122/// will allow us to eliminate a truncate or extend.
8123///
8124/// This is a truncation operation if Ty is smaller than V->getType(), or an
8125/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00008126///
8127/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8128/// should return true if trunc(V) can be computed by computing V in the smaller
8129/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8130/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8131/// efficiently truncated.
8132///
8133/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8134/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8135/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008136bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00008137 unsigned CastOpc,
8138 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008139 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008140 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008141 return true;
8142
8143 Instruction *I = dyn_cast<Instruction>(V);
8144 if (!I) return false;
8145
Dan Gohman8fd520a2009-06-15 22:12:54 +00008146 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008147
Chris Lattneref70bb82007-08-02 06:11:14 +00008148 // If this is an extension or truncate, we can often eliminate it.
8149 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8150 // If this is a cast from the destination type, we can trivially eliminate
8151 // it, and this will remove a cast overall.
8152 if (I->getOperand(0)->getType() == Ty) {
8153 // If the first operand is itself a cast, and is eliminable, do not count
8154 // this as an eliminable cast. We would prefer to eliminate those two
8155 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00008156 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00008157 ++NumCastsRemoved;
8158 return true;
8159 }
8160 }
8161
8162 // We can't extend or shrink something that has multiple uses: doing so would
8163 // require duplicating the instruction in general, which isn't profitable.
8164 if (!I->hasOneUse()) return false;
8165
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008166 unsigned Opc = I->getOpcode();
8167 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008168 case Instruction::Add:
8169 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008170 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008171 case Instruction::And:
8172 case Instruction::Or:
8173 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008174 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00008175 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008176 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00008177 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008178 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008179
Eli Friedman08c45bc2009-07-13 22:46:01 +00008180 case Instruction::UDiv:
8181 case Instruction::URem: {
8182 // UDiv and URem can be truncated if all the truncated bits are zero.
8183 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8184 uint32_t BitWidth = Ty->getScalarSizeInBits();
8185 if (BitWidth < OrigBitWidth) {
8186 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8187 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8188 MaskedValueIsZero(I->getOperand(1), Mask)) {
8189 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8190 NumCastsRemoved) &&
8191 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8192 NumCastsRemoved);
8193 }
8194 }
8195 break;
8196 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008197 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008198 // If we are truncating the result of this SHL, and if it's a shift of a
8199 // constant amount, we can always perform a SHL in a smaller type.
8200 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008201 uint32_t BitWidth = Ty->getScalarSizeInBits();
8202 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008203 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008204 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008205 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008206 }
8207 break;
8208 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008209 // If this is a truncate of a logical shr, we can truncate it to a smaller
8210 // lshr iff we know that the bits we would otherwise be shifting in are
8211 // already zeros.
8212 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008213 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8214 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008215 if (BitWidth < OrigBitWidth &&
8216 MaskedValueIsZero(I->getOperand(0),
8217 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8218 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008219 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008220 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008221 }
8222 }
8223 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008224 case Instruction::ZExt:
8225 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008226 case Instruction::Trunc:
8227 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008228 // can safely replace it. Note that replacing it does not reduce the number
8229 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008230 if (Opc == CastOpc)
8231 return true;
8232
8233 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008234 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008235 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008236 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008237 case Instruction::Select: {
8238 SelectInst *SI = cast<SelectInst>(I);
8239 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008240 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008241 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008242 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008243 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008244 case Instruction::PHI: {
8245 // We can change a phi if we can change all operands.
8246 PHINode *PN = cast<PHINode>(I);
8247 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8248 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008249 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008250 return false;
8251 return true;
8252 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008253 default:
8254 // TODO: Can handle more cases here.
8255 break;
8256 }
8257
8258 return false;
8259}
8260
8261/// EvaluateInDifferentType - Given an expression that
8262/// CanEvaluateInDifferentType returns true for, actually insert the code to
8263/// evaluate the expression.
8264Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8265 bool isSigned) {
8266 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008267 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008268
8269 // Otherwise, it must be an instruction.
8270 Instruction *I = cast<Instruction>(V);
8271 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008272 unsigned Opc = I->getOpcode();
8273 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008274 case Instruction::Add:
8275 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008276 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008277 case Instruction::And:
8278 case Instruction::Or:
8279 case Instruction::Xor:
8280 case Instruction::AShr:
8281 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008282 case Instruction::Shl:
8283 case Instruction::UDiv:
8284 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008285 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8286 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008287 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008288 break;
8289 }
8290 case Instruction::Trunc:
8291 case Instruction::ZExt:
8292 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008293 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008294 // just return the source. There's no need to insert it because it is not
8295 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296 if (I->getOperand(0)->getType() == Ty)
8297 return I->getOperand(0);
8298
Chris Lattner4200c2062008-06-18 04:00:49 +00008299 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008300 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008301 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008302 case Instruction::Select: {
8303 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8304 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8305 Res = SelectInst::Create(I->getOperand(0), True, False);
8306 break;
8307 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008308 case Instruction::PHI: {
8309 PHINode *OPN = cast<PHINode>(I);
8310 PHINode *NPN = PHINode::Create(Ty);
8311 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8312 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8313 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8314 }
8315 Res = NPN;
8316 break;
8317 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 default:
8319 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008320 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008321 break;
8322 }
8323
Chris Lattner4200c2062008-06-18 04:00:49 +00008324 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 return InsertNewInstBefore(Res, *I);
8326}
8327
8328/// @brief Implement the transforms common to all CastInst visitors.
8329Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8330 Value *Src = CI.getOperand(0);
8331
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008332 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8333 // eliminate it now.
8334 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8335 if (Instruction::CastOps opc =
8336 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8337 // The first cast (CSrc) is eliminable so we need to fix up or replace
8338 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008339 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008340 }
8341 }
8342
8343 // If we are casting a select then fold the cast into the select
8344 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8345 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8346 return NV;
8347
8348 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00008349 if (isa<PHINode>(Src)) {
8350 // We don't do this if this would create a PHI node with an illegal type if
8351 // it is currently legal.
8352 if (!isa<IntegerType>(Src->getType()) ||
8353 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerd0011092009-11-10 07:23:37 +00008354 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008355 if (Instruction *NV = FoldOpIntoPhi(CI))
8356 return NV;
Chris Lattner1cd526b2009-11-08 19:23:30 +00008357 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008358
8359 return 0;
8360}
8361
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008362/// FindElementAtOffset - Given a type and a constant offset, determine whether
8363/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008364/// the specified offset. If so, fill them into NewIndices and return the
8365/// resultant element type, otherwise return null.
8366static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8367 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008368 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008369 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008370 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008371 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008372
8373 // Start with the index over the outer type. Note that the type size
8374 // might be zero (even if the offset isn't zero) if the indexed type
8375 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008376 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008377 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008378 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008379 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008380 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008381
Chris Lattnerce48c462009-01-11 20:15:20 +00008382 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008383 if (Offset < 0) {
8384 --FirstIdx;
8385 Offset += TySize;
8386 assert(Offset >= 0);
8387 }
8388 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8389 }
8390
Owen Andersoneacb44d2009-07-24 23:12:02 +00008391 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008392
8393 // Index into the types. If we fail, set OrigBase to null.
8394 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008395 // Indexing into tail padding between struct/array elements.
8396 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008397 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008398
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008399 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8400 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008401 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8402 "Offset must stay within the indexed type");
8403
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008404 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008405 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008406
8407 Offset -= SL->getElementOffset(Elt);
8408 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008409 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008410 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008411 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008412 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008413 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008414 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008415 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008416 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008417 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008418 }
8419 }
8420
Chris Lattner54dddc72009-01-24 01:00:13 +00008421 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008422}
8423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008424/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8425Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8426 Value *Src = CI.getOperand(0);
8427
8428 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8429 // If casting the result of a getelementptr instruction with no offset, turn
8430 // this into a cast of the original pointer!
8431 if (GEP->hasAllZeroIndices()) {
8432 // Changing the cast operand is usually not a good idea but it is safe
8433 // here because the pointer operand is being replaced with another
8434 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008435 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008436 CI.setOperand(0, GEP->getOperand(0));
8437 return &CI;
8438 }
8439
8440 // If the GEP has a single use, and the base pointer is a bitcast, and the
8441 // GEP computes a constant offset, see if we can convert these three
8442 // instructions into fewer. This typically happens with unions and other
8443 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008444 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008445 if (GEP->hasAllConstantIndices()) {
8446 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +00008447 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008448 int64_t Offset = OffsetV->getSExtValue();
8449
8450 // Get the base pointer input of the bitcast, and the type it points to.
8451 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8452 const Type *GEPIdxTy =
8453 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008454 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008455 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008456 // If we were able to index down into an element, create the GEP
8457 // and bitcast the result. This eliminates one bitcast, potentially
8458 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008459 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8460 Builder->CreateInBoundsGEP(OrigBase,
8461 NewIndices.begin(), NewIndices.end()) :
8462 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008463 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008464
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008465 if (isa<BitCastInst>(CI))
8466 return new BitCastInst(NGEP, CI.getType());
8467 assert(isa<PtrToIntInst>(CI));
8468 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008469 }
8470 }
8471 }
8472 }
8473
8474 return commonCastTransforms(CI);
8475}
8476
Eli Friedman827e37a2009-07-13 20:58:59 +00008477/// commonIntCastTransforms - This function implements the common transforms
8478/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008479Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8480 if (Instruction *Result = commonCastTransforms(CI))
8481 return Result;
8482
8483 Value *Src = CI.getOperand(0);
8484 const Type *SrcTy = Src->getType();
8485 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008486 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8487 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008488
8489 // See if we can simplify any instructions used by the LHS whose sole
8490 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008491 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008492 return &CI;
8493
8494 // If the source isn't an instruction or has more than one use then we
8495 // can't do anything more.
8496 Instruction *SrcI = dyn_cast<Instruction>(Src);
8497 if (!SrcI || !Src->hasOneUse())
8498 return 0;
8499
8500 // Attempt to propagate the cast into the instruction for int->int casts.
8501 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008502 // Only do this if the dest type is a simple type, don't convert the
8503 // expression tree to something weird like i93 unless the source is also
8504 // strange.
Chris Lattnerbc5d0132009-11-10 17:00:47 +00008505 if ((isa<VectorType>(DestTy) ||
8506 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8507 CanEvaluateInDifferentType(SrcI, DestTy,
8508 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008509 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008510 // eliminates the cast, so it is always a win. If this is a zero-extension,
8511 // we need to do an AND to maintain the clear top-part of the computation,
8512 // so we require that the input have eliminated at least one cast. If this
8513 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008514 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008515 bool DoXForm = false;
8516 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008517 switch (CI.getOpcode()) {
8518 default:
8519 // All the others use floating point so we shouldn't actually
8520 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008521 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008522 case Instruction::Trunc:
8523 DoXForm = true;
8524 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008525 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008526 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008527
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008528 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008529 // If it's unnecessary to issue an AND to clear the high bits, it's
8530 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008531 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008532 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8533 if (MaskedValueIsZero(TryRes, Mask))
8534 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008535
8536 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008537 if (TryI->use_empty())
8538 EraseInstFromFunction(*TryI);
8539 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008540 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008541 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008542 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008543 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008544 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008545 // If we do not have to emit the truncate + sext pair, then it's always
8546 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008547 //
8548 // It's not safe to eliminate the trunc + sext pair if one of the
8549 // eliminated cast is a truncate. e.g.
8550 // t2 = trunc i32 t1 to i16
8551 // t3 = sext i16 t2 to i32
8552 // !=
8553 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008554 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008555 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8556 if (NumSignBits > (DestBitSize - SrcBitSize))
8557 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008558
8559 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008560 if (TryI->use_empty())
8561 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008562 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008563 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008564 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008565 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008566
8567 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008568 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8569 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008570 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8571 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008572 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008573 // Just replace this cast with the result.
8574 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008575
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008576 assert(Res->getType() == DestTy);
8577 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008578 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008579 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008580 // Just replace this cast with the result.
8581 return ReplaceInstUsesWith(CI, Res);
8582 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008583 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008584
8585 // If the high bits are already zero, just replace this cast with the
8586 // result.
8587 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8588 if (MaskedValueIsZero(Res, Mask))
8589 return ReplaceInstUsesWith(CI, Res);
8590
8591 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008592 Constant *C = ConstantInt::get(*Context,
8593 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008594 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008595 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008596 case Instruction::SExt: {
8597 // If the high bits are already filled with sign bit, just replace this
8598 // cast with the result.
8599 unsigned NumSignBits = ComputeNumSignBits(Res);
8600 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008601 return ReplaceInstUsesWith(CI, Res);
8602
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008603 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008604 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008605 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008606 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008607 }
8608 }
8609
8610 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8611 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8612
8613 switch (SrcI->getOpcode()) {
8614 case Instruction::Add:
8615 case Instruction::Mul:
8616 case Instruction::And:
8617 case Instruction::Or:
8618 case Instruction::Xor:
8619 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008620 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8621 // Don't insert two casts unless at least one can be eliminated.
8622 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008623 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008624 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8625 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008626 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008627 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8628 }
8629 }
8630
8631 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8632 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8633 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008634 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008635 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008636 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008637 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008638 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008639 }
8640 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008641
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008642 case Instruction::Shl: {
8643 // Canonicalize trunc inside shl, if we can.
8644 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8645 if (CI && DestBitSize < SrcBitSize &&
8646 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008647 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8648 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008649 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008650 }
8651 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008652 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008653 }
8654 return 0;
8655}
8656
8657Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8658 if (Instruction *Result = commonIntCastTransforms(CI))
8659 return Result;
8660
8661 Value *Src = CI.getOperand(0);
8662 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008663 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8664 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008665
8666 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008667 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008668 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008669 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008670 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008671 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008672 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008673
Chris Lattner32177f82009-03-24 18:15:30 +00008674 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8675 ConstantInt *ShAmtV = 0;
8676 Value *ShiftOp = 0;
8677 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008678 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008679 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8680
8681 // Get a mask for the bits shifting in.
8682 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8683 if (MaskedValueIsZero(ShiftOp, Mask)) {
8684 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008685 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008686
8687 // Okay, we can shrink this. Truncate the input, then return a new
8688 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008689 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008690 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008691 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008692 }
8693 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008695 return 0;
8696}
8697
Evan Chenge3779cf2008-03-24 00:21:34 +00008698/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8699/// in order to eliminate the icmp.
8700Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8701 bool DoXform) {
8702 // If we are just checking for a icmp eq of a single bit and zext'ing it
8703 // to an integer, then shift the bit to the appropriate place and then
8704 // cast to integer to avoid the comparison.
8705 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8706 const APInt &Op1CV = Op1C->getValue();
8707
8708 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8709 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8710 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8711 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8712 if (!DoXform) return ICI;
8713
8714 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008715 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008716 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008717 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008718 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008719 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008720
8721 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008722 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008723 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008724 }
8725
8726 return ReplaceInstUsesWith(CI, In);
8727 }
8728
8729
8730
8731 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8732 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8733 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8734 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8735 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8736 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8737 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8738 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8739 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8740 // This only works for EQ and NE
8741 ICI->isEquality()) {
8742 // If Op1C some other power of two, convert:
8743 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8744 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8745 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8746 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8747
8748 APInt KnownZeroMask(~KnownZero);
8749 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8750 if (!DoXform) return ICI;
8751
8752 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8753 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8754 // (X&4) == 2 --> false
8755 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008756 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008757 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008758 return ReplaceInstUsesWith(CI, Res);
8759 }
8760
8761 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8762 Value *In = ICI->getOperand(0);
8763 if (ShiftAmt) {
8764 // Perform a logical shr by shiftamt.
8765 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008766 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8767 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008768 }
8769
8770 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008771 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008772 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008773 }
8774
8775 if (CI.getType() == In->getType())
8776 return ReplaceInstUsesWith(CI, In);
8777 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008778 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008779 }
8780 }
8781 }
8782
Nick Lewyckyef61f692009-11-23 03:17:33 +00008783 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8784 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8785 // may lead to additional simplifications.
8786 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8787 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8788 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008789 Value *LHS = ICI->getOperand(0);
8790 Value *RHS = ICI->getOperand(1);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008791
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008792 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8793 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8794 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8795 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8796 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008797
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008798 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8799 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8800 APInt UnknownBit = ~KnownBits;
8801 if (UnknownBit.countPopulation() == 1) {
Nick Lewyckyef61f692009-11-23 03:17:33 +00008802 if (!DoXform) return ICI;
8803
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008804 Value *Result = Builder->CreateXor(LHS, RHS);
8805
8806 // Mask off any bits that are set and won't be shifted away.
8807 if (KnownOneLHS.uge(UnknownBit))
8808 Result = Builder->CreateAnd(Result,
8809 ConstantInt::get(ITy, UnknownBit));
8810
8811 // Shift the bit we're testing down to the lsb.
8812 Result = Builder->CreateLShr(
8813 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8814
Nick Lewyckyef61f692009-11-23 03:17:33 +00008815 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008816 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8817 Result->takeName(ICI);
8818 return ReplaceInstUsesWith(CI, Result);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008819 }
8820 }
8821 }
8822 }
8823
Evan Chenge3779cf2008-03-24 00:21:34 +00008824 return 0;
8825}
8826
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008827Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8828 // If one of the common conversion will work ..
8829 if (Instruction *Result = commonIntCastTransforms(CI))
8830 return Result;
8831
8832 Value *Src = CI.getOperand(0);
8833
Chris Lattner215d56e2009-02-17 20:47:23 +00008834 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8835 // types and if the sizes are just right we can convert this into a logical
8836 // 'and' which will be much cheaper than the pair of casts.
8837 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8838 // Get the sizes of the types involved. We know that the intermediate type
8839 // will be smaller than A or C, but don't know the relation between A and C.
8840 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008841 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8842 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8843 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008844 // If we're actually extending zero bits, then if
8845 // SrcSize < DstSize: zext(a & mask)
8846 // SrcSize == DstSize: a & mask
8847 // SrcSize > DstSize: trunc(a) & mask
8848 if (SrcSize < DstSize) {
8849 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008850 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008851 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008852 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008853 }
8854
8855 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008856 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008857 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008858 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008859 }
8860 if (SrcSize > DstSize) {
8861 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008862 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008863 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008864 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008865 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008866 }
8867 }
8868
Evan Chenge3779cf2008-03-24 00:21:34 +00008869 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8870 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008871
Evan Chenge3779cf2008-03-24 00:21:34 +00008872 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8873 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8874 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8875 // of the (zext icmp) will be transformed.
8876 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8877 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8878 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8879 (transformZExtICmp(LHS, CI, false) ||
8880 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008881 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8882 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008883 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008884 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008885 }
8886
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008887 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008888 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8889 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8890 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8891 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008892 if (TI0->getType() == CI.getType())
8893 return
8894 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008895 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008896 }
8897
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008898 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8899 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8900 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8901 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8902 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8903 And->getOperand(1) == C)
8904 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8905 Value *TI0 = TI->getOperand(0);
8906 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008907 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008908 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008909 return BinaryOperator::CreateXor(NewAnd, ZC);
8910 }
8911 }
8912
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008913 return 0;
8914}
8915
8916Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8917 if (Instruction *I = commonIntCastTransforms(CI))
8918 return I;
8919
8920 Value *Src = CI.getOperand(0);
8921
Dan Gohman35b76162008-10-30 20:40:10 +00008922 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008923 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008924 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008925 Constant::getAllOnesValue(CI.getType()),
8926 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008927
8928 // See if the value being truncated is already sign extended. If so, just
8929 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008930 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008931 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008932 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8933 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8934 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008935 unsigned NumSignBits = ComputeNumSignBits(Op);
8936
8937 if (OpBits == DestBits) {
8938 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8939 // bits, it is already ready.
8940 if (NumSignBits > DestBits-MidBits)
8941 return ReplaceInstUsesWith(CI, Op);
8942 } else if (OpBits < DestBits) {
8943 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8944 // bits, just sext from i32.
8945 if (NumSignBits > OpBits-MidBits)
8946 return new SExtInst(Op, CI.getType(), "tmp");
8947 } else {
8948 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8949 // bits, just truncate to i32.
8950 if (NumSignBits > OpBits-MidBits)
8951 return new TruncInst(Op, CI.getType(), "tmp");
8952 }
8953 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008954
8955 // If the input is a shl/ashr pair of a same constant, then this is a sign
8956 // extension from a smaller value. If we could trust arbitrary bitwidth
8957 // integers, we could turn this into a truncate to the smaller bit and then
8958 // use a sext for the whole extension. Since we don't, look deeper and check
8959 // for a truncate. If the source and dest are the same type, eliminate the
8960 // trunc and extend and just do shifts. For example, turn:
8961 // %a = trunc i32 %i to i8
8962 // %b = shl i8 %a, 6
8963 // %c = ashr i8 %b, 6
8964 // %d = sext i8 %c to i32
8965 // into:
8966 // %a = shl i32 %i, 30
8967 // %d = ashr i32 %a, 30
8968 Value *A = 0;
8969 ConstantInt *BA = 0, *CA = 0;
8970 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008971 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008972 BA == CA && isa<TruncInst>(A)) {
8973 Value *I = cast<TruncInst>(A)->getOperand(0);
8974 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008975 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8976 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008977 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008978 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008979 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008980 return BinaryOperator::CreateAShr(I, ShAmtV);
8981 }
8982 }
8983
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008984 return 0;
8985}
8986
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008987/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8988/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008989static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008990 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008991 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008992 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008993 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8994 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008995 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008996 return 0;
8997}
8998
8999/// LookThroughFPExtensions - If this is an fp extension instruction, look
9000/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00009001static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009002 if (Instruction *I = dyn_cast<Instruction>(V))
9003 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00009004 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009005
9006 // If this value is a constant, return the constant in the smallest FP type
9007 // that can accurately represent it. This allows us to turn
9008 // (float)((double)X+2.0) into x+2.0f.
9009 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009010 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009011 return V; // No constant folding of this.
9012 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00009013 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009014 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00009015 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009016 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00009017 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009018 return V;
9019 // Don't try to shrink to various long double types.
9020 }
9021
9022 return V;
9023}
9024
9025Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9026 if (Instruction *I = commonCastTransforms(CI))
9027 return I;
9028
Dan Gohman7ce405e2009-06-04 22:49:04 +00009029 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009030 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00009031 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009032 // many builtins (sqrt, etc).
9033 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9034 if (OpI && OpI->hasOneUse()) {
9035 switch (OpI->getOpcode()) {
9036 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009037 case Instruction::FAdd:
9038 case Instruction::FSub:
9039 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009040 case Instruction::FDiv:
9041 case Instruction::FRem:
9042 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00009043 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9044 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009045 if (LHSTrunc->getType() != SrcTy &&
9046 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00009047 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009048 // If the source types were both smaller than the destination type of
9049 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00009050 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9051 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009052 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9053 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00009054 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009055 }
9056 }
9057 break;
9058 }
9059 }
9060 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009061}
9062
9063Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9064 return commonCastTransforms(CI);
9065}
9066
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009067Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00009068 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9069 if (OpI == 0)
9070 return commonCastTransforms(FI);
9071
9072 // fptoui(uitofp(X)) --> X
9073 // fptoui(sitofp(X)) --> X
9074 // This is safe if the intermediate type has enough bits in its mantissa to
9075 // accurately represent all values of X. For example, do not do this with
9076 // i64->float->i64. This is also safe for sitofp case, because any negative
9077 // 'X' value would cause an undefined result for the fptoui.
9078 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9079 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00009080 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00009081 OpI->getType()->getFPMantissaWidth())
9082 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009083
9084 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009085}
9086
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009087Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00009088 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9089 if (OpI == 0)
9090 return commonCastTransforms(FI);
9091
9092 // fptosi(sitofp(X)) --> X
9093 // fptosi(uitofp(X)) --> X
9094 // This is safe if the intermediate type has enough bits in its mantissa to
9095 // accurately represent all values of X. For example, do not do this with
9096 // i64->float->i64. This is also safe for sitofp case, because any negative
9097 // 'X' value would cause an undefined result for the fptoui.
9098 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9099 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00009100 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00009101 OpI->getType()->getFPMantissaWidth())
9102 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009103
9104 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009105}
9106
9107Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9108 return commonCastTransforms(CI);
9109}
9110
9111Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9112 return commonCastTransforms(CI);
9113}
9114
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009115Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9116 // If the destination integer type is smaller than the intptr_t type for
9117 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9118 // trunc to be exposed to other transforms. Don't do this for extending
9119 // ptrtoint's, because we don't know if the target sign or zero extends its
9120 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00009121 if (TD &&
9122 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009123 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9124 TD->getIntPtrType(CI.getContext()),
9125 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009126 return new TruncInst(P, CI.getType());
9127 }
9128
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009129 return commonPointerCastTransforms(CI);
9130}
9131
Chris Lattner7c1626482008-01-08 07:23:51 +00009132Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009133 // If the source integer type is larger than the intptr_t type for
9134 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9135 // allows the trunc to be exposed to other transforms. Don't do this for
9136 // extending inttoptr's, because we don't know if the target sign or zero
9137 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009138 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009139 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009140 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9141 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009142 return new IntToPtrInst(P, CI.getType());
9143 }
9144
Chris Lattner7c1626482008-01-08 07:23:51 +00009145 if (Instruction *I = commonCastTransforms(CI))
9146 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00009147
Chris Lattner7c1626482008-01-08 07:23:51 +00009148 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009149}
9150
9151Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9152 // If the operands are integer typed then apply the integer transforms,
9153 // otherwise just apply the common ones.
9154 Value *Src = CI.getOperand(0);
9155 const Type *SrcTy = Src->getType();
9156 const Type *DestTy = CI.getType();
9157
Eli Friedman5013d3f2009-07-13 20:53:00 +00009158 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009159 if (Instruction *I = commonPointerCastTransforms(CI))
9160 return I;
9161 } else {
9162 if (Instruction *Result = commonCastTransforms(CI))
9163 return Result;
9164 }
9165
9166
9167 // Get rid of casts from one type to the same type. These are useless and can
9168 // be replaced by the operand.
9169 if (DestTy == Src->getType())
9170 return ReplaceInstUsesWith(CI, Src);
9171
9172 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9173 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9174 const Type *DstElTy = DstPTy->getElementType();
9175 const Type *SrcElTy = SrcPTy->getElementType();
9176
Nate Begemandf5b3612008-03-31 00:22:16 +00009177 // If the address spaces don't match, don't eliminate the bitcast, which is
9178 // required for changing types.
9179 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9180 return 0;
9181
Victor Hernandez48c3c542009-09-18 22:35:49 +00009182 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009183 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00009184 // There is no need to modify malloc calls because it is their bitcast that
9185 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00009186 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009187 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9188 return V;
9189
9190 // If the source and destination are pointers, and this cast is equivalent
9191 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9192 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00009193 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009194 unsigned NumZeros = 0;
9195 while (SrcElTy != DstElTy &&
9196 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9197 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9198 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9199 ++NumZeros;
9200 }
9201
9202 // If we found a path from the src to dest, create the getelementptr now.
9203 if (SrcElTy == DstElTy) {
9204 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00009205 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9206 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009207 }
9208 }
9209
Eli Friedman1d31dee2009-07-18 23:06:53 +00009210 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9211 if (DestVTy->getNumElements() == 1) {
9212 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009213 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009214 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00009215 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009216 }
9217 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9218 }
9219 }
9220
9221 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9222 if (SrcVTy->getNumElements() == 1) {
9223 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009224 Value *Elem =
9225 Builder->CreateExtractElement(Src,
9226 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009227 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9228 }
9229 }
9230 }
9231
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009232 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9233 if (SVI->hasOneUse()) {
9234 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9235 // a bitconvert to a vector with the same # elts.
9236 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009237 cast<VectorType>(DestTy)->getNumElements() ==
9238 SVI->getType()->getNumElements() &&
9239 SVI->getType()->getNumElements() ==
9240 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009241 CastInst *Tmp;
9242 // If either of the operands is a cast from CI.getType(), then
9243 // evaluating the shuffle in the casted destination's type will allow
9244 // us to eliminate at least one cast.
9245 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9246 Tmp->getOperand(0)->getType() == DestTy) ||
9247 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9248 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009249 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9250 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009251 // Return a new shuffle vector. Use the same element ID's, as we
9252 // know the vector types match #elts.
9253 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9254 }
9255 }
9256 }
9257 }
9258 return 0;
9259}
9260
9261/// GetSelectFoldableOperands - We want to turn code that looks like this:
9262/// %C = or %A, %B
9263/// %D = select %cond, %C, %A
9264/// into:
9265/// %C = select %cond, %B, 0
9266/// %D = or %A, %C
9267///
9268/// Assuming that the specified instruction is an operand to the select, return
9269/// a bitmask indicating which operands of this instruction are foldable if they
9270/// equal the other incoming value of the select.
9271///
9272static unsigned GetSelectFoldableOperands(Instruction *I) {
9273 switch (I->getOpcode()) {
9274 case Instruction::Add:
9275 case Instruction::Mul:
9276 case Instruction::And:
9277 case Instruction::Or:
9278 case Instruction::Xor:
9279 return 3; // Can fold through either operand.
9280 case Instruction::Sub: // Can only fold on the amount subtracted.
9281 case Instruction::Shl: // Can only fold on the shift amount.
9282 case Instruction::LShr:
9283 case Instruction::AShr:
9284 return 1;
9285 default:
9286 return 0; // Cannot fold
9287 }
9288}
9289
9290/// GetSelectFoldableConstant - For the same transformation as the previous
9291/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009292static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009293 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009294 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009295 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009296 case Instruction::Add:
9297 case Instruction::Sub:
9298 case Instruction::Or:
9299 case Instruction::Xor:
9300 case Instruction::Shl:
9301 case Instruction::LShr:
9302 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009303 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009304 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009305 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009306 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009307 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009308 }
9309}
9310
9311/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9312/// have the same opcode and only one use each. Try to simplify this.
9313Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9314 Instruction *FI) {
9315 if (TI->getNumOperands() == 1) {
9316 // If this is a non-volatile load or a cast from the same type,
9317 // merge.
9318 if (TI->isCast()) {
9319 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9320 return 0;
9321 } else {
9322 return 0; // unknown unary op.
9323 }
9324
9325 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009326 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009327 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009328 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009329 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009330 TI->getType());
9331 }
9332
9333 // Only handle binary operators here.
9334 if (!isa<BinaryOperator>(TI))
9335 return 0;
9336
9337 // Figure out if the operations have any operands in common.
9338 Value *MatchOp, *OtherOpT, *OtherOpF;
9339 bool MatchIsOpZero;
9340 if (TI->getOperand(0) == FI->getOperand(0)) {
9341 MatchOp = TI->getOperand(0);
9342 OtherOpT = TI->getOperand(1);
9343 OtherOpF = FI->getOperand(1);
9344 MatchIsOpZero = true;
9345 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9346 MatchOp = TI->getOperand(1);
9347 OtherOpT = TI->getOperand(0);
9348 OtherOpF = FI->getOperand(0);
9349 MatchIsOpZero = false;
9350 } else if (!TI->isCommutative()) {
9351 return 0;
9352 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9353 MatchOp = TI->getOperand(0);
9354 OtherOpT = TI->getOperand(1);
9355 OtherOpF = FI->getOperand(0);
9356 MatchIsOpZero = true;
9357 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9358 MatchOp = TI->getOperand(1);
9359 OtherOpT = TI->getOperand(0);
9360 OtherOpF = FI->getOperand(1);
9361 MatchIsOpZero = true;
9362 } else {
9363 return 0;
9364 }
9365
9366 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009367 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9368 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009369 InsertNewInstBefore(NewSI, SI);
9370
9371 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9372 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009373 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009374 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009375 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009376 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009377 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009378 return 0;
9379}
9380
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009381static bool isSelect01(Constant *C1, Constant *C2) {
9382 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9383 if (!C1I)
9384 return false;
9385 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9386 if (!C2I)
9387 return false;
9388 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9389}
9390
9391/// FoldSelectIntoOp - Try fold the select into one of the operands to
9392/// facilitate further optimization.
9393Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9394 Value *FalseVal) {
9395 // See the comment above GetSelectFoldableOperands for a description of the
9396 // transformation we are doing here.
9397 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9398 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9399 !isa<Constant>(FalseVal)) {
9400 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9401 unsigned OpToFold = 0;
9402 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9403 OpToFold = 1;
9404 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9405 OpToFold = 2;
9406 }
9407
9408 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009409 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009410 Value *OOp = TVI->getOperand(2-OpToFold);
9411 // Avoid creating select between 2 constants unless it's selecting
9412 // between 0 and 1.
9413 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9414 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9415 InsertNewInstBefore(NewSel, SI);
9416 NewSel->takeName(TVI);
9417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9418 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009419 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009420 }
9421 }
9422 }
9423 }
9424 }
9425
9426 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9427 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9428 !isa<Constant>(TrueVal)) {
9429 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9430 unsigned OpToFold = 0;
9431 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9432 OpToFold = 1;
9433 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9434 OpToFold = 2;
9435 }
9436
9437 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009438 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009439 Value *OOp = FVI->getOperand(2-OpToFold);
9440 // Avoid creating select between 2 constants unless it's selecting
9441 // between 0 and 1.
9442 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9443 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9444 InsertNewInstBefore(NewSel, SI);
9445 NewSel->takeName(FVI);
9446 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9447 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009448 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009449 }
9450 }
9451 }
9452 }
9453 }
9454
9455 return 0;
9456}
9457
Dan Gohman58c09632008-09-16 18:46:06 +00009458/// visitSelectInstWithICmp - Visit a SelectInst that has an
9459/// ICmpInst as its first operand.
9460///
9461Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9462 ICmpInst *ICI) {
9463 bool Changed = false;
9464 ICmpInst::Predicate Pred = ICI->getPredicate();
9465 Value *CmpLHS = ICI->getOperand(0);
9466 Value *CmpRHS = ICI->getOperand(1);
9467 Value *TrueVal = SI.getTrueValue();
9468 Value *FalseVal = SI.getFalseValue();
9469
9470 // Check cases where the comparison is with a constant that
9471 // can be adjusted to fit the min/max idiom. We may edit ICI in
9472 // place here, so make sure the select is the only user.
9473 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009474 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009475 switch (Pred) {
9476 default: break;
9477 case ICmpInst::ICMP_ULT:
9478 case ICmpInst::ICMP_SLT: {
9479 // X < MIN ? T : F --> F
9480 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9481 return ReplaceInstUsesWith(SI, FalseVal);
9482 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009483 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009484 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9485 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9486 Pred = ICmpInst::getSwappedPredicate(Pred);
9487 CmpRHS = AdjustedRHS;
9488 std::swap(FalseVal, TrueVal);
9489 ICI->setPredicate(Pred);
9490 ICI->setOperand(1, CmpRHS);
9491 SI.setOperand(1, TrueVal);
9492 SI.setOperand(2, FalseVal);
9493 Changed = true;
9494 }
9495 break;
9496 }
9497 case ICmpInst::ICMP_UGT:
9498 case ICmpInst::ICMP_SGT: {
9499 // X > MAX ? T : F --> F
9500 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9501 return ReplaceInstUsesWith(SI, FalseVal);
9502 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009503 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009504 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9505 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9506 Pred = ICmpInst::getSwappedPredicate(Pred);
9507 CmpRHS = AdjustedRHS;
9508 std::swap(FalseVal, TrueVal);
9509 ICI->setPredicate(Pred);
9510 ICI->setOperand(1, CmpRHS);
9511 SI.setOperand(1, TrueVal);
9512 SI.setOperand(2, FalseVal);
9513 Changed = true;
9514 }
9515 break;
9516 }
9517 }
9518
Dan Gohman35b76162008-10-30 20:40:10 +00009519 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9520 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009521 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009522 if (match(TrueVal, m_ConstantInt<-1>()) &&
9523 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009524 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009525 else if (match(TrueVal, m_ConstantInt<0>()) &&
9526 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009527 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9528
Dan Gohman35b76162008-10-30 20:40:10 +00009529 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9530 // If we are just checking for a icmp eq of a single bit and zext'ing it
9531 // to an integer, then shift the bit to the appropriate place and then
9532 // cast to integer to avoid the comparison.
9533 const APInt &Op1CV = CI->getValue();
9534
9535 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9536 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9537 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009538 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009539 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009540 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009541 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009542 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009543 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009544 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009545 if (In->getType() != SI.getType())
9546 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009547 true/*SExt*/, "tmp", ICI);
9548
9549 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009550 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009551 In->getName()+".not"), *ICI);
9552
9553 return ReplaceInstUsesWith(SI, In);
9554 }
9555 }
9556 }
9557
Dan Gohman58c09632008-09-16 18:46:06 +00009558 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9559 // Transform (X == Y) ? X : Y -> Y
9560 if (Pred == ICmpInst::ICMP_EQ)
9561 return ReplaceInstUsesWith(SI, FalseVal);
9562 // Transform (X != Y) ? X : Y -> X
9563 if (Pred == ICmpInst::ICMP_NE)
9564 return ReplaceInstUsesWith(SI, TrueVal);
9565 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9566
9567 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9568 // Transform (X == Y) ? Y : X -> X
9569 if (Pred == ICmpInst::ICMP_EQ)
9570 return ReplaceInstUsesWith(SI, FalseVal);
9571 // Transform (X != Y) ? Y : X -> Y
9572 if (Pred == ICmpInst::ICMP_NE)
9573 return ReplaceInstUsesWith(SI, TrueVal);
9574 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9575 }
Dan Gohman58c09632008-09-16 18:46:06 +00009576 return Changed ? &SI : 0;
9577}
9578
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009579
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009580/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9581/// PHI node (but the two may be in different blocks). See if the true/false
9582/// values (V) are live in all of the predecessor blocks of the PHI. For
9583/// example, cases like this cannot be mapped:
9584///
9585/// X = phi [ C1, BB1], [C2, BB2]
9586/// Y = add
9587/// Z = select X, Y, 0
9588///
9589/// because Y is not live in BB1/BB2.
9590///
9591static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9592 const SelectInst &SI) {
9593 // If the value is a non-instruction value like a constant or argument, it
9594 // can always be mapped.
9595 const Instruction *I = dyn_cast<Instruction>(V);
9596 if (I == 0) return true;
9597
9598 // If V is a PHI node defined in the same block as the condition PHI, we can
9599 // map the arguments.
9600 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9601
9602 if (const PHINode *VP = dyn_cast<PHINode>(I))
9603 if (VP->getParent() == CondPHI->getParent())
9604 return true;
9605
9606 // Otherwise, if the PHI and select are defined in the same block and if V is
9607 // defined in a different block, then we can transform it.
9608 if (SI.getParent() == CondPHI->getParent() &&
9609 I->getParent() != CondPHI->getParent())
9610 return true;
9611
9612 // Otherwise we have a 'hard' case and we can't tell without doing more
9613 // detailed dominator based analysis, punt.
9614 return false;
9615}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009616
Chris Lattner78500cb2009-12-21 06:03:05 +00009617/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9618/// SPF2(SPF1(A, B), C)
9619Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9620 SelectPatternFlavor SPF1,
9621 Value *A, Value *B,
9622 Instruction &Outer,
9623 SelectPatternFlavor SPF2, Value *C) {
9624 if (C == A || C == B) {
9625 // MAX(MAX(A, B), B) -> MAX(A, B)
9626 // MIN(MIN(a, b), a) -> MIN(a, b)
9627 if (SPF1 == SPF2)
9628 return ReplaceInstUsesWith(Outer, Inner);
9629
9630 // MAX(MIN(a, b), a) -> a
9631 // MIN(MAX(a, b), a) -> a
Daniel Dunbarb61aa2b2009-12-21 23:27:57 +00009632 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9633 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9634 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9635 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattner78500cb2009-12-21 06:03:05 +00009636 return ReplaceInstUsesWith(Outer, C);
9637 }
9638
9639 // TODO: MIN(MIN(A, 23), 97)
9640 return 0;
9641}
9642
9643
9644
9645
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009646Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9647 Value *CondVal = SI.getCondition();
9648 Value *TrueVal = SI.getTrueValue();
9649 Value *FalseVal = SI.getFalseValue();
9650
9651 // select true, X, Y -> X
9652 // select false, X, Y -> Y
9653 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9654 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9655
9656 // select C, X, X -> X
9657 if (TrueVal == FalseVal)
9658 return ReplaceInstUsesWith(SI, TrueVal);
9659
9660 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9661 return ReplaceInstUsesWith(SI, FalseVal);
9662 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9663 return ReplaceInstUsesWith(SI, TrueVal);
9664 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9665 if (isa<Constant>(TrueVal))
9666 return ReplaceInstUsesWith(SI, TrueVal);
9667 else
9668 return ReplaceInstUsesWith(SI, FalseVal);
9669 }
9670
Owen Anderson35b47072009-08-13 21:58:54 +00009671 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009672 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9673 if (C->getZExtValue()) {
9674 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009675 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009676 } else {
9677 // Change: A = select B, false, C --> A = and !B, C
9678 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009679 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009680 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009681 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009682 }
9683 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9684 if (C->getZExtValue() == false) {
9685 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009686 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009687 } else {
9688 // Change: A = select B, C, true --> A = or !B, C
9689 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009690 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009691 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009692 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009693 }
9694 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009695
9696 // select a, b, a -> a&b
9697 // select a, a, b -> a|b
9698 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009699 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009700 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009701 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009702 }
9703
9704 // Selecting between two integer constants?
9705 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9706 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9707 // select C, 1, 0 -> zext C to int
9708 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009709 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009710 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9711 // select C, 0, 1 -> zext !C to int
9712 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009713 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009714 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009715 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009716 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009717
9718 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009719 // If one of the constants is zero (we know they can't both be) and we
9720 // have an icmp instruction with zero, and we have an 'and' with the
9721 // non-constant value, eliminate this whole mess. This corresponds to
9722 // cases like this: ((X & 27) ? 27 : 0)
9723 if (TrueValC->isZero() || FalseValC->isZero())
9724 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9725 cast<Constant>(IC->getOperand(1))->isNullValue())
9726 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9727 if (ICA->getOpcode() == Instruction::And &&
9728 isa<ConstantInt>(ICA->getOperand(1)) &&
9729 (ICA->getOperand(1) == TrueValC ||
9730 ICA->getOperand(1) == FalseValC) &&
9731 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9732 // Okay, now we know that everything is set up, we just don't
9733 // know whether we have a icmp_ne or icmp_eq and whether the
9734 // true or false val is the zero.
9735 bool ShouldNotVal = !TrueValC->isZero();
9736 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9737 Value *V = ICA;
9738 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009739 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009740 Instruction::Xor, V, ICA->getOperand(1)), SI);
9741 return ReplaceInstUsesWith(SI, V);
9742 }
9743 }
9744 }
9745
9746 // See if we are selecting two values based on a comparison of the two values.
9747 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9748 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9749 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009750 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9751 // This is not safe in general for floating point:
9752 // consider X== -0, Y== +0.
9753 // It becomes safe if either operand is a nonzero constant.
9754 ConstantFP *CFPt, *CFPf;
9755 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9756 !CFPt->getValueAPF().isZero()) ||
9757 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9758 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009759 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009760 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009761 // Transform (X != Y) ? X : Y -> X
9762 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9763 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009764 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009765
9766 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9767 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009768 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9769 // This is not safe in general for floating point:
9770 // consider X== -0, Y== +0.
9771 // It becomes safe if either operand is a nonzero constant.
9772 ConstantFP *CFPt, *CFPf;
9773 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9774 !CFPt->getValueAPF().isZero()) ||
9775 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9776 !CFPf->getValueAPF().isZero()))
9777 return ReplaceInstUsesWith(SI, FalseVal);
9778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009779 // Transform (X != Y) ? Y : X -> Y
9780 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9781 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009782 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009783 }
Dan Gohman58c09632008-09-16 18:46:06 +00009784 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009785 }
9786
9787 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009788 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9789 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9790 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009791
9792 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9793 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9794 if (TI->hasOneUse() && FI->hasOneUse()) {
9795 Instruction *AddOp = 0, *SubOp = 0;
9796
9797 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9798 if (TI->getOpcode() == FI->getOpcode())
9799 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9800 return IV;
9801
9802 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9803 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009804 if ((TI->getOpcode() == Instruction::Sub &&
9805 FI->getOpcode() == Instruction::Add) ||
9806 (TI->getOpcode() == Instruction::FSub &&
9807 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009808 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009809 } else if ((FI->getOpcode() == Instruction::Sub &&
9810 TI->getOpcode() == Instruction::Add) ||
9811 (FI->getOpcode() == Instruction::FSub &&
9812 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009813 AddOp = TI; SubOp = FI;
9814 }
9815
9816 if (AddOp) {
9817 Value *OtherAddOp = 0;
9818 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9819 OtherAddOp = AddOp->getOperand(1);
9820 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9821 OtherAddOp = AddOp->getOperand(0);
9822 }
9823
9824 if (OtherAddOp) {
9825 // So at this point we know we have (Y -> OtherAddOp):
9826 // select C, (add X, Y), (sub X, Z)
9827 Value *NegVal; // Compute -Z
9828 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009829 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009830 } else {
9831 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009832 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009833 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009834 }
9835
9836 Value *NewTrueOp = OtherAddOp;
9837 Value *NewFalseOp = NegVal;
9838 if (AddOp != TI)
9839 std::swap(NewTrueOp, NewFalseOp);
9840 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009841 SelectInst::Create(CondVal, NewTrueOp,
9842 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009843
9844 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009845 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009846 }
9847 }
9848 }
9849
9850 // See if we can fold the select into one of our operands.
9851 if (SI.getType()->isInteger()) {
Chris Lattner78500cb2009-12-21 06:03:05 +00009852 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009853 return FoldI;
Chris Lattner78500cb2009-12-21 06:03:05 +00009854
9855 // MAX(MAX(a, b), a) -> MAX(a, b)
9856 // MIN(MIN(a, b), a) -> MIN(a, b)
9857 // MAX(MIN(a, b), a) -> a
9858 // MIN(MAX(a, b), a) -> a
9859 Value *LHS, *RHS, *LHS2, *RHS2;
9860 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
9861 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
9862 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
9863 SI, SPF, RHS))
9864 return R;
9865 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
9866 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
9867 SI, SPF, LHS))
9868 return R;
9869 }
9870
9871 // TODO.
9872 // ABS(-X) -> ABS(X)
9873 // ABS(ABS(X)) -> ABS(X)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009874 }
9875
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009876 // See if we can fold the select into a phi node if the condition is a select.
9877 if (isa<PHINode>(SI.getCondition()))
9878 // The true/false values have to be live in the PHI predecessor's blocks.
9879 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9880 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9881 if (Instruction *NV = FoldOpIntoPhi(SI))
9882 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00009883
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009884 if (BinaryOperator::isNot(CondVal)) {
9885 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9886 SI.setOperand(1, FalseVal);
9887 SI.setOperand(2, TrueVal);
9888 return &SI;
9889 }
9890
9891 return 0;
9892}
9893
Dan Gohman2d648bb2008-04-10 18:43:06 +00009894/// EnforceKnownAlignment - If the specified pointer points to an object that
9895/// we control, modify the object's alignment to PrefAlign. This isn't
9896/// often possible though. If alignment is important, a more reliable approach
9897/// is to simply align all global variables and allocation instructions to
9898/// their preferred alignment from the beginning.
9899///
9900static unsigned EnforceKnownAlignment(Value *V,
9901 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009902
Dan Gohman2d648bb2008-04-10 18:43:06 +00009903 User *U = dyn_cast<User>(V);
9904 if (!U) return Align;
9905
Dan Gohman9545fb02009-07-17 20:47:02 +00009906 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009907 default: break;
9908 case Instruction::BitCast:
9909 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9910 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009911 // If all indexes are zero, it is just the alignment of the base pointer.
9912 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009913 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009914 if (!isa<Constant>(*i) ||
9915 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009916 AllZeroOperands = false;
9917 break;
9918 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009919
9920 if (AllZeroOperands) {
9921 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009922 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009923 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009924 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009925 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009926 }
9927
9928 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9929 // If there is a large requested alignment and we can, bump up the alignment
9930 // of the global.
9931 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009932 if (GV->getAlignment() >= PrefAlign)
9933 Align = GV->getAlignment();
9934 else {
9935 GV->setAlignment(PrefAlign);
9936 Align = PrefAlign;
9937 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009938 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009939 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9940 // If there is a requested alignment and if this is an alloca, round up.
9941 if (AI->getAlignment() >= PrefAlign)
9942 Align = AI->getAlignment();
9943 else {
9944 AI->setAlignment(PrefAlign);
9945 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009946 }
9947 }
9948
9949 return Align;
9950}
9951
9952/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9953/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9954/// and it is more than the alignment of the ultimate object, see if we can
9955/// increase the alignment of the ultimate object, making this check succeed.
9956unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9957 unsigned PrefAlign) {
9958 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9959 sizeof(PrefAlign) * CHAR_BIT;
9960 APInt Mask = APInt::getAllOnesValue(BitWidth);
9961 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9962 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9963 unsigned TrailZ = KnownZero.countTrailingOnes();
9964 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9965
9966 if (PrefAlign > Align)
9967 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9968
9969 // We don't need to make any adjustment.
9970 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009971}
9972
Chris Lattner00ae5132008-01-13 23:50:23 +00009973Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009974 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009975 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009976 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009977 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009978
9979 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009980 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009981 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009982 return MI;
9983 }
9984
9985 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9986 // load/store.
9987 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9988 if (MemOpLength == 0) return 0;
9989
Chris Lattnerc669fb62008-01-14 00:28:35 +00009990 // Source and destination pointer types are always "i8*" for intrinsic. See
9991 // if the size is something we can handle with a single primitive load/store.
9992 // A single load+store correctly handles overlapping memory in the memmove
9993 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009994 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009995 if (Size == 0) return MI; // Delete this mem transfer.
9996
9997 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009998 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009999
Chris Lattnerc669fb62008-01-14 00:28:35 +000010000 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +000010001 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +000010002 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +000010003
10004 // Memcpy forces the use of i8* for the source and destination. That means
10005 // that if you're using memcpy to move one double around, you'll get a cast
10006 // from double* to i8*. We'd much rather use a double load+store rather than
10007 // an i64 load+store, here because this improves the odds that the source or
10008 // dest address will be promotable. See if we can find a better type than the
10009 // integer datatype.
10010 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10011 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000010012 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +000010013 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10014 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +000010015 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +000010016 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10017 if (STy->getNumElements() == 1)
10018 SrcETy = STy->getElementType(0);
10019 else
10020 break;
10021 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10022 if (ATy->getNumElements() == 1)
10023 SrcETy = ATy->getElementType();
10024 else
10025 break;
10026 } else
10027 break;
10028 }
10029
Dan Gohmanb8e94f62008-05-23 01:52:21 +000010030 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010031 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +000010032 }
10033 }
10034
10035
Chris Lattner00ae5132008-01-13 23:50:23 +000010036 // If the memcpy/memmove provides better alignment info than we can
10037 // infer, use it.
10038 SrcAlign = std::max(SrcAlign, CopyAlign);
10039 DstAlign = std::max(DstAlign, CopyAlign);
10040
Chris Lattner78628292009-08-30 19:47:22 +000010041 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10042 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +000010043 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10044 InsertNewInstBefore(L, *MI);
10045 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10046
10047 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +000010048 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +000010049 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +000010050}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010051
Chris Lattner5af8a912008-04-30 06:39:11 +000010052Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10053 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +000010054 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000010055 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +000010056 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +000010057 return MI;
10058 }
10059
10060 // Extract the length and alignment and fill if they are constant.
10061 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10062 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +000010063 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +000010064 return 0;
10065 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +000010066 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +000010067
10068 // If the length is zero, this is a no-op
10069 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10070
10071 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10072 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +000010073 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +000010074
10075 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +000010076 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +000010077
10078 // Alignment 0 is identity for alignment 1 for memset, but not store.
10079 if (Alignment == 0) Alignment = 1;
10080
10081 // Extract the fill value and store.
10082 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +000010083 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +000010084 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +000010085
10086 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +000010087 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +000010088 return MI;
10089 }
10090
10091 return 0;
10092}
10093
10094
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010095/// visitCallInst - CallInst simplification. This mostly only handles folding
10096/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10097/// the heavy lifting.
10098///
10099Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +000010100 if (isFreeCall(&CI))
10101 return visitFree(CI);
10102
Chris Lattneraa295aa2009-05-13 17:39:14 +000010103 // If the caller function is nounwind, mark the call as nounwind, even if the
10104 // callee isn't.
10105 if (CI.getParent()->getParent()->doesNotThrow() &&
10106 !CI.doesNotThrow()) {
10107 CI.setDoesNotThrow();
10108 return &CI;
10109 }
10110
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010111 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10112 if (!II) return visitCallSite(&CI);
10113
10114 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10115 // visitCallSite.
10116 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
10117 bool Changed = false;
10118
10119 // memmove/cpy/set of zero bytes is a noop.
10120 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10121 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10122
10123 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
10124 if (CI->getZExtValue() == 1) {
10125 // Replace the instruction with just byte operations. We would
10126 // transform other cases to loads/stores, but we don't know if
10127 // alignment is sufficient.
10128 }
10129 }
10130
10131 // If we have a memmove and the source operation is a constant global,
10132 // then the source and dest pointers can't alias, so we can change this
10133 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +000010134 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010135 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10136 if (GVSrc->isConstant()) {
10137 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +000010138 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10139 const Type *Tys[1];
10140 Tys[0] = CI.getOperand(3)->getType();
10141 CI.setOperand(0,
10142 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010143 Changed = true;
10144 }
Eli Friedman626e32a2009-12-17 21:07:31 +000010145 }
Chris Lattner59b27d92008-05-28 05:30:41 +000010146
Eli Friedman626e32a2009-12-17 21:07:31 +000010147 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +000010148 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +000010149 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +000010150 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010151 }
10152
10153 // If we can determine a pointer alignment that is bigger than currently
10154 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +000010155 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +000010156 if (Instruction *I = SimplifyMemTransfer(MI))
10157 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +000010158 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10159 if (Instruction *I = SimplifyMemSet(MSI))
10160 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010161 }
10162
10163 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +000010164 }
10165
10166 switch (II->getIntrinsicID()) {
10167 default: break;
10168 case Intrinsic::bswap:
10169 // bswap(bswap(x)) -> x
10170 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10171 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10172 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattner723b9642010-01-01 18:34:40 +000010173
10174 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10175 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10176 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10177 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10178 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10179 TI->getType()->getPrimitiveSizeInBits();
10180 Value *CV = ConstantInt::get(Operand->getType(), C);
10181 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10182 return new TruncInst(V, TI->getType());
10183 }
10184 }
10185
Chris Lattner989ba312008-06-18 04:33:20 +000010186 break;
Chris Lattnerfd4f21a2010-01-01 01:52:15 +000010187 case Intrinsic::powi:
10188 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10189 // powi(x, 0) -> 1.0
10190 if (Power->isZero())
10191 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10192 // powi(x, 1) -> x
10193 if (Power->isOne())
10194 return ReplaceInstUsesWith(CI, II->getOperand(1));
10195 // powi(x, -1) -> 1/x
Chris Lattner60179fb2010-01-01 01:54:08 +000010196 if (Power->isAllOnesValue())
10197 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10198 II->getOperand(1));
Chris Lattnerfd4f21a2010-01-01 01:52:15 +000010199 }
10200 break;
10201
Chris Lattner0b452262009-11-26 21:42:47 +000010202 case Intrinsic::uadd_with_overflow: {
10203 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10204 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10205 uint32_t BitWidth = IT->getBitWidth();
10206 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +000010207 APInt LHSKnownZero(BitWidth, 0);
10208 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010209 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10210 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10211 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10212
10213 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +000010214 APInt RHSKnownZero(BitWidth, 0);
10215 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010216 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10217 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10218 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10219 if (LHSKnownNegative && RHSKnownNegative) {
10220 // The sign bit is set in both cases: this MUST overflow.
10221 // Create a simple add instruction, and insert it into the struct.
10222 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10223 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010224 Constant *V[] = {
10225 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10226 };
Chris Lattner0b452262009-11-26 21:42:47 +000010227 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10228 return InsertValueInst::Create(Struct, Add, 0);
10229 }
10230
10231 if (LHSKnownPositive && RHSKnownPositive) {
10232 // The sign bit is clear in both cases: this CANNOT overflow.
10233 // Create a simple add instruction, and insert it into the struct.
10234 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10235 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010236 Constant *V[] = {
10237 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10238 };
Chris Lattner0b452262009-11-26 21:42:47 +000010239 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10240 return InsertValueInst::Create(Struct, Add, 0);
10241 }
10242 }
10243 }
10244 // FALL THROUGH uadd into sadd
10245 case Intrinsic::sadd_with_overflow:
10246 // Canonicalize constants into the RHS.
10247 if (isa<Constant>(II->getOperand(1)) &&
10248 !isa<Constant>(II->getOperand(2))) {
10249 Value *LHS = II->getOperand(1);
10250 II->setOperand(1, II->getOperand(2));
10251 II->setOperand(2, LHS);
10252 return II;
10253 }
10254
10255 // X + undef -> undef
10256 if (isa<UndefValue>(II->getOperand(2)))
10257 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10258
10259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10260 // X + 0 -> {X, false}
10261 if (RHS->isZero()) {
10262 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010263 UndefValue::get(II->getOperand(0)->getType()),
10264 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010265 };
10266 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10267 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10268 }
10269 }
10270 break;
10271 case Intrinsic::usub_with_overflow:
10272 case Intrinsic::ssub_with_overflow:
10273 // undef - X -> undef
10274 // X - undef -> undef
10275 if (isa<UndefValue>(II->getOperand(1)) ||
10276 isa<UndefValue>(II->getOperand(2)))
10277 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10278
10279 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10280 // X - 0 -> {X, false}
10281 if (RHS->isZero()) {
10282 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010283 UndefValue::get(II->getOperand(1)->getType()),
10284 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010285 };
10286 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10287 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10288 }
10289 }
10290 break;
10291 case Intrinsic::umul_with_overflow:
10292 case Intrinsic::smul_with_overflow:
10293 // Canonicalize constants into the RHS.
10294 if (isa<Constant>(II->getOperand(1)) &&
10295 !isa<Constant>(II->getOperand(2))) {
10296 Value *LHS = II->getOperand(1);
10297 II->setOperand(1, II->getOperand(2));
10298 II->setOperand(2, LHS);
10299 return II;
10300 }
10301
10302 // X * undef -> undef
10303 if (isa<UndefValue>(II->getOperand(2)))
10304 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10305
10306 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10307 // X*0 -> {0, false}
10308 if (RHSI->isZero())
10309 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10310
10311 // X * 1 -> {X, false}
10312 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010313 Constant *V[] = {
10314 UndefValue::get(II->getOperand(1)->getType()),
10315 ConstantInt::getFalse(*Context)
10316 };
Chris Lattner0b452262009-11-26 21:42:47 +000010317 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010318 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010319 }
10320 }
10321 break;
Chris Lattner989ba312008-06-18 04:33:20 +000010322 case Intrinsic::ppc_altivec_lvx:
10323 case Intrinsic::ppc_altivec_lvxl:
10324 case Intrinsic::x86_sse_loadu_ps:
10325 case Intrinsic::x86_sse2_loadu_pd:
10326 case Intrinsic::x86_sse2_loadu_dq:
10327 // Turn PPC lvx -> load if the pointer is known aligned.
10328 // Turn X86 loadups -> load if the pointer is known aligned.
10329 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +000010330 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10331 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +000010332 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010333 }
Chris Lattner989ba312008-06-18 04:33:20 +000010334 break;
10335 case Intrinsic::ppc_altivec_stvx:
10336 case Intrinsic::ppc_altivec_stvxl:
10337 // Turn stvx -> store if the pointer is known aligned.
10338 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10339 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010340 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010341 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010342 return new StoreInst(II->getOperand(1), Ptr);
10343 }
10344 break;
10345 case Intrinsic::x86_sse_storeu_ps:
10346 case Intrinsic::x86_sse2_storeu_pd:
10347 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +000010348 // Turn X86 storeu -> store if the pointer is known aligned.
10349 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10350 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010351 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010352 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010353 return new StoreInst(II->getOperand(2), Ptr);
10354 }
10355 break;
10356
10357 case Intrinsic::x86_sse_cvttss2si: {
10358 // These intrinsics only demands the 0th element of its input vector. If
10359 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +000010360 unsigned VWidth =
10361 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10362 APInt DemandedElts(VWidth, 1);
10363 APInt UndefElts(VWidth, 0);
10364 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +000010365 UndefElts)) {
10366 II->setOperand(1, V);
10367 return II;
10368 }
10369 break;
10370 }
10371
10372 case Intrinsic::ppc_altivec_vperm:
10373 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10374 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10375 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010376
Chris Lattner989ba312008-06-18 04:33:20 +000010377 // Check that all of the elements are integer constants or undefs.
10378 bool AllEltsOk = true;
10379 for (unsigned i = 0; i != 16; ++i) {
10380 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10381 !isa<UndefValue>(Mask->getOperand(i))) {
10382 AllEltsOk = false;
10383 break;
10384 }
10385 }
10386
10387 if (AllEltsOk) {
10388 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +000010389 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10390 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +000010391 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010392
Chris Lattner989ba312008-06-18 04:33:20 +000010393 // Only extract each element once.
10394 Value *ExtractedElts[32];
10395 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10396
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010397 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +000010398 if (isa<UndefValue>(Mask->getOperand(i)))
10399 continue;
10400 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10401 Idx &= 31; // Match the hardware behavior.
10402
10403 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010404 ExtractedElts[Idx] =
10405 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10406 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10407 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010409
Chris Lattner989ba312008-06-18 04:33:20 +000010410 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +000010411 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10412 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10413 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010414 }
Chris Lattner989ba312008-06-18 04:33:20 +000010415 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010416 }
Chris Lattner989ba312008-06-18 04:33:20 +000010417 }
10418 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010419
Chris Lattner989ba312008-06-18 04:33:20 +000010420 case Intrinsic::stackrestore: {
10421 // If the save is right next to the restore, remove the restore. This can
10422 // happen when variable allocas are DCE'd.
10423 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10424 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10425 BasicBlock::iterator BI = SS;
10426 if (&*++BI == II)
10427 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010428 }
Chris Lattner989ba312008-06-18 04:33:20 +000010429 }
10430
10431 // Scan down this block to see if there is another stack restore in the
10432 // same block without an intervening call/alloca.
10433 BasicBlock::iterator BI = II;
10434 TerminatorInst *TI = II->getParent()->getTerminator();
10435 bool CannotRemove = false;
10436 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000010437 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +000010438 CannotRemove = true;
10439 break;
10440 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010441 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10442 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10443 // If there is a stackrestore below this one, remove this one.
10444 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10445 return EraseInstFromFunction(CI);
10446 // Otherwise, ignore the intrinsic.
10447 } else {
10448 // If we found a non-intrinsic call, we can't remove the stack
10449 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010450 CannotRemove = true;
10451 break;
10452 }
Chris Lattner989ba312008-06-18 04:33:20 +000010453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010454 }
Chris Lattner989ba312008-06-18 04:33:20 +000010455
10456 // If the stack restore is in a return/unwind block and if there are no
10457 // allocas or calls between the restore and the return, nuke the restore.
10458 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10459 return EraseInstFromFunction(CI);
10460 break;
10461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010462 }
10463
10464 return visitCallSite(II);
10465}
10466
10467// InvokeInst simplification
10468//
10469Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10470 return visitCallSite(&II);
10471}
10472
Dale Johannesen96021832008-04-25 21:16:07 +000010473/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10474/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010475static bool isSafeToEliminateVarargsCast(const CallSite CS,
10476 const CastInst * const CI,
10477 const TargetData * const TD,
10478 const int ix) {
10479 if (!CI->isLosslessCast())
10480 return false;
10481
10482 // The size of ByVal arguments is derived from the type, so we
10483 // can't change to a type with a different size. If the size were
10484 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010485 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010486 return true;
10487
10488 const Type* SrcTy =
10489 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10490 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10491 if (!SrcTy->isSized() || !DstTy->isSized())
10492 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010493 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010494 return false;
10495 return true;
10496}
10497
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010498// visitCallSite - Improvements for call and invoke instructions.
10499//
10500Instruction *InstCombiner::visitCallSite(CallSite CS) {
10501 bool Changed = false;
10502
10503 // If the callee is a constexpr cast of a function, attempt to move the cast
10504 // to the arguments of the call/invoke.
10505 if (transformConstExprCastCall(CS)) return 0;
10506
10507 Value *Callee = CS.getCalledValue();
10508
10509 if (Function *CalleeF = dyn_cast<Function>(Callee))
10510 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10511 Instruction *OldCall = CS.getInstruction();
10512 // If the call and callee calling conventions don't match, this call must
10513 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010514 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010515 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010516 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010517 // If OldCall dues not return void then replaceAllUsesWith undef.
10518 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010519 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010520 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010521 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10522 return EraseInstFromFunction(*OldCall);
10523 return 0;
10524 }
10525
10526 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10527 // This instruction is not reachable, just remove it. We insert a store to
10528 // undef so that we know that this code is not reachable, despite the fact
10529 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010530 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010531 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010532 CS.getInstruction());
10533
Devang Patele3829c82009-10-13 22:56:32 +000010534 // If CS dues not return void then replaceAllUsesWith undef.
10535 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010536 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010537 CS.getInstruction()->
10538 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010539
10540 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10541 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010542 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010543 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010544 }
10545 return EraseInstFromFunction(*CS.getInstruction());
10546 }
10547
Duncan Sands74833f22007-09-17 10:26:40 +000010548 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10549 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10550 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10551 return transformCallThroughTrampoline(CS);
10552
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010553 const PointerType *PTy = cast<PointerType>(Callee->getType());
10554 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10555 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010556 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010557 // See if we can optimize any arguments passed through the varargs area of
10558 // the call.
10559 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010560 E = CS.arg_end(); I != E; ++I, ++ix) {
10561 CastInst *CI = dyn_cast<CastInst>(*I);
10562 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10563 *I = CI->getOperand(0);
10564 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010565 }
Dale Johannesen35615462008-04-23 18:34:37 +000010566 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010567 }
10568
Duncan Sands2937e352007-12-19 21:13:37 +000010569 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010570 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010571 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010572 Changed = true;
10573 }
10574
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010575 return Changed ? CS.getInstruction() : 0;
10576}
10577
10578// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10579// attempt to move the cast to the arguments of the call/invoke.
10580//
10581bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10582 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10583 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10584 if (CE->getOpcode() != Instruction::BitCast ||
10585 !isa<Function>(CE->getOperand(0)))
10586 return false;
10587 Function *Callee = cast<Function>(CE->getOperand(0));
10588 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010589 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010590
10591 // Okay, this is a cast from a function to a different type. Unless doing so
10592 // would cause a type conversion of one of our arguments, change this call to
10593 // be a direct call with arguments casted to the appropriate types.
10594 //
10595 const FunctionType *FT = Callee->getFunctionType();
10596 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010597 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010598
Duncan Sands7901ce12008-06-01 07:38:42 +000010599 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010600 return false; // TODO: Handle multiple return values.
10601
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010602 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010603 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010604 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010605 // Conversion is ok if changing from one pointer type to another or from
10606 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010607 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010608 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010609 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010610 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010611 return false; // Cannot transform this return value.
10612
Duncan Sands5c489582008-01-06 10:12:28 +000010613 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010614 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010615 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010616 return false; // Cannot transform this return value.
10617
Chris Lattner1c8733e2008-03-12 17:45:29 +000010618 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010619 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010620 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010621 return false; // Attribute not compatible with transformed value.
10622 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010623
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010624 // If the callsite is an invoke instruction, and the return value is used by
10625 // a PHI node in a successor, we cannot change the return type of the call
10626 // because there is no place to put the cast instruction (without breaking
10627 // the critical edge). Bail out in this case.
10628 if (!Caller->use_empty())
10629 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10630 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10631 UI != E; ++UI)
10632 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10633 if (PN->getParent() == II->getNormalDest() ||
10634 PN->getParent() == II->getUnwindDest())
10635 return false;
10636 }
10637
10638 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10639 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10640
10641 CallSite::arg_iterator AI = CS.arg_begin();
10642 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10643 const Type *ParamTy = FT->getParamType(i);
10644 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010645
10646 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010647 return false; // Cannot transform this parameter value.
10648
Devang Patelf2a4a922008-09-26 22:53:05 +000010649 if (CallerPAL.getParamAttributes(i + 1)
10650 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010651 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010652
Duncan Sands7901ce12008-06-01 07:38:42 +000010653 // Converting from one pointer type to another or between a pointer and an
10654 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010655 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010656 (TD && ((isa<PointerType>(ParamTy) ||
10657 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10658 (isa<PointerType>(ActTy) ||
10659 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010660 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010661 }
10662
10663 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10664 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010665 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010666
Chris Lattner1c8733e2008-03-12 17:45:29 +000010667 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10668 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010669 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010670 // won't be dropping them. Check that these extra arguments have attributes
10671 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010672 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10673 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010674 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010675 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010676 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010677 return false;
10678 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010679
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010680 // Okay, we decided that this is a safe thing to do: go ahead and start
10681 // inserting cast instructions as necessary...
10682 std::vector<Value*> Args;
10683 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010684 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010685 attrVec.reserve(NumCommonArgs);
10686
10687 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010688 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010689
10690 // If the return value is not being used, the type may not be compatible
10691 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010692 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010693
10694 // Add the new return attributes.
10695 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010696 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010697
10698 AI = CS.arg_begin();
10699 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10700 const Type *ParamTy = FT->getParamType(i);
10701 if ((*AI)->getType() == ParamTy) {
10702 Args.push_back(*AI);
10703 } else {
10704 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10705 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010706 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010707 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010708
10709 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010710 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010711 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010712 }
10713
10714 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010715 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010716 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010717 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010718
Chris Lattnerad7516a2009-08-30 18:50:58 +000010719 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010720 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010721 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010722 errs() << "WARNING: While resolving call to function '"
10723 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010724 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010725 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010726 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10727 const Type *PTy = getPromotedType((*AI)->getType());
10728 if (PTy != (*AI)->getType()) {
10729 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010730 Instruction::CastOps opcode =
10731 CastInst::getCastOpcode(*AI, false, PTy, false);
10732 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010733 } else {
10734 Args.push_back(*AI);
10735 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010736
Duncan Sands4ced1f82008-01-13 08:02:44 +000010737 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010738 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010739 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010740 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010741 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010742 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010743
Devang Patelf2a4a922008-09-26 22:53:05 +000010744 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10745 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10746
Devang Patele9d08b82009-10-14 17:29:00 +000010747 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010748 Caller->setName(""); // Void type should not have a name.
10749
Eric Christopher3e7381f2009-07-25 02:45:27 +000010750 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10751 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010752
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010753 Instruction *NC;
10754 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010755 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010756 Args.begin(), Args.end(),
10757 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010758 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010759 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010760 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010761 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10762 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010763 CallInst *CI = cast<CallInst>(Caller);
10764 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010765 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010766 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010767 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010768 }
10769
10770 // Insert a cast of the return type as necessary.
10771 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010772 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010773 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010774 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010775 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010776 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010777
10778 // If this is an invoke instruction, we should insert it after the first
10779 // non-phi, instruction in the normal successor block.
10780 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010781 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010782 InsertNewInstBefore(NC, *I);
10783 } else {
10784 // Otherwise, it's a call, just insert cast right after the call instr
10785 InsertNewInstBefore(NC, *Caller);
10786 }
Chris Lattner4796b622009-08-30 06:22:51 +000010787 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010788 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010789 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010790 }
10791 }
10792
Devang Pateledad36f2009-10-13 21:41:20 +000010793
Chris Lattner26b7f942009-08-31 05:17:58 +000010794 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010795 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010796
10797 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010798 return true;
10799}
10800
Duncan Sands74833f22007-09-17 10:26:40 +000010801// transformCallThroughTrampoline - Turn a call to a function created by the
10802// init_trampoline intrinsic into a direct call to the underlying function.
10803//
10804Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10805 Value *Callee = CS.getCalledValue();
10806 const PointerType *PTy = cast<PointerType>(Callee->getType());
10807 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010808 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010809
10810 // If the call already has the 'nest' attribute somewhere then give up -
10811 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010812 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010813 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010814
10815 IntrinsicInst *Tramp =
10816 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10817
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010818 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010819 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10820 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10821
Devang Pateld222f862008-09-25 21:00:45 +000010822 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010823 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010824 unsigned NestIdx = 1;
10825 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010826 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010827
10828 // Look for a parameter marked with the 'nest' attribute.
10829 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10830 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010831 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010832 // Record the parameter type and any other attributes.
10833 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010834 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010835 break;
10836 }
10837
10838 if (NestTy) {
10839 Instruction *Caller = CS.getInstruction();
10840 std::vector<Value*> NewArgs;
10841 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10842
Devang Pateld222f862008-09-25 21:00:45 +000010843 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010844 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010845
Duncan Sands74833f22007-09-17 10:26:40 +000010846 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010847 // mean appending it. Likewise for attributes.
10848
Devang Patelf2a4a922008-09-26 22:53:05 +000010849 // Add any result attributes.
10850 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010851 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010852
Duncan Sands74833f22007-09-17 10:26:40 +000010853 {
10854 unsigned Idx = 1;
10855 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10856 do {
10857 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010858 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010859 Value *NestVal = Tramp->getOperand(3);
10860 if (NestVal->getType() != NestTy)
10861 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10862 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010863 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010864 }
10865
10866 if (I == E)
10867 break;
10868
Duncan Sands48b81112008-01-14 19:52:09 +000010869 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010870 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010871 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010872 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010873 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010874
10875 ++Idx, ++I;
10876 } while (1);
10877 }
10878
Devang Patelf2a4a922008-09-26 22:53:05 +000010879 // Add any function attributes.
10880 if (Attributes Attr = Attrs.getFnAttributes())
10881 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10882
Duncan Sands74833f22007-09-17 10:26:40 +000010883 // The trampoline may have been bitcast to a bogus type (FTy).
10884 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010885 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010886
Duncan Sands74833f22007-09-17 10:26:40 +000010887 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010888 NewTypes.reserve(FTy->getNumParams()+1);
10889
Duncan Sands74833f22007-09-17 10:26:40 +000010890 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010891 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010892 {
10893 unsigned Idx = 1;
10894 FunctionType::param_iterator I = FTy->param_begin(),
10895 E = FTy->param_end();
10896
10897 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010898 if (Idx == NestIdx)
10899 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010900 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010901
10902 if (I == E)
10903 break;
10904
Duncan Sands48b81112008-01-14 19:52:09 +000010905 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010906 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010907
10908 ++Idx, ++I;
10909 } while (1);
10910 }
10911
10912 // Replace the trampoline call with a direct call. Let the generic
10913 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010914 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010915 FTy->isVarArg());
10916 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010917 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010918 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010919 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010920 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10921 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010922
10923 Instruction *NewCaller;
10924 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010925 NewCaller = InvokeInst::Create(NewCallee,
10926 II->getNormalDest(), II->getUnwindDest(),
10927 NewArgs.begin(), NewArgs.end(),
10928 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010929 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010930 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010931 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010932 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10933 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010934 if (cast<CallInst>(Caller)->isTailCall())
10935 cast<CallInst>(NewCaller)->setTailCall();
10936 cast<CallInst>(NewCaller)->
10937 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010938 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010939 }
Devang Patele9d08b82009-10-14 17:29:00 +000010940 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010941 Caller->replaceAllUsesWith(NewCaller);
10942 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010943 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010944 return 0;
10945 }
10946 }
10947
10948 // Replace the trampoline call with a direct call. Since there is no 'nest'
10949 // parameter, there is no need to adjust the argument list. Let the generic
10950 // code sort out any function type mismatches.
10951 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010952 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010953 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010954 CS.setCalledFunction(NewCallee);
10955 return CS.getInstruction();
10956}
10957
Dan Gohman09cf2b62009-09-16 16:50:24 +000010958/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10959/// 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 +000010960/// and a single binop.
10961Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10962 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010963 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010964 unsigned Opc = FirstInst->getOpcode();
10965 Value *LHSVal = FirstInst->getOperand(0);
10966 Value *RHSVal = FirstInst->getOperand(1);
10967
10968 const Type *LHSType = LHSVal->getType();
10969 const Type *RHSType = RHSVal->getType();
10970
Dan Gohman09cf2b62009-09-16 16:50:24 +000010971 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010972 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010973 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10974 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10975 // Verify type of the LHS matches so we don't fold cmp's of different
10976 // types or GEP's with different index types.
10977 I->getOperand(0)->getType() != LHSType ||
10978 I->getOperand(1)->getType() != RHSType)
10979 return 0;
10980
10981 // If they are CmpInst instructions, check their predicates
10982 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10983 if (cast<CmpInst>(I)->getPredicate() !=
10984 cast<CmpInst>(FirstInst)->getPredicate())
10985 return 0;
10986
10987 // Keep track of which operand needs a phi node.
10988 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10989 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10990 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010991
10992 // If both LHS and RHS would need a PHI, don't do this transformation,
10993 // because it would increase the number of PHIs entering the block,
10994 // which leads to higher register pressure. This is especially
10995 // bad when the PHIs are in the header of a loop.
10996 if (!LHSVal && !RHSVal)
10997 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010998
Chris Lattner30078012008-12-01 03:42:51 +000010999 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011000
11001 Value *InLHS = FirstInst->getOperand(0);
11002 Value *InRHS = FirstInst->getOperand(1);
11003 PHINode *NewLHS = 0, *NewRHS = 0;
11004 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011005 NewLHS = PHINode::Create(LHSType,
11006 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011007 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11008 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
11009 InsertNewInstBefore(NewLHS, PN);
11010 LHSVal = NewLHS;
11011 }
11012
11013 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011014 NewRHS = PHINode::Create(RHSType,
11015 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011016 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11017 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
11018 InsertNewInstBefore(NewRHS, PN);
11019 RHSVal = NewRHS;
11020 }
11021
11022 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000011023 if (NewLHS || NewRHS) {
11024 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11025 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11026 if (NewLHS) {
11027 Value *NewInLHS = InInst->getOperand(0);
11028 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11029 }
11030 if (NewRHS) {
11031 Value *NewInRHS = InInst->getOperand(1);
11032 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11033 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011034 }
11035 }
11036
11037 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011038 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000011039 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000011040 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000011041 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011042}
11043
Chris Lattner9e1916e2008-12-01 02:34:36 +000011044Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11045 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11046
11047 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11048 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000011049 // This is true if all GEP bases are allocas and if all indices into them are
11050 // constants.
11051 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000011052
11053 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000011054 // more than one phi, which leads to higher register pressure. This is
11055 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000011056 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000011057
Dan Gohman09cf2b62009-09-16 16:50:24 +000011058 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000011059 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11060 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11061 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11062 GEP->getNumOperands() != FirstInst->getNumOperands())
11063 return 0;
11064
Chris Lattneradf354b2009-02-21 00:46:50 +000011065 // Keep track of whether or not all GEPs are of alloca pointers.
11066 if (AllBasePointersAreAllocas &&
11067 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11068 !GEP->hasAllConstantIndices()))
11069 AllBasePointersAreAllocas = false;
11070
Chris Lattner9e1916e2008-12-01 02:34:36 +000011071 // Compare the operand lists.
11072 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11073 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11074 continue;
11075
11076 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11077 // if one of the PHIs has a constant for the index. The index may be
11078 // substantially cheaper to compute for the constants, so making it a
11079 // variable index could pessimize the path. This also handles the case
11080 // for struct indices, which must always be constant.
11081 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11082 isa<ConstantInt>(GEP->getOperand(op)))
11083 return 0;
11084
11085 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11086 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000011087
11088 // If we already needed a PHI for an earlier operand, and another operand
11089 // also requires a PHI, we'd be introducing more PHIs than we're
11090 // eliminating, which increases register pressure on entry to the PHI's
11091 // block.
11092 if (NeededPhi)
11093 return 0;
11094
Chris Lattner9e1916e2008-12-01 02:34:36 +000011095 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000011096 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000011097 }
11098 }
11099
Chris Lattneradf354b2009-02-21 00:46:50 +000011100 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000011101 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000011102 // offset calculation, but all the predecessors will have to materialize the
11103 // stack address into a register anyway. We'd actually rather *clone* the
11104 // load up into the predecessors so that we have a load of a gep of an alloca,
11105 // which can usually all be folded into the load.
11106 if (AllBasePointersAreAllocas)
11107 return 0;
11108
Chris Lattner9e1916e2008-12-01 02:34:36 +000011109 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11110 // that is variable.
11111 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11112
11113 bool HasAnyPHIs = false;
11114 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11115 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11116 Value *FirstOp = FirstInst->getOperand(i);
11117 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11118 FirstOp->getName()+".pn");
11119 InsertNewInstBefore(NewPN, PN);
11120
11121 NewPN->reserveOperandSpace(e);
11122 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11123 OperandPhis[i] = NewPN;
11124 FixedOperands[i] = NewPN;
11125 HasAnyPHIs = true;
11126 }
11127
11128
11129 // Add all operands to the new PHIs.
11130 if (HasAnyPHIs) {
11131 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11132 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11133 BasicBlock *InBB = PN.getIncomingBlock(i);
11134
11135 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11136 if (PHINode *OpPhi = OperandPhis[op])
11137 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11138 }
11139 }
11140
11141 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011142 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11143 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11144 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011145 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11146 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000011147}
11148
11149
Chris Lattnerf1e30c82009-02-23 05:56:17 +000011150/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11151/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000011152/// obvious the value of the load is not changed from the point of the load to
11153/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011154///
11155/// Finally, it is safe, but not profitable, to sink a load targetting a
11156/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11157/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000011158static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011159 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11160
11161 for (++BBI; BBI != E; ++BBI)
11162 if (BBI->mayWriteToMemory())
11163 return false;
11164
11165 // Check for non-address taken alloca. If not address-taken already, it isn't
11166 // profitable to do this xform.
11167 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11168 bool isAddressTaken = false;
11169 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11170 UI != E; ++UI) {
11171 if (isa<LoadInst>(UI)) continue;
11172 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11173 // If storing TO the alloca, then the address isn't taken.
11174 if (SI->getOperand(1) == AI) continue;
11175 }
11176 isAddressTaken = true;
11177 break;
11178 }
11179
Chris Lattneradf354b2009-02-21 00:46:50 +000011180 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011181 return false;
11182 }
11183
Chris Lattneradf354b2009-02-21 00:46:50 +000011184 // If this load is a load from a GEP with a constant offset from an alloca,
11185 // then we don't want to sink it. In its present form, it will be
11186 // load [constant stack offset]. Sinking it will cause us to have to
11187 // materialize the stack addresses in each predecessor in a register only to
11188 // do a shared load from register in the successor.
11189 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11190 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11191 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11192 return false;
11193
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011194 return true;
11195}
11196
Chris Lattner38751f82009-11-01 20:04:24 +000011197Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11198 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11199
11200 // When processing loads, we need to propagate two bits of information to the
11201 // sunk load: whether it is volatile, and what its alignment is. We currently
11202 // don't sink loads when some have their alignment specified and some don't.
11203 // visitLoadInst will propagate an alignment onto the load when TD is around,
11204 // and if TD isn't around, we can't handle the mixed case.
11205 bool isVolatile = FirstLI->isVolatile();
11206 unsigned LoadAlignment = FirstLI->getAlignment();
11207
11208 // We can't sink the load if the loaded value could be modified between the
11209 // load and the PHI.
11210 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11211 !isSafeAndProfitableToSinkLoad(FirstLI))
11212 return 0;
11213
11214 // If the PHI is of volatile loads and the load block has multiple
11215 // successors, sinking it would remove a load of the volatile value from
11216 // the path through the other successor.
11217 if (isVolatile &&
11218 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11219 return 0;
11220
11221 // Check to see if all arguments are the same operation.
11222 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11223 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11224 if (!LI || !LI->hasOneUse())
11225 return 0;
11226
11227 // We can't sink the load if the loaded value could be modified between
11228 // the load and the PHI.
11229 if (LI->isVolatile() != isVolatile ||
11230 LI->getParent() != PN.getIncomingBlock(i) ||
11231 !isSafeAndProfitableToSinkLoad(LI))
11232 return 0;
11233
11234 // If some of the loads have an alignment specified but not all of them,
11235 // we can't do the transformation.
11236 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11237 return 0;
11238
Chris Lattner52fe1bc2009-11-01 20:07:07 +000011239 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +000011240
11241 // If the PHI is of volatile loads and the load block has multiple
11242 // successors, sinking it would remove a load of the volatile value from
11243 // the path through the other successor.
11244 if (isVolatile &&
11245 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11246 return 0;
11247 }
11248
11249 // Okay, they are all the same operation. Create a new PHI node of the
11250 // correct type, and PHI together all of the LHS's of the instructions.
11251 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11252 PN.getName()+".in");
11253 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11254
11255 Value *InVal = FirstLI->getOperand(0);
11256 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11257
11258 // Add all operands to the new PHI.
11259 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11260 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11261 if (NewInVal != InVal)
11262 InVal = 0;
11263 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11264 }
11265
11266 Value *PhiVal;
11267 if (InVal) {
11268 // The new PHI unions all of the same values together. This is really
11269 // common, so we handle it intelligently here for compile-time speed.
11270 PhiVal = InVal;
11271 delete NewPN;
11272 } else {
11273 InsertNewInstBefore(NewPN, PN);
11274 PhiVal = NewPN;
11275 }
11276
11277 // If this was a volatile load that we are merging, make sure to loop through
11278 // and mark all the input loads as non-volatile. If we don't do this, we will
11279 // insert a new volatile load and the old ones will not be deletable.
11280 if (isVolatile)
11281 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11282 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11283
11284 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11285}
11286
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011287
Chris Lattnerd0011092009-11-10 07:23:37 +000011288
11289/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11290/// operator and they all are only used by the PHI, PHI together their
11291/// inputs, and do the operation once, to the result of the PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011292Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11293 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11294
Chris Lattner38751f82009-11-01 20:04:24 +000011295 if (isa<GetElementPtrInst>(FirstInst))
11296 return FoldPHIArgGEPIntoPHI(PN);
11297 if (isa<LoadInst>(FirstInst))
11298 return FoldPHIArgLoadIntoPHI(PN);
11299
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011300 // Scan the instruction, looking for input operations that can be folded away.
11301 // If all input operands to the phi are the same instruction (e.g. a cast from
11302 // the same type or "+42") we can pull the operation through the PHI, reducing
11303 // code size and simplifying code.
11304 Constant *ConstantOp = 0;
11305 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +000011306
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011307 if (isa<CastInst>(FirstInst)) {
11308 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +000011309
11310 // Be careful about transforming integer PHIs. We don't want to pessimize
11311 // the code by turning an i32 into an i1293.
11312 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerd0011092009-11-10 07:23:37 +000011313 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattner4ca73902009-11-08 21:20:06 +000011314 return 0;
11315 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011316 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11317 // Can fold binop, compare or shift here if the RHS is a constant,
11318 // otherwise call FoldPHIArgBinOpIntoPHI.
11319 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11320 if (ConstantOp == 0)
11321 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011322 } else {
11323 return 0; // Cannot fold this operation.
11324 }
11325
11326 // Check to see if all arguments are the same operation.
11327 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +000011328 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11329 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011330 return 0;
11331 if (CastSrcTy) {
11332 if (I->getOperand(0)->getType() != CastSrcTy)
11333 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011334 } else if (I->getOperand(1) != ConstantOp) {
11335 return 0;
11336 }
11337 }
11338
11339 // Okay, they are all the same operation. Create a new PHI node of the
11340 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000011341 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11342 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011343 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11344
11345 Value *InVal = FirstInst->getOperand(0);
11346 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11347
11348 // Add all operands to the new PHI.
11349 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11350 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11351 if (NewInVal != InVal)
11352 InVal = 0;
11353 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11354 }
11355
11356 Value *PhiVal;
11357 if (InVal) {
11358 // The new PHI unions all of the same values together. This is really
11359 // common, so we handle it intelligently here for compile-time speed.
11360 PhiVal = InVal;
11361 delete NewPN;
11362 } else {
11363 InsertNewInstBefore(NewPN, PN);
11364 PhiVal = NewPN;
11365 }
11366
11367 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +000011368 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011369 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +000011370
Chris Lattnerfc984e92008-04-29 17:13:43 +000011371 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011372 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +000011373
Chris Lattner38751f82009-11-01 20:04:24 +000011374 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11375 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11376 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011377}
11378
11379/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11380/// that is dead.
11381static bool DeadPHICycle(PHINode *PN,
11382 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11383 if (PN->use_empty()) return true;
11384 if (!PN->hasOneUse()) return false;
11385
11386 // Remember this node, and if we find the cycle, return.
11387 if (!PotentiallyDeadPHIs.insert(PN))
11388 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000011389
11390 // Don't scan crazily complex things.
11391 if (PotentiallyDeadPHIs.size() == 16)
11392 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011393
11394 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11395 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11396
11397 return false;
11398}
11399
Chris Lattner27b695d2007-11-06 21:52:06 +000011400/// PHIsEqualValue - Return true if this phi node is always equal to
11401/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11402/// z = some value; x = phi (y, z); y = phi (x, z)
11403static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11404 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11405 // See if we already saw this PHI node.
11406 if (!ValueEqualPHIs.insert(PN))
11407 return true;
11408
11409 // Don't scan crazily complex things.
11410 if (ValueEqualPHIs.size() == 16)
11411 return false;
11412
11413 // Scan the operands to see if they are either phi nodes or are equal to
11414 // the value.
11415 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11416 Value *Op = PN->getIncomingValue(i);
11417 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11418 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11419 return false;
11420 } else if (Op != NonPhiInVal)
11421 return false;
11422 }
11423
11424 return true;
11425}
11426
11427
Chris Lattner1cd526b2009-11-08 19:23:30 +000011428namespace {
11429struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +000011430 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +000011431 unsigned Shift; // The amount shifted.
11432 Instruction *Inst; // The trunc instruction.
11433
Chris Lattner073c12c2009-11-09 01:38:00 +000011434 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11435 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +000011436
11437 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +000011438 if (PHIId < RHS.PHIId) return true;
11439 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011440 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +000011441 if (Shift > RHS.Shift) return false;
11442 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +000011443 RHS.Inst->getType()->getPrimitiveSizeInBits();
11444 }
11445};
Chris Lattner073c12c2009-11-09 01:38:00 +000011446
11447struct LoweredPHIRecord {
11448 PHINode *PN; // The PHI that was lowered.
11449 unsigned Shift; // The amount shifted.
11450 unsigned Width; // The width extracted.
11451
11452 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11453 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11454
11455 // Ctor form used by DenseMap.
11456 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11457 : PN(pn), Shift(Sh), Width(0) {}
11458};
11459}
11460
11461namespace llvm {
11462 template<>
11463 struct DenseMapInfo<LoweredPHIRecord> {
11464 static inline LoweredPHIRecord getEmptyKey() {
11465 return LoweredPHIRecord(0, 0);
11466 }
11467 static inline LoweredPHIRecord getTombstoneKey() {
11468 return LoweredPHIRecord(0, 1);
11469 }
11470 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11471 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11472 (Val.Width>>3);
11473 }
11474 static bool isEqual(const LoweredPHIRecord &LHS,
11475 const LoweredPHIRecord &RHS) {
11476 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11477 LHS.Width == RHS.Width;
11478 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011479 };
Chris Lattner169f3a22009-12-15 07:26:43 +000011480 template <>
11481 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner1cd526b2009-11-08 19:23:30 +000011482}
11483
11484
11485/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11486/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11487/// so, we split the PHI into the various pieces being extracted. This sort of
11488/// thing is introduced when SROA promotes an aggregate to large integer values.
11489///
11490/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11491/// inttoptr. We should produce new PHIs in the right type.
11492///
Chris Lattner073c12c2009-11-09 01:38:00 +000011493Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11494 // PHIUsers - Keep track of all of the truncated values extracted from a set
11495 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011496 SmallVector<PHIUsageRecord, 16> PHIUsers;
11497
Chris Lattner073c12c2009-11-09 01:38:00 +000011498 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11499 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11500 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11501 // check the uses of (to ensure they are all extracts).
11502 SmallVector<PHINode*, 8> PHIsToSlice;
11503 SmallPtrSet<PHINode*, 8> PHIsInspected;
11504
11505 PHIsToSlice.push_back(&FirstPhi);
11506 PHIsInspected.insert(&FirstPhi);
11507
11508 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11509 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011510
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011511 // Scan the input list of the PHI. If any input is an invoke, and if the
11512 // input is defined in the predecessor, then we won't be split the critical
11513 // edge which is required to insert a truncate. Because of this, we have to
11514 // bail out.
11515 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11516 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11517 if (II == 0) continue;
11518 if (II->getParent() != PN->getIncomingBlock(i))
11519 continue;
11520
11521 // If we have a phi, and if it's directly in the predecessor, then we have
11522 // a critical edge where we need to put the truncate. Since we can't
11523 // split the edge in instcombine, we have to bail out.
11524 return 0;
11525 }
11526
11527
Chris Lattner073c12c2009-11-09 01:38:00 +000011528 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11529 UI != E; ++UI) {
11530 Instruction *User = cast<Instruction>(*UI);
11531
11532 // If the user is a PHI, inspect its uses recursively.
11533 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11534 if (PHIsInspected.insert(UserPN))
11535 PHIsToSlice.push_back(UserPN);
11536 continue;
11537 }
11538
11539 // Truncates are always ok.
11540 if (isa<TruncInst>(User)) {
11541 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11542 continue;
11543 }
11544
11545 // Otherwise it must be a lshr which can only be used by one trunc.
11546 if (User->getOpcode() != Instruction::LShr ||
11547 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11548 !isa<ConstantInt>(User->getOperand(1)))
11549 return 0;
11550
11551 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11552 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011553 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011554 }
11555
11556 // If we have no users, they must be all self uses, just nuke the PHI.
11557 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +000011558 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011559
11560 // If this phi node is transformable, create new PHIs for all the pieces
11561 // extracted out of it. First, sort the users by their offset and size.
11562 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11563
Chris Lattner073c12c2009-11-09 01:38:00 +000011564 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11565 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11566 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11567 );
Chris Lattner1cd526b2009-11-08 19:23:30 +000011568
Chris Lattner073c12c2009-11-09 01:38:00 +000011569 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11570 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011571 DenseMap<BasicBlock*, Value*> PredValues;
11572
Chris Lattner073c12c2009-11-09 01:38:00 +000011573 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11574 // introduce redundant PHIs.
11575 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11576
11577 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11578 unsigned PHIId = PHIUsers[UserI].PHIId;
11579 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011580 unsigned Offset = PHIUsers[UserI].Shift;
11581 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011582
Chris Lattner073c12c2009-11-09 01:38:00 +000011583 PHINode *EltPHI;
11584
11585 // If we've already lowered a user like this, reuse the previously lowered
11586 // value.
11587 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +000011588
Chris Lattner073c12c2009-11-09 01:38:00 +000011589 // Otherwise, Create the new PHI node for this user.
11590 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11591 assert(EltPHI->getType() != PN->getType() &&
11592 "Truncate didn't shrink phi?");
11593
11594 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11595 BasicBlock *Pred = PN->getIncomingBlock(i);
11596 Value *&PredVal = PredValues[Pred];
11597
11598 // If we already have a value for this predecessor, reuse it.
11599 if (PredVal) {
11600 EltPHI->addIncoming(PredVal, Pred);
11601 continue;
11602 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011603
Chris Lattner073c12c2009-11-09 01:38:00 +000011604 // Handle the PHI self-reuse case.
11605 Value *InVal = PN->getIncomingValue(i);
11606 if (InVal == PN) {
11607 PredVal = EltPHI;
11608 EltPHI->addIncoming(PredVal, Pred);
11609 continue;
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011610 }
11611
11612 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattner073c12c2009-11-09 01:38:00 +000011613 // If the incoming value was a PHI, and if it was one of the PHIs we
11614 // already rewrote it, just use the lowered value.
11615 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11616 PredVal = Res;
11617 EltPHI->addIncoming(PredVal, Pred);
11618 continue;
11619 }
11620 }
11621
11622 // Otherwise, do an extract in the predecessor.
11623 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11624 Value *Res = InVal;
11625 if (Offset)
11626 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11627 Offset), "extract");
11628 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11629 PredVal = Res;
11630 EltPHI->addIncoming(Res, Pred);
11631
11632 // If the incoming value was a PHI, and if it was one of the PHIs we are
11633 // rewriting, we will ultimately delete the code we inserted. This
11634 // means we need to revisit that PHI to make sure we extract out the
11635 // needed piece.
11636 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11637 if (PHIsInspected.count(OldInVal)) {
11638 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11639 OldInVal)-PHIsToSlice.begin();
11640 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11641 cast<Instruction>(Res)));
11642 ++UserE;
11643 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011644 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011645 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011646
Chris Lattner073c12c2009-11-09 01:38:00 +000011647 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11648 << *EltPHI << '\n');
11649 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011650 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011651
Chris Lattner073c12c2009-11-09 01:38:00 +000011652 // Replace the use of this piece with the PHI node.
11653 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011654 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011655
11656 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11657 // with undefs.
11658 Value *Undef = UndefValue::get(FirstPhi.getType());
11659 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11660 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11661 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011662}
11663
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011664// PHINode simplification
11665//
11666Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11667 // If LCSSA is around, don't mess with Phi nodes
11668 if (MustPreserveLCSSA) return 0;
11669
11670 if (Value *V = PN.hasConstantValue())
11671 return ReplaceInstUsesWith(PN, V);
11672
11673 // If all PHI operands are the same operation, pull them through the PHI,
11674 // reducing code size.
11675 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000011676 isa<Instruction>(PN.getIncomingValue(1)) &&
11677 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11678 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11679 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11680 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011681 PN.getIncomingValue(0)->hasOneUse())
11682 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11683 return Result;
11684
11685 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11686 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11687 // PHI)... break the cycle.
11688 if (PN.hasOneUse()) {
11689 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11690 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11691 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11692 PotentiallyDeadPHIs.insert(&PN);
11693 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011694 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011695 }
11696
11697 // If this phi has a single use, and if that use just computes a value for
11698 // the next iteration of a loop, delete the phi. This occurs with unused
11699 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11700 // common case here is good because the only other things that catch this
11701 // are induction variable analysis (sometimes) and ADCE, which is only run
11702 // late.
11703 if (PHIUser->hasOneUse() &&
11704 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11705 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011706 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011707 }
11708 }
11709
Chris Lattner27b695d2007-11-06 21:52:06 +000011710 // We sometimes end up with phi cycles that non-obviously end up being the
11711 // same value, for example:
11712 // z = some value; x = phi (y, z); y = phi (x, z)
11713 // where the phi nodes don't necessarily need to be in the same block. Do a
11714 // quick check to see if the PHI node only contains a single non-phi value, if
11715 // so, scan to see if the phi cycle is actually equal to that value.
11716 {
11717 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11718 // Scan for the first non-phi operand.
11719 while (InValNo != NumOperandVals &&
11720 isa<PHINode>(PN.getIncomingValue(InValNo)))
11721 ++InValNo;
11722
11723 if (InValNo != NumOperandVals) {
11724 Value *NonPhiInVal = PN.getOperand(InValNo);
11725
11726 // Scan the rest of the operands to see if there are any conflicts, if so
11727 // there is no need to recursively scan other phis.
11728 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11729 Value *OpVal = PN.getIncomingValue(InValNo);
11730 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11731 break;
11732 }
11733
11734 // If we scanned over all operands, then we have one unique value plus
11735 // phi values. Scan PHI nodes to see if they all merge in each other or
11736 // the value.
11737 if (InValNo == NumOperandVals) {
11738 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11739 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11740 return ReplaceInstUsesWith(PN, NonPhiInVal);
11741 }
11742 }
11743 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011744
Dan Gohman2cc8e842009-10-31 14:22:52 +000011745 // If there are multiple PHIs, sort their operands so that they all list
11746 // the blocks in the same order. This will help identical PHIs be eliminated
11747 // by other passes. Other passes shouldn't depend on this for correctness
11748 // however.
11749 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11750 if (&PN != FirstPN)
11751 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +000011752 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +000011753 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11754 if (BBA != BBB) {
11755 Value *VA = PN.getIncomingValue(i);
11756 unsigned j = PN.getBasicBlockIndex(BBB);
11757 Value *VB = PN.getIncomingValue(j);
11758 PN.setIncomingBlock(i, BBB);
11759 PN.setIncomingValue(i, VB);
11760 PN.setIncomingBlock(j, BBA);
11761 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +000011762 // NOTE: Instcombine normally would want us to "return &PN" if we
11763 // modified any of the operands of an instruction. However, since we
11764 // aren't adding or removing uses (just rearranging them) we don't do
11765 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +000011766 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011767 }
11768
Chris Lattner1cd526b2009-11-08 19:23:30 +000011769 // If this is an integer PHI and we know that it has an illegal type, see if
11770 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11771 // PHI into the various pieces being extracted. This sort of thing is
11772 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +000011773 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +000011774 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11775 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11776 return Res;
11777
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011778 return 0;
11779}
11780
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011781Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +000011782 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11783
11784 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11785 return ReplaceInstUsesWith(GEP, V);
11786
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011787 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011788
11789 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011790 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011791
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011792 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011793 if (TD) {
11794 bool MadeChange = false;
11795 unsigned PtrSize = TD->getPointerSizeInBits();
11796
11797 gep_type_iterator GTI = gep_type_begin(GEP);
11798 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11799 I != E; ++I, ++GTI) {
11800 if (!isa<SequentialType>(*GTI)) continue;
11801
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011802 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011803 // to what we need. If narrower, sign-extend it to what we need. This
11804 // explicit cast can make subsequent optimizations more obvious.
11805 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011806 if (OpBits == PtrSize)
11807 continue;
11808
Chris Lattnerd6164c22009-08-30 20:01:10 +000011809 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011810 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011811 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011812 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011813 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011814
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011815 // Combine Indices - If the source pointer to this getelementptr instruction
11816 // is a getelementptr instruction, combine the indices of the two
11817 // getelementptr instructions into a single instruction.
11818 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011819 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011820 // Note that if our source is a gep chain itself that we wait for that
11821 // chain to be resolved before we perform this transformation. This
11822 // avoids us creating a TON of code in some cases.
11823 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011824 if (GetElementPtrInst *SrcGEP =
11825 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11826 if (SrcGEP->getNumOperands() == 2)
11827 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011828
11829 SmallVector<Value*, 8> Indices;
11830
11831 // Find out whether the last index in the source GEP is a sequential idx.
11832 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000011833 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11834 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011835 EndsWithSequential = !isa<StructType>(*I);
11836
11837 // Can we combine the two pointer arithmetics offsets?
11838 if (EndsWithSequential) {
11839 // Replace: gep (gep %P, long B), long A, ...
11840 // With: T = long A+B; gep %P, T, ...
11841 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011842 Value *Sum;
11843 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11844 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011845 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011846 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011847 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011848 Sum = SO1;
11849 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000011850 // If they aren't the same type, then the input hasn't been processed
11851 // by the loop above yet (which canonicalizes sequential index types to
11852 // intptr_t). Just avoid transforming this until the input has been
11853 // normalized.
11854 if (SO1->getType() != GO1->getType())
11855 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000011856 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011857 }
11858
Chris Lattner1c641fc2009-08-30 05:30:55 +000011859 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011860 if (Src->getNumOperands() == 2) {
11861 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011862 GEP.setOperand(1, Sum);
11863 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011864 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011865 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011866 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011867 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011868 } else if (isa<Constant>(*GEP.idx_begin()) &&
11869 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011870 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011871 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011872 Indices.append(Src->op_begin()+1, Src->op_end());
11873 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011874 }
11875
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011876 if (!Indices.empty())
11877 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11878 Src->isInBounds()) ?
11879 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11880 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011881 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011882 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011883 }
11884
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011885 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11886 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011887 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011888
Chris Lattner83288fa2009-08-30 20:38:21 +000011889 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11890 // want to change the gep until the bitcasts are eliminated.
11891 if (getBitCastOperand(X)) {
11892 Worklist.AddValue(PtrOp);
11893 return 0;
11894 }
11895
Chris Lattner5594a482009-11-27 00:29:05 +000011896 bool HasZeroPointerIndex = false;
11897 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11898 HasZeroPointerIndex = C->isZero();
11899
Chris Lattnerf3a23592009-08-30 20:36:46 +000011900 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11901 // into : GEP [10 x i8]* X, i32 0, ...
11902 //
11903 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11904 // into : GEP i8* X, ...
11905 //
11906 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011907 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011908 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11909 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011910 if (const ArrayType *CATy =
11911 dyn_cast<ArrayType>(CPTy->getElementType())) {
11912 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11913 if (CATy->getElementType() == XTy->getElementType()) {
11914 // -> GEP i8* X, ...
11915 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011916 return cast<GEPOperator>(&GEP)->isInBounds() ?
11917 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11918 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011919 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11920 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011921 }
11922
11923 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011924 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011925 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011926 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011927 // At this point, we know that the cast source type is a pointer
11928 // to an array of the same type as the destination pointer
11929 // array. Because the array type is never stepped over (there
11930 // is a leading zero) we can fold the cast into this GEP.
11931 GEP.setOperand(0, X);
11932 return &GEP;
11933 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011934 }
11935 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011936 } else if (GEP.getNumOperands() == 2) {
11937 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011938 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11939 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011940 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11941 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011942 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011943 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11944 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011945 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011946 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011947 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011948 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11949 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011950 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011951 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011952 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011953 }
11954
11955 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011956 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011957 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011958 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011959
Owen Anderson35b47072009-08-13 21:58:54 +000011960 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011961 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011962 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011963
11964 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11965 // allow either a mul, shift, or constant here.
11966 Value *NewIdx = 0;
11967 ConstantInt *Scale = 0;
11968 if (ArrayEltSize == 1) {
11969 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011970 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011971 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011972 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011973 Scale = CI;
11974 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11975 if (Inst->getOpcode() == Instruction::Shl &&
11976 isa<ConstantInt>(Inst->getOperand(1))) {
11977 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11978 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011979 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011980 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011981 NewIdx = Inst->getOperand(0);
11982 } else if (Inst->getOpcode() == Instruction::Mul &&
11983 isa<ConstantInt>(Inst->getOperand(1))) {
11984 Scale = cast<ConstantInt>(Inst->getOperand(1));
11985 NewIdx = Inst->getOperand(0);
11986 }
11987 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011988
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011989 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011990 // out, perform the transformation. Note, we don't know whether Scale is
11991 // signed or not. We'll use unsigned version of division/modulo
11992 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011993 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011994 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011995 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011996 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011997 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011998 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11999 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000012000 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012001 }
12002
12003 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000012004 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000012005 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000012006 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012007 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12008 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12009 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012010 // The NewGEP must be pointer typed, so must the old one -> BitCast
12011 return new BitCastInst(NewGEP, GEP.getType());
12012 }
12013 }
12014 }
12015 }
Chris Lattner111ea772009-01-09 04:53:57 +000012016
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012017 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000012018 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012019 /// Y = gep X, <...constant indices...>
12020 /// into a gep of the original struct. This is important for SROA and alias
12021 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000012022 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000012023 if (TD &&
12024 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012025 // Determine how much the GEP moves the pointer. We are guaranteed to get
12026 // a constant back from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +000012027 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012028 int64_t Offset = OffsetV->getSExtValue();
12029
12030 // If this GEP instruction doesn't move the pointer, just replace the GEP
12031 // with a bitcast of the real input to the dest type.
12032 if (Offset == 0) {
12033 // If the bitcast is of an allocation, and the allocation will be
12034 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000012035 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000012036 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012037 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12038 if (Instruction *I = visitBitCast(*BCI)) {
12039 if (I != BCI) {
12040 I->takeName(BCI);
12041 BCI->getParent()->getInstList().insert(BCI, I);
12042 ReplaceInstUsesWith(*BCI, I);
12043 }
12044 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000012045 }
Chris Lattner111ea772009-01-09 04:53:57 +000012046 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012047 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000012048 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012049
12050 // Otherwise, if the offset is non-zero, we need to find out if there is a
12051 // field at Offset in 'A's type. If so, we can pull the cast through the
12052 // GEP.
12053 SmallVector<Value*, 8> NewIndices;
12054 const Type *InTy =
12055 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000012056 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012057 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12058 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12059 NewIndices.end()) :
12060 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12061 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000012062
12063 if (NGEP->getType() == GEP.getType())
12064 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012065 NGEP->takeName(&GEP);
12066 return new BitCastInst(NGEP, GEP.getType());
12067 }
Chris Lattner111ea772009-01-09 04:53:57 +000012068 }
12069 }
12070
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012071 return 0;
12072}
12073
Victor Hernandezb1687302009-10-23 21:09:37 +000012074Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +000012075 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000012076 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012077 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12078 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012079 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000012080 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000012081 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000012082 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012083
12084 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000012085 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012086 //
12087 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000012088 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012089
12090 // Now that I is pointing to the first non-allocation-inst in the block,
12091 // insert our getelementptr instruction...
12092 //
Owen Anderson35b47072009-08-13 21:58:54 +000012093 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000012094 Value *Idx[2];
12095 Idx[0] = NullIdx;
12096 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012097 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12098 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012099
12100 // Now make everything use the getelementptr instead of the original
12101 // allocation.
12102 return ReplaceInstUsesWith(AI, V);
12103 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000012104 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012105 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000012106 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012107
Dan Gohmana80e2712009-07-21 23:21:54 +000012108 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000012109 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000012110 // Note that we only do this for alloca's, because malloc should allocate
12111 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000012112 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000012113 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000012114
12115 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12116 if (AI.getAlignment() == 0)
12117 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12118 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012119
12120 return 0;
12121}
12122
Victor Hernandez93946082009-10-24 04:23:03 +000012123Instruction *InstCombiner::visitFree(Instruction &FI) {
12124 Value *Op = FI.getOperand(1);
12125
12126 // free undef -> unreachable.
12127 if (isa<UndefValue>(Op)) {
12128 // Insert a new store to null because we cannot modify the CFG here.
12129 new StoreInst(ConstantInt::getTrue(*Context),
12130 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12131 return EraseInstFromFunction(FI);
12132 }
12133
12134 // If we have 'free null' delete the instruction. This can happen in stl code
12135 // when lots of inlining happens.
12136 if (isa<ConstantPointerNull>(Op))
12137 return EraseInstFromFunction(FI);
12138
Victor Hernandezf9a7a332009-10-26 23:43:48 +000012139 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +000012140 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +000012141 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12142 if (Op->hasOneUse() && CI->hasOneUse()) {
12143 EraseInstFromFunction(FI);
12144 EraseInstFromFunction(*CI);
12145 return EraseInstFromFunction(*cast<Instruction>(Op));
12146 }
12147 } else {
12148 // Op is a call to malloc
12149 if (Op->hasOneUse()) {
12150 EraseInstFromFunction(FI);
12151 return EraseInstFromFunction(*cast<Instruction>(Op));
12152 }
12153 }
Dan Gohman1674ea52009-10-27 00:11:02 +000012154 }
Victor Hernandez93946082009-10-24 04:23:03 +000012155
12156 return 0;
12157}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012158
12159/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000012160static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000012161 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012162 User *CI = cast<User>(LI.getOperand(0));
12163 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000012164 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012165
Mon P Wangbd05ed82009-02-07 22:19:29 +000012166 const PointerType *DestTy = cast<PointerType>(CI->getType());
12167 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012168 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000012169
12170 // If the address spaces don't match, don't eliminate the cast.
12171 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12172 return 0;
12173
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012174 const Type *SrcPTy = SrcTy->getElementType();
12175
12176 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
12177 isa<VectorType>(DestPTy)) {
12178 // If the source is an array, the code below will not succeed. Check to
12179 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12180 // constants.
12181 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12182 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12183 if (ASrcTy->getNumElements() != 0) {
12184 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000012185 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12186 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000012187 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012188 SrcTy = cast<PointerType>(CastOp->getType());
12189 SrcPTy = SrcTy->getElementType();
12190 }
12191
Dan Gohmana80e2712009-07-21 23:21:54 +000012192 if (IC.getTargetData() &&
12193 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012194 isa<VectorType>(SrcPTy)) &&
12195 // Do not allow turning this into a load of an integer, which is then
12196 // casted to a pointer, this pessimizes pointer analysis a lot.
12197 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000012198 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12199 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012200
12201 // Okay, we are casting from one integer or pointer type to another of
12202 // the same size. Instead of casting the pointer before the load, cast
12203 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000012204 Value *NewLoad =
12205 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012206 // Now cast the result of the load.
12207 return new BitCastInst(NewLoad, LI.getType());
12208 }
12209 }
12210 }
12211 return 0;
12212}
12213
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012214Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12215 Value *Op = LI.getOperand(0);
12216
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012217 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012218 if (TD) {
12219 unsigned KnownAlign =
12220 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12221 if (KnownAlign >
12222 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12223 LI.getAlignment()))
12224 LI.setAlignment(KnownAlign);
12225 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012226
Chris Lattnerf3a23592009-08-30 20:36:46 +000012227 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012228 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000012229 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012230 return Res;
12231
12232 // None of the following transforms are legal for volatile loads.
12233 if (LI.isVolatile()) return 0;
12234
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012235 // Do really simple store-to-load forwarding and load CSE, to catch cases
12236 // where there are several consequtive memory accesses to the same location,
12237 // separated by a few arithmetic operations.
12238 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000012239 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12240 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012241
Chris Lattner05274832009-10-22 06:25:11 +000012242 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000012243 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12244 const Value *GEPI0 = GEPI->getOperand(0);
12245 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000012246 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012247 // Insert a new store to null instruction before the load to indicate
12248 // that this code is not reachable. We do this instead of inserting
12249 // an unreachable instruction directly because we cannot modify the
12250 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012251 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000012252 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012253 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012254 }
Christopher Lamb2c175392007-12-29 07:56:53 +000012255 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012256
Chris Lattner05274832009-10-22 06:25:11 +000012257 // load null/undef -> unreachable
12258 // TODO: Consider a target hook for valid address spaces for this xform.
12259 if (isa<UndefValue>(Op) ||
12260 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12261 // Insert a new store to null instruction before the load to indicate that
12262 // this code is not reachable. We do this instead of inserting an
12263 // unreachable instruction directly because we cannot modify the CFG.
12264 new StoreInst(UndefValue::get(LI.getType()),
12265 Constant::getNullValue(Op->getType()), &LI);
12266 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012267 }
Chris Lattner05274832009-10-22 06:25:11 +000012268
12269 // Instcombine load (constantexpr_cast global) -> cast (load global)
12270 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12271 if (CE->isCast())
12272 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12273 return Res;
12274
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012275 if (Op->hasOneUse()) {
12276 // Change select and PHI nodes to select values instead of addresses: this
12277 // helps alias analysis out a lot, allows many others simplifications, and
12278 // exposes redundancy in the code.
12279 //
12280 // Note that we cannot do the transformation unless we know that the
12281 // introduced loads cannot trap! Something like this is valid as long as
12282 // the condition is always false: load (select bool %C, int* null, int* %G),
12283 // but it would not be valid if we transformed it to load from null
12284 // unconditionally.
12285 //
12286 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12287 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
12288 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12289 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000012290 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12291 SI->getOperand(1)->getName()+".val");
12292 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12293 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000012294 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012295 }
12296
12297 // load (select (cond, null, P)) -> load P
12298 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12299 if (C->isNullValue()) {
12300 LI.setOperand(0, SI->getOperand(2));
12301 return &LI;
12302 }
12303
12304 // load (select (cond, P, null)) -> load P
12305 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12306 if (C->isNullValue()) {
12307 LI.setOperand(0, SI->getOperand(1));
12308 return &LI;
12309 }
12310 }
12311 }
12312 return 0;
12313}
12314
12315/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000012316/// when possible. This makes it generally easy to do alias analysis and/or
12317/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012318static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12319 User *CI = cast<User>(SI.getOperand(1));
12320 Value *CastOp = CI->getOperand(0);
12321
12322 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000012323 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12324 if (SrcTy == 0) return 0;
12325
12326 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012327
Chris Lattnera032c0e2009-01-16 20:08:59 +000012328 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12329 return 0;
12330
Chris Lattner54dddc72009-01-24 01:00:13 +000012331 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12332 /// to its first element. This allows us to handle things like:
12333 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12334 /// on 32-bit hosts.
12335 SmallVector<Value*, 4> NewGEPIndices;
12336
Chris Lattnera032c0e2009-01-16 20:08:59 +000012337 // If the source is an array, the code below will not succeed. Check to
12338 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12339 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000012340 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12341 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000012342 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000012343 NewGEPIndices.push_back(Zero);
12344
12345 while (1) {
12346 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000012347 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000012348 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000012349 NewGEPIndices.push_back(Zero);
12350 SrcPTy = STy->getElementType(0);
12351 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12352 NewGEPIndices.push_back(Zero);
12353 SrcPTy = ATy->getElementType();
12354 } else {
12355 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012356 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012357 }
12358
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012359 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000012360 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000012361
12362 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12363 return 0;
12364
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012365 // If the pointers point into different address spaces or if they point to
12366 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000012367 if (!IC.getTargetData() ||
12368 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012369 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000012370 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12371 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000012372 return 0;
12373
12374 // Okay, we are casting from one integer or pointer type to another of
12375 // the same size. Instead of casting the pointer before
12376 // the store, cast the value to be stored.
12377 Value *NewCast;
12378 Value *SIOp0 = SI.getOperand(0);
12379 Instruction::CastOps opcode = Instruction::BitCast;
12380 const Type* CastSrcTy = SIOp0->getType();
12381 const Type* CastDstTy = SrcPTy;
12382 if (isa<PointerType>(CastDstTy)) {
12383 if (CastSrcTy->isInteger())
12384 opcode = Instruction::IntToPtr;
12385 } else if (isa<IntegerType>(CastDstTy)) {
12386 if (isa<PointerType>(SIOp0->getType()))
12387 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012388 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012389
12390 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12391 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012392 if (!NewGEPIndices.empty())
12393 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12394 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000012395
Chris Lattnerad7516a2009-08-30 18:50:58 +000012396 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12397 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000012398 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012399}
12400
Chris Lattner6fd8c802008-11-27 08:56:30 +000012401/// equivalentAddressValues - Test if A and B will obviously have the same
12402/// value. This includes recognizing that %t0 and %t1 will have the same
12403/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000012404/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012405/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000012406/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012407/// %t2 = load i32* %t1
12408///
12409static bool equivalentAddressValues(Value *A, Value *B) {
12410 // Test if the values are trivially equivalent.
12411 if (A == B) return true;
12412
12413 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012414 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12415 // its only used to compare two uses within the same basic block, which
12416 // means that they'll always either have the same value or one of them
12417 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000012418 if (isa<BinaryOperator>(A) ||
12419 isa<CastInst>(A) ||
12420 isa<PHINode>(A) ||
12421 isa<GetElementPtrInst>(A))
12422 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012423 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000012424 return true;
12425
12426 // Otherwise they may not be equivalent.
12427 return false;
12428}
12429
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012430// If this instruction has two uses, one of which is a llvm.dbg.declare,
12431// return the llvm.dbg.declare.
12432DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12433 if (!V->hasNUses(2))
12434 return 0;
12435 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12436 UI != E; ++UI) {
12437 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12438 return DI;
12439 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12440 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12441 return DI;
12442 }
12443 }
12444 return 0;
12445}
12446
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012447Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12448 Value *Val = SI.getOperand(0);
12449 Value *Ptr = SI.getOperand(1);
12450
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012451 // If the RHS is an alloca with a single use, zapify the store, making the
12452 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012453 // If the RHS is an alloca with a two uses, the other one being a
12454 // llvm.dbg.declare, zapify the store and the declare, making the
12455 // alloca dead. We must do this to prevent declare's from affecting
12456 // codegen.
12457 if (!SI.isVolatile()) {
12458 if (Ptr->hasOneUse()) {
12459 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012460 EraseInstFromFunction(SI);
12461 ++NumCombined;
12462 return 0;
12463 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012464 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12465 if (isa<AllocaInst>(GEP->getOperand(0))) {
12466 if (GEP->getOperand(0)->hasOneUse()) {
12467 EraseInstFromFunction(SI);
12468 ++NumCombined;
12469 return 0;
12470 }
12471 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12472 EraseInstFromFunction(*DI);
12473 EraseInstFromFunction(SI);
12474 ++NumCombined;
12475 return 0;
12476 }
12477 }
12478 }
12479 }
12480 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12481 EraseInstFromFunction(*DI);
12482 EraseInstFromFunction(SI);
12483 ++NumCombined;
12484 return 0;
12485 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012486 }
12487
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012488 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012489 if (TD) {
12490 unsigned KnownAlign =
12491 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12492 if (KnownAlign >
12493 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12494 SI.getAlignment()))
12495 SI.setAlignment(KnownAlign);
12496 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012497
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012498 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012499 // stores to the same location, separated by a few arithmetic operations. This
12500 // situation often occurs with bitfield accesses.
12501 BasicBlock::iterator BBI = &SI;
12502 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12503 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000012504 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000012505 // Don't count debug info directives, lest they affect codegen,
12506 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12507 // It is necessary for correctness to skip those that feed into a
12508 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000012509 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000012510 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012511 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012512 continue;
12513 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012514
12515 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12516 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000012517 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12518 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012519 ++NumDeadStore;
12520 ++BBI;
12521 EraseInstFromFunction(*PrevSI);
12522 continue;
12523 }
12524 break;
12525 }
12526
12527 // If this is a load, we have to stop. However, if the loaded value is from
12528 // the pointer we're loading and is producing the pointer we're storing,
12529 // then *this* store is dead (X = load P; store X -> P).
12530 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012531 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12532 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012533 EraseInstFromFunction(SI);
12534 ++NumCombined;
12535 return 0;
12536 }
12537 // Otherwise, this is a load from some other location. Stores before it
12538 // may not be dead.
12539 break;
12540 }
12541
12542 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000012543 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012544 break;
12545 }
12546
12547
12548 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12549
12550 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000012551 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012552 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012553 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012554 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000012555 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012556 ++NumCombined;
12557 }
12558 return 0; // Do not modify these!
12559 }
12560
12561 // store undef, Ptr -> noop
12562 if (isa<UndefValue>(Val)) {
12563 EraseInstFromFunction(SI);
12564 ++NumCombined;
12565 return 0;
12566 }
12567
12568 // If the pointer destination is a cast, see if we can fold the cast into the
12569 // source instead.
12570 if (isa<CastInst>(Ptr))
12571 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12572 return Res;
12573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12574 if (CE->isCast())
12575 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12576 return Res;
12577
12578
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012579 // If this store is the last instruction in the basic block (possibly
12580 // excepting debug info instructions and the pointer bitcasts that feed
12581 // into them), and if the block ends with an unconditional branch, try
12582 // to move it to the successor block.
12583 BBI = &SI;
12584 do {
12585 ++BBI;
12586 } while (isa<DbgInfoIntrinsic>(BBI) ||
12587 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012588 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12589 if (BI->isUnconditional())
12590 if (SimplifyStoreAtEndOfBlock(SI))
12591 return 0; // xform done!
12592
12593 return 0;
12594}
12595
12596/// SimplifyStoreAtEndOfBlock - Turn things like:
12597/// if () { *P = v1; } else { *P = v2 }
12598/// into a phi node with a store in the successor.
12599///
12600/// Simplify things like:
12601/// *P = v1; if () { *P = v2; }
12602/// into a phi node with a store in the successor.
12603///
12604bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12605 BasicBlock *StoreBB = SI.getParent();
12606
12607 // Check to see if the successor block has exactly two incoming edges. If
12608 // so, see if the other predecessor contains a store to the same location.
12609 // if so, insert a PHI node (if needed) and move the stores down.
12610 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12611
12612 // Determine whether Dest has exactly two predecessors and, if so, compute
12613 // the other predecessor.
12614 pred_iterator PI = pred_begin(DestBB);
12615 BasicBlock *OtherBB = 0;
12616 if (*PI != StoreBB)
12617 OtherBB = *PI;
12618 ++PI;
12619 if (PI == pred_end(DestBB))
12620 return false;
12621
12622 if (*PI != StoreBB) {
12623 if (OtherBB)
12624 return false;
12625 OtherBB = *PI;
12626 }
12627 if (++PI != pred_end(DestBB))
12628 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012629
12630 // Bail out if all the relevant blocks aren't distinct (this can happen,
12631 // for example, if SI is in an infinite loop)
12632 if (StoreBB == DestBB || OtherBB == DestBB)
12633 return false;
12634
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012635 // Verify that the other block ends in a branch and is not otherwise empty.
12636 BasicBlock::iterator BBI = OtherBB->getTerminator();
12637 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12638 if (!OtherBr || BBI == OtherBB->begin())
12639 return false;
12640
12641 // If the other block ends in an unconditional branch, check for the 'if then
12642 // else' case. there is an instruction before the branch.
12643 StoreInst *OtherStore = 0;
12644 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012645 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012646 // Skip over debugging info.
12647 while (isa<DbgInfoIntrinsic>(BBI) ||
12648 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12649 if (BBI==OtherBB->begin())
12650 return false;
12651 --BBI;
12652 }
Chris Lattner69fa3f52009-11-02 02:06:37 +000012653 // If this isn't a store, isn't a store to the same location, or if the
12654 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012655 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +000012656 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12657 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012658 return false;
12659 } else {
12660 // Otherwise, the other block ended with a conditional branch. If one of the
12661 // destinations is StoreBB, then we have the if/then case.
12662 if (OtherBr->getSuccessor(0) != StoreBB &&
12663 OtherBr->getSuccessor(1) != StoreBB)
12664 return false;
12665
12666 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12667 // if/then triangle. See if there is a store to the same ptr as SI that
12668 // lives in OtherBB.
12669 for (;; --BBI) {
12670 // Check to see if we find the matching store.
12671 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +000012672 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12673 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012674 return false;
12675 break;
12676 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012677 // If we find something that may be using or overwriting the stored
12678 // value, or if we run out of instructions, we can't do the xform.
12679 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012680 BBI == OtherBB->begin())
12681 return false;
12682 }
12683
12684 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012685 // make sure nothing reads or overwrites the stored value in
12686 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012687 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12688 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012689 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012690 return false;
12691 }
12692 }
12693
12694 // Insert a PHI node now if we need it.
12695 Value *MergedVal = OtherStore->getOperand(0);
12696 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012697 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012698 PN->reserveOperandSpace(2);
12699 PN->addIncoming(SI.getOperand(0), SI.getParent());
12700 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12701 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12702 }
12703
12704 // Advance to a place where it is safe to insert the new store and
12705 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012706 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012707 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +000012708 OtherStore->isVolatile(),
12709 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012710
12711 // Nuke the old stores.
12712 EraseInstFromFunction(SI);
12713 EraseInstFromFunction(*OtherStore);
12714 ++NumCombined;
12715 return true;
12716}
12717
12718
12719Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12720 // Change br (not X), label True, label False to: br X, label False, True
12721 Value *X = 0;
12722 BasicBlock *TrueDest;
12723 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012724 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012725 !isa<Constant>(X)) {
12726 // Swap Destinations and condition...
12727 BI.setCondition(X);
12728 BI.setSuccessor(0, FalseDest);
12729 BI.setSuccessor(1, TrueDest);
12730 return &BI;
12731 }
12732
12733 // Cannonicalize fcmp_one -> fcmp_oeq
12734 FCmpInst::Predicate FPred; Value *Y;
12735 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012736 TrueDest, FalseDest)) &&
12737 BI.getCondition()->hasOneUse())
12738 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12739 FPred == FCmpInst::FCMP_OGE) {
12740 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12741 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12742
12743 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012744 BI.setSuccessor(0, FalseDest);
12745 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012746 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012747 return &BI;
12748 }
12749
12750 // Cannonicalize icmp_ne -> icmp_eq
12751 ICmpInst::Predicate IPred;
12752 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012753 TrueDest, FalseDest)) &&
12754 BI.getCondition()->hasOneUse())
12755 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12756 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12757 IPred == ICmpInst::ICMP_SGE) {
12758 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12759 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12760 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012761 BI.setSuccessor(0, FalseDest);
12762 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012763 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012764 return &BI;
12765 }
12766
12767 return 0;
12768}
12769
12770Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12771 Value *Cond = SI.getCondition();
12772 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12773 if (I->getOpcode() == Instruction::Add)
12774 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12775 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12776 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012777 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012778 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012779 AddRHS));
12780 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012781 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012782 return &SI;
12783 }
12784 }
12785 return 0;
12786}
12787
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012788Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012789 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012790
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012791 if (!EV.hasIndices())
12792 return ReplaceInstUsesWith(EV, Agg);
12793
12794 if (Constant *C = dyn_cast<Constant>(Agg)) {
12795 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012796 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012797
12798 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012799 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012800
12801 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12802 // Extract the element indexed by the first index out of the constant
12803 Value *V = C->getOperand(*EV.idx_begin());
12804 if (EV.getNumIndices() > 1)
12805 // Extract the remaining indices out of the constant indexed by the
12806 // first index
12807 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12808 else
12809 return ReplaceInstUsesWith(EV, V);
12810 }
12811 return 0; // Can't handle other constants
12812 }
12813 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12814 // We're extracting from an insertvalue instruction, compare the indices
12815 const unsigned *exti, *exte, *insi, *inse;
12816 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12817 exte = EV.idx_end(), inse = IV->idx_end();
12818 exti != exte && insi != inse;
12819 ++exti, ++insi) {
12820 if (*insi != *exti)
12821 // The insert and extract both reference distinctly different elements.
12822 // This means the extract is not influenced by the insert, and we can
12823 // replace the aggregate operand of the extract with the aggregate
12824 // operand of the insert. i.e., replace
12825 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12826 // %E = extractvalue { i32, { i32 } } %I, 0
12827 // with
12828 // %E = extractvalue { i32, { i32 } } %A, 0
12829 return ExtractValueInst::Create(IV->getAggregateOperand(),
12830 EV.idx_begin(), EV.idx_end());
12831 }
12832 if (exti == exte && insi == inse)
12833 // Both iterators are at the end: Index lists are identical. Replace
12834 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12835 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12836 // with "i32 42"
12837 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12838 if (exti == exte) {
12839 // The extract list is a prefix of the insert list. i.e. replace
12840 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12841 // %E = extractvalue { i32, { i32 } } %I, 1
12842 // with
12843 // %X = extractvalue { i32, { i32 } } %A, 1
12844 // %E = insertvalue { i32 } %X, i32 42, 0
12845 // by switching the order of the insert and extract (though the
12846 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012847 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12848 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012849 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12850 insi, inse);
12851 }
12852 if (insi == inse)
12853 // The insert list is a prefix of the extract list
12854 // We can simply remove the common indices from the extract and make it
12855 // operate on the inserted value instead of the insertvalue result.
12856 // i.e., replace
12857 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12858 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12859 // with
12860 // %E extractvalue { i32 } { i32 42 }, 0
12861 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12862 exti, exte);
12863 }
Chris Lattner69a70752009-11-09 07:07:56 +000012864 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12865 // We're extracting from an intrinsic, see if we're the only user, which
12866 // allows us to simplify multiple result intrinsics to simpler things that
12867 // just get one value..
12868 if (II->hasOneUse()) {
12869 // Check if we're grabbing the overflow bit or the result of a 'with
12870 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12871 // and replace it with a traditional binary instruction.
12872 switch (II->getIntrinsicID()) {
12873 case Intrinsic::uadd_with_overflow:
12874 case Intrinsic::sadd_with_overflow:
12875 if (*EV.idx_begin() == 0) { // Normal result.
12876 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12877 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12878 EraseInstFromFunction(*II);
12879 return BinaryOperator::CreateAdd(LHS, RHS);
12880 }
12881 break;
12882 case Intrinsic::usub_with_overflow:
12883 case Intrinsic::ssub_with_overflow:
12884 if (*EV.idx_begin() == 0) { // Normal result.
12885 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12886 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12887 EraseInstFromFunction(*II);
12888 return BinaryOperator::CreateSub(LHS, RHS);
12889 }
12890 break;
12891 case Intrinsic::umul_with_overflow:
12892 case Intrinsic::smul_with_overflow:
12893 if (*EV.idx_begin() == 0) { // Normal result.
12894 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12895 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12896 EraseInstFromFunction(*II);
12897 return BinaryOperator::CreateMul(LHS, RHS);
12898 }
12899 break;
12900 default:
12901 break;
12902 }
12903 }
12904 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012905 // Can't simplify extracts from other values. Note that nested extracts are
12906 // already simplified implicitely by the above (extract ( extract (insert) )
12907 // will be translated into extract ( insert ( extract ) ) first and then just
12908 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012909 return 0;
12910}
12911
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012912/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12913/// is to leave as a vector operation.
12914static bool CheapToScalarize(Value *V, bool isConstant) {
12915 if (isa<ConstantAggregateZero>(V))
12916 return true;
12917 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12918 if (isConstant) return true;
12919 // If all elts are the same, we can extract.
12920 Constant *Op0 = C->getOperand(0);
12921 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12922 if (C->getOperand(i) != Op0)
12923 return false;
12924 return true;
12925 }
12926 Instruction *I = dyn_cast<Instruction>(V);
12927 if (!I) return false;
12928
12929 // Insert element gets simplified to the inserted element or is deleted if
12930 // this is constant idx extract element and its a constant idx insertelt.
12931 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12932 isa<ConstantInt>(I->getOperand(2)))
12933 return true;
12934 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12935 return true;
12936 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12937 if (BO->hasOneUse() &&
12938 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12939 CheapToScalarize(BO->getOperand(1), isConstant)))
12940 return true;
12941 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12942 if (CI->hasOneUse() &&
12943 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12944 CheapToScalarize(CI->getOperand(1), isConstant)))
12945 return true;
12946
12947 return false;
12948}
12949
12950/// Read and decode a shufflevector mask.
12951///
12952/// It turns undef elements into values that are larger than the number of
12953/// elements in the input.
12954static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12955 unsigned NElts = SVI->getType()->getNumElements();
12956 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12957 return std::vector<unsigned>(NElts, 0);
12958 if (isa<UndefValue>(SVI->getOperand(2)))
12959 return std::vector<unsigned>(NElts, 2*NElts);
12960
12961 std::vector<unsigned> Result;
12962 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012963 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12964 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012965 Result.push_back(NElts*2); // undef -> 8
12966 else
Gabor Greif17396002008-06-12 21:37:33 +000012967 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012968 return Result;
12969}
12970
12971/// FindScalarElement - Given a vector and an element number, see if the scalar
12972/// value is already around as a register, for example if it were inserted then
12973/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012974static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012975 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012976 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12977 const VectorType *PTy = cast<VectorType>(V->getType());
12978 unsigned Width = PTy->getNumElements();
12979 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012980 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012981
12982 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012983 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012984 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012985 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012986 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12987 return CP->getOperand(EltNo);
12988 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12989 // If this is an insert to a variable element, we don't know what it is.
12990 if (!isa<ConstantInt>(III->getOperand(2)))
12991 return 0;
12992 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12993
12994 // If this is an insert to the element we are looking for, return the
12995 // inserted value.
12996 if (EltNo == IIElt)
12997 return III->getOperand(1);
12998
12999 // Otherwise, the insertelement doesn't modify the value, recurse on its
13000 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000013001 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013002 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013003 unsigned LHSWidth =
13004 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013005 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013006 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000013007 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013008 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000013009 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013010 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000013011 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013012 }
13013
13014 // Otherwise, we don't know.
13015 return 0;
13016}
13017
13018Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013019 // If vector val is undef, replace extract with scalar undef.
13020 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013021 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013022
13023 // If vector val is constant 0, replace extract with scalar 0.
13024 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000013025 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013026
13027 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000013028 // If vector val is constant with all elements the same, replace EI with
13029 // that element. When the elements are not identical, we cannot replace yet
13030 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013031 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000013032 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013033 if (C->getOperand(i) != op0) {
13034 op0 = 0;
13035 break;
13036 }
13037 if (op0)
13038 return ReplaceInstUsesWith(EI, op0);
13039 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000013040
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013041 // If extracting a specified index from the vector, see if we can recursively
13042 // find a previously computed scalar that was inserted into the vector.
13043 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13044 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000013045 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013046
13047 // If this is extracting an invalid index, turn this into undef, to avoid
13048 // crashing the code below.
13049 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000013050 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013051
13052 // This instruction only demands the single element from the input vector.
13053 // If the input vector has a single use, simplify it based on this use
13054 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000013055 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000013056 APInt UndefElts(VectorWidth, 0);
13057 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013058 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000013059 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013060 EI.setOperand(0, V);
13061 return &EI;
13062 }
13063 }
13064
Owen Anderson24be4c12009-07-03 00:17:18 +000013065 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013066 return ReplaceInstUsesWith(EI, Elt);
13067
13068 // If the this extractelement is directly using a bitcast from a vector of
13069 // the same number of elements, see if we can find the source element from
13070 // it. In this case, we will end up needing to bitcast the scalars.
13071 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13072 if (const VectorType *VT =
13073 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13074 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000013075 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13076 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013077 return new BitCastInst(Elt, EI.getType());
13078 }
13079 }
13080
13081 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000013082 // Push extractelement into predecessor operation if legal and
13083 // profitable to do so
13084 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13085 if (I->hasOneUse() &&
13086 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13087 Value *newEI0 =
13088 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13089 EI.getName()+".lhs");
13090 Value *newEI1 =
13091 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13092 EI.getName()+".rhs");
13093 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013094 }
Chris Lattnera97bc602009-09-08 18:48:01 +000013095 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013096 // Extracting the inserted element?
13097 if (IE->getOperand(2) == EI.getOperand(1))
13098 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13099 // If the inserted and extracted elements are constants, they must not
13100 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000013101 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000013102 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013103 EI.setOperand(0, IE->getOperand(0));
13104 return &EI;
13105 }
13106 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13107 // If this is extracting an element from a shufflevector, figure out where
13108 // it came from and extract from the appropriate input element instead.
13109 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13110 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
13111 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013112 unsigned LHSWidth =
13113 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13114
13115 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013116 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013117 else if (SrcIdx < LHSWidth*2) {
13118 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013119 Src = SVI->getOperand(1);
13120 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000013121 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013122 }
Eric Christopher1ba36872009-07-25 02:28:41 +000013123 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000013124 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13125 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013126 }
13127 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000013128 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013129 }
13130 return 0;
13131}
13132
13133/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13134/// elements from either LHS or RHS, return the shuffle mask and true.
13135/// Otherwise, return false.
13136static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000013137 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013138 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013139 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13140 "Invalid CollectSingleShuffleElements");
13141 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13142
13143 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013144 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013145 return true;
13146 } else if (V == LHS) {
13147 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013148 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013149 return true;
13150 } else if (V == RHS) {
13151 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013152 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013153 return true;
13154 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13155 // If this is an insert of an extract from some other vector, include it.
13156 Value *VecOp = IEI->getOperand(0);
13157 Value *ScalarOp = IEI->getOperand(1);
13158 Value *IdxOp = IEI->getOperand(2);
13159
13160 if (!isa<ConstantInt>(IdxOp))
13161 return false;
13162 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13163
13164 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13165 // Okay, we can handle this if the vector we are insertinting into is
13166 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000013167 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013168 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013169 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013170 return true;
13171 }
13172 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13173 if (isa<ConstantInt>(EI->getOperand(1)) &&
13174 EI->getOperand(0)->getType() == V->getType()) {
13175 unsigned ExtractedIdx =
13176 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13177
13178 // This must be extracting from either LHS or RHS.
13179 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13180 // Okay, we can handle this if the vector we are insertinting into is
13181 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000013182 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013183 // If so, update the mask to reflect the inserted value.
13184 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013185 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013186 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013187 } else {
13188 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013189 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013190 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013191
13192 }
13193 return true;
13194 }
13195 }
13196 }
13197 }
13198 }
13199 // TODO: Handle shufflevector here!
13200
13201 return false;
13202}
13203
13204/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13205/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13206/// that computes V and the LHS value of the shuffle.
13207static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013208 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013209 assert(isa<VectorType>(V->getType()) &&
13210 (RHS == 0 || V->getType() == RHS->getType()) &&
13211 "Invalid shuffle!");
13212 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13213
13214 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013215 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013216 return V;
13217 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013218 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013219 return V;
13220 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13221 // If this is an insert of an extract from some other vector, include it.
13222 Value *VecOp = IEI->getOperand(0);
13223 Value *ScalarOp = IEI->getOperand(1);
13224 Value *IdxOp = IEI->getOperand(2);
13225
13226 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13227 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13228 EI->getOperand(0)->getType() == V->getType()) {
13229 unsigned ExtractedIdx =
13230 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13231 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13232
13233 // Either the extracted from or inserted into vector must be RHSVec,
13234 // otherwise we'd end up with a shuffle of three inputs.
13235 if (EI->getOperand(0) == RHS || RHS == 0) {
13236 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000013237 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013238 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013239 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013240 return V;
13241 }
13242
13243 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000013244 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13245 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013246 // Everything but the extracted element is replaced with the RHS.
13247 for (unsigned i = 0; i != NumElts; ++i) {
13248 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000013249 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013250 }
13251 return V;
13252 }
13253
13254 // If this insertelement is a chain that comes from exactly these two
13255 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000013256 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13257 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013258 return EI->getOperand(0);
13259
13260 }
13261 }
13262 }
13263 // TODO: Handle shufflevector here!
13264
13265 // Otherwise, can't do anything fancy. Return an identity vector.
13266 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013267 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013268 return V;
13269}
13270
13271Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13272 Value *VecOp = IE.getOperand(0);
13273 Value *ScalarOp = IE.getOperand(1);
13274 Value *IdxOp = IE.getOperand(2);
13275
13276 // Inserting an undef or into an undefined place, remove this.
13277 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13278 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000013279
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013280 // If the inserted element was extracted from some other vector, and if the
13281 // indexes are constant, try to turn this into a shufflevector operation.
13282 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13283 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13284 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000013285 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013286 unsigned ExtractedIdx =
13287 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13288 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13289
13290 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13291 return ReplaceInstUsesWith(IE, VecOp);
13292
13293 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000013294 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013295
13296 // If we are extracting a value from a vector, then inserting it right
13297 // back into the same place, just use the input vector.
13298 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13299 return ReplaceInstUsesWith(IE, VecOp);
13300
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013301 // If this insertelement isn't used by some other insertelement, turn it
13302 // (and any insertelements it points to), into one big shuffle.
13303 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13304 std::vector<Constant*> Mask;
13305 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000013306 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000013307 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013308 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000013309 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000013310 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013311 }
13312 }
13313 }
13314
Eli Friedmanbefee262009-06-06 20:08:03 +000013315 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13316 APInt UndefElts(VWidth, 0);
13317 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13318 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13319 return &IE;
13320
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013321 return 0;
13322}
13323
13324
13325Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13326 Value *LHS = SVI.getOperand(0);
13327 Value *RHS = SVI.getOperand(1);
13328 std::vector<unsigned> Mask = getShuffleMask(&SVI);
13329
13330 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013331
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013332 // Undefined shuffle mask -> undefined value.
13333 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013334 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013335
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013336 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013337
13338 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13339 return 0;
13340
Evan Cheng63295ab2009-02-03 10:05:09 +000013341 APInt UndefElts(VWidth, 0);
13342 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13343 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000013344 LHS = SVI.getOperand(0);
13345 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013346 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000013347 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013348
13349 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13350 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13351 if (LHS == RHS || isa<UndefValue>(LHS)) {
13352 if (isa<UndefValue>(LHS) && LHS == RHS) {
13353 // shuffle(undef,undef,mask) -> undef.
13354 return ReplaceInstUsesWith(SVI, LHS);
13355 }
13356
13357 // Remap any references to RHS to use LHS.
13358 std::vector<Constant*> Elts;
13359 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13360 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000013361 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013362 else {
13363 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000013364 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013365 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013366 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013367 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013368 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000013369 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013370 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013371 }
13372 }
13373 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000013374 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000013375 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013376 LHS = SVI.getOperand(0);
13377 RHS = SVI.getOperand(1);
13378 MadeChange = true;
13379 }
13380
13381 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13382 bool isLHSID = true, isRHSID = true;
13383
13384 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13385 if (Mask[i] >= e*2) continue; // Ignore undef values.
13386 // Is this an identity shuffle of the LHS value?
13387 isLHSID &= (Mask[i] == i);
13388
13389 // Is this an identity shuffle of the RHS value?
13390 isRHSID &= (Mask[i]-e == i);
13391 }
13392
13393 // Eliminate identity shuffles.
13394 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13395 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13396
13397 // If the LHS is a shufflevector itself, see if we can combine it with this
13398 // one without producing an unusual shuffle. Here we are really conservative:
13399 // we are absolutely afraid of producing a shuffle mask not in the input
13400 // program, because the code gen may not be smart enough to turn a merged
13401 // shuffle into two specific shuffles: it may produce worse code. As such,
13402 // we only merge two shuffles if the result is one of the two input shuffle
13403 // masks. In this case, merging the shuffles just removes one instruction,
13404 // which we know is safe. This is good for things like turning:
13405 // (splat(splat)) -> splat.
13406 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13407 if (isa<UndefValue>(RHS)) {
13408 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13409
David Greeneb736b5d2009-11-16 21:52:23 +000013410 if (LHSMask.size() == Mask.size()) {
13411 std::vector<unsigned> NewMask;
13412 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sandse7f89b02009-11-20 13:19:51 +000013413 if (Mask[i] >= e)
David Greeneb736b5d2009-11-16 21:52:23 +000013414 NewMask.push_back(2*e);
13415 else
13416 NewMask.push_back(LHSMask[Mask[i]]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013417
David Greeneb736b5d2009-11-16 21:52:23 +000013418 // If the result mask is equal to the src shuffle or this
13419 // shuffle mask, do the replacement.
13420 if (NewMask == LHSMask || NewMask == Mask) {
13421 unsigned LHSInNElts =
13422 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13423 getNumElements();
13424 std::vector<Constant*> Elts;
13425 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13426 if (NewMask[i] >= LHSInNElts*2) {
13427 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13428 } else {
13429 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13430 NewMask[i]));
13431 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013432 }
David Greeneb736b5d2009-11-16 21:52:23 +000013433 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13434 LHSSVI->getOperand(1),
13435 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013436 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013437 }
13438 }
13439 }
13440
13441 return MadeChange ? &SVI : 0;
13442}
13443
13444
13445
13446
13447/// TryToSinkInstruction - Try to move the specified instruction from its
13448/// current block into the beginning of DestBlock, which can only happen if it's
13449/// safe to move the instruction past all of the instructions between it and the
13450/// end of its block.
13451static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13452 assert(I->hasOneUse() && "Invariants didn't hold!");
13453
13454 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000013455 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000013456 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013457
13458 // Do not sink alloca instructions out of the entry block.
13459 if (isa<AllocaInst>(I) && I->getParent() ==
13460 &DestBlock->getParent()->getEntryBlock())
13461 return false;
13462
13463 // We can only sink load instructions if there is nothing between the load and
13464 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000013465 if (I->mayReadFromMemory()) {
13466 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013467 Scan != E; ++Scan)
13468 if (Scan->mayWriteToMemory())
13469 return false;
13470 }
13471
Dan Gohman514277c2008-05-23 21:05:58 +000013472 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013473
Dale Johannesen24339f12009-03-03 01:09:07 +000013474 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013475 I->moveBefore(InsertPos);
13476 ++NumSunkInst;
13477 return true;
13478}
13479
13480
13481/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13482/// all reachable code to the worklist.
13483///
13484/// This has a couple of tricks to make the code faster and more powerful. In
13485/// particular, we constant fold and DCE instructions as we go, to avoid adding
13486/// them to the worklist (this significantly speeds up instcombine on code where
13487/// many instructions are dead or constant). Additionally, if we find a branch
13488/// whose condition is a known constant, we only visit the reachable successors.
13489///
Chris Lattnerc4269e52009-10-15 04:59:28 +000013490static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013491 SmallPtrSet<BasicBlock*, 64> &Visited,
13492 InstCombiner &IC,
13493 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000013494 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000013495 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013496 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000013497
13498 std::vector<Instruction*> InstrsForInstCombineWorklist;
13499 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013500
Chris Lattnerc4269e52009-10-15 04:59:28 +000013501 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13502
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013503 while (!Worklist.empty()) {
13504 BB = Worklist.back();
13505 Worklist.pop_back();
13506
13507 // We have now visited this block! If we've already been here, ignore it.
13508 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000013509
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013510 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13511 Instruction *Inst = BBI++;
13512
13513 // DCE instruction if trivially dead.
13514 if (isInstructionTriviallyDead(Inst)) {
13515 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000013516 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013517 Inst->eraseFromParent();
13518 continue;
13519 }
13520
13521 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000013522 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013523 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013524 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13525 << *Inst << '\n');
13526 Inst->replaceAllUsesWith(C);
13527 ++NumConstProp;
13528 Inst->eraseFromParent();
13529 continue;
13530 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000013531
13532
13533
13534 if (TD) {
13535 // See if we can constant fold its operands.
13536 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13537 i != e; ++i) {
13538 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13539 if (CE == 0) continue;
13540
13541 // If we already folded this constant, don't try again.
13542 if (!FoldedConstants.insert(CE))
13543 continue;
13544
Chris Lattner6070c012009-11-06 04:27:31 +000013545 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +000013546 if (NewC && NewC != CE) {
13547 *i = NewC;
13548 MadeIRChange = true;
13549 }
13550 }
13551 }
13552
Devang Patel794140c2008-11-19 18:56:50 +000013553
Chris Lattnerb5663c72009-10-12 03:58:40 +000013554 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013555 }
13556
13557 // Recursively visit successors. If this is a branch or switch on a
13558 // constant, only visit the reachable successor.
13559 TerminatorInst *TI = BB->getTerminator();
13560 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13561 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13562 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013563 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013564 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013565 continue;
13566 }
13567 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13568 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13569 // See if this is an explicit destination.
13570 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13571 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013572 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013573 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013574 continue;
13575 }
13576
13577 // Otherwise it is the default destination.
13578 Worklist.push_back(SI->getSuccessor(0));
13579 continue;
13580 }
13581 }
13582
13583 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13584 Worklist.push_back(TI->getSuccessor(i));
13585 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000013586
13587 // Once we've found all of the instructions to add to instcombine's worklist,
13588 // add them in reverse order. This way instcombine will visit from the top
13589 // of the function down. This jives well with the way that it adds all uses
13590 // of instructions to the worklist after doing a transformation, thus avoiding
13591 // some N^2 behavior in pathological cases.
13592 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13593 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000013594
13595 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013596}
13597
13598bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000013599 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013600
Daniel Dunbar005975c2009-07-25 00:23:56 +000013601 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13602 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013603
13604 {
13605 // Do a depth-first traversal of the function, populate the worklist with
13606 // the reachable instructions. Ignore blocks that are not reachable. Keep
13607 // track of which blocks we visit.
13608 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000013609 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013610
13611 // Do a quick scan over the function. If we find any blocks that are
13612 // unreachable, remove any instructions inside of them. This prevents
13613 // the instcombine code from having to deal with some bad special cases.
13614 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13615 if (!Visited.count(BB)) {
13616 Instruction *Term = BB->getTerminator();
13617 while (Term != BB->begin()) { // Remove instrs bottom-up
13618 BasicBlock::iterator I = Term; --I;
13619
Chris Lattner8a6411c2009-08-23 04:37:46 +000013620 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013621 // A debug intrinsic shouldn't force another iteration if we weren't
13622 // going to do one without it.
13623 if (!isa<DbgInfoIntrinsic>(I)) {
13624 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013625 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000013626 }
Devang Patele3829c82009-10-13 22:56:32 +000013627
Devang Patele3829c82009-10-13 22:56:32 +000013628 // If I is not void type then replaceAllUsesWith undef.
13629 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000013630 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000013631 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013632 I->eraseFromParent();
13633 }
13634 }
13635 }
13636
Chris Lattner5119c702009-08-30 05:55:36 +000013637 while (!Worklist.isEmpty()) {
13638 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013639 if (I == 0) continue; // skip null values.
13640
13641 // Check to see if we can DCE the instruction.
13642 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013643 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000013644 EraseInstFromFunction(*I);
13645 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013646 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013647 continue;
13648 }
13649
13650 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000013651 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013652 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013653 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013654
Chris Lattneree5839b2009-10-15 04:13:44 +000013655 // Add operands to the worklist.
13656 ReplaceInstUsesWith(*I, C);
13657 ++NumConstProp;
13658 EraseInstFromFunction(*I);
13659 MadeIRChange = true;
13660 continue;
13661 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013662
13663 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013664 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013665 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000013666 Instruction *UserInst = cast<Instruction>(I->use_back());
13667 BasicBlock *UserParent;
13668
13669 // Get the block the use occurs in.
13670 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13671 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13672 else
13673 UserParent = UserInst->getParent();
13674
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013675 if (UserParent != BB) {
13676 bool UserIsSuccessor = false;
13677 // See if the user is one of our successors.
13678 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13679 if (*SI == UserParent) {
13680 UserIsSuccessor = true;
13681 break;
13682 }
13683
13684 // If the user is one of our immediate successors, and if that successor
13685 // only has us as a predecessors (we'd have to split the critical edge
13686 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000013687 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013688 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000013689 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013690 }
13691 }
13692
Chris Lattnerc7694852009-08-30 07:44:24 +000013693 // Now that we have an instruction, try combining it to simplify it.
13694 Builder->SetInsertPoint(I->getParent(), I);
13695
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013696#ifndef NDEBUG
13697 std::string OrigI;
13698#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013699 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000013700 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13701
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013702 if (Instruction *Result = visit(*I)) {
13703 ++NumCombined;
13704 // Should we replace the old instruction with a new one?
13705 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013706 DEBUG(errs() << "IC: Old = " << *I << '\n'
13707 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013708
13709 // Everything uses the new instruction now.
13710 I->replaceAllUsesWith(Result);
13711
13712 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000013713 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000013714 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013715
13716 // Move the name to the new instruction first.
13717 Result->takeName(I);
13718
13719 // Insert the new instruction into the basic block...
13720 BasicBlock *InstParent = I->getParent();
13721 BasicBlock::iterator InsertPos = I;
13722
13723 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13724 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13725 ++InsertPos;
13726
13727 InstParent->getInstList().insert(InsertPos, Result);
13728
Chris Lattner3183fb62009-08-30 06:13:40 +000013729 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013730 } else {
13731#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013732 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13733 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013734#endif
13735
13736 // If the instruction was modified, it's possible that it is now dead.
13737 // if so, remove it.
13738 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000013739 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013740 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000013741 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000013742 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013743 }
13744 }
Chris Lattner21d79e22009-08-31 06:57:37 +000013745 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013746 }
13747 }
13748
Chris Lattner5119c702009-08-30 05:55:36 +000013749 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000013750 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013751}
13752
13753
13754bool InstCombiner::runOnFunction(Function &F) {
13755 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013756 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000013757 TD = getAnalysisIfAvailable<TargetData>();
13758
Chris Lattnerc7694852009-08-30 07:44:24 +000013759
13760 /// Builder - This is an IRBuilder that automatically inserts new
13761 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000013762 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000013763 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000013764 InstCombineIRInserter(Worklist));
13765 Builder = &TheBuilder;
13766
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013767 bool EverMadeChange = false;
13768
13769 // Iterate while there is work to do.
13770 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013771 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013772 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000013773
13774 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013775 return EverMadeChange;
13776}
13777
13778FunctionPass *llvm::createInstructionCombiningPass() {
13779 return new InstCombiner();
13780}