blob: 0285fb53773a09773448de2e3296c919bddda94b [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez48c3c542009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
55#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057#include "llvm/Support/MathExtras.h"
58#include "llvm/Support/PatternMatch.h"
Chris Lattneree5839b2009-10-15 04:13:44 +000059#include "llvm/Support/TargetFolder.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061#include "llvm/ADT/DenseMap.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/Statistic.h"
65#include "llvm/ADT/STLExtras.h"
66#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000067#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068using namespace llvm;
69using namespace llvm::PatternMatch;
70
71STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75STATISTIC(NumSunkInst , "Number of instructions sunk");
76
77namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000078 /// InstCombineWorklist - This is the worklist management logic for
79 /// InstCombine.
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
83
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 public:
87 InstCombineWorklist() {}
88
89 bool isEmpty() const { return Worklist.empty(); }
90
91 /// Add - Add the specified instruction to the worklist if it isn't already
92 /// in it.
93 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +000096 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000097 }
Chris Lattner5119c702009-08-30 05:55:36 +000098 }
99
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
102 Add(I);
103 }
104
Chris Lattnerb5663c72009-10-12 03:58:40 +0000105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
116 }
117 }
118
Chris Lattner3183fb62009-08-30 06:13:40 +0000119 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
123
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
126
127 WorklistMap.erase(It);
128 }
129
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
132 Worklist.pop_back();
133 WorklistMap.erase(I);
134 return I;
135 }
136
Chris Lattner4796b622009-08-30 06:22:51 +0000137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
139 /// now.
140 ///
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 UI != UE; ++UI)
144 Add(cast<Instruction>(*UI));
145 }
146
Chris Lattner5119c702009-08-30 05:55:36 +0000147
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
150 void Zap() {
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152
153 // Do an explicit clear, this shrinks the map if needed.
154 WorklistMap.clear();
155 }
156 };
157} // end anonymous namespace.
158
159
160namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
166 public:
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172 Worklist.Add(I);
173 }
174 };
175} // end anonymous namespace
176
177
178namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 TargetData *TD;
182 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000183 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000185 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000186 InstCombineWorklist Worklist;
187
Chris Lattnerc7694852009-08-30 07:44:24 +0000188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +0000190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000191 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000192
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195
Owen Anderson175b6542009-07-22 00:24:57 +0000196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000198
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 public:
200 virtual bool runOnFunction(Function &F);
201
202 bool DoOneIteration(Function &F, unsigned ItNum);
203
204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 AU.addPreservedID(LCSSAID);
206 AU.setPreservesCFG();
207 }
208
Dan Gohmana80e2712009-07-21 23:21:54 +0000209 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210
211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
213 // Return Value:
214 // null - No change was made
215 // I - Change was made, I is still valid, I may be dead though
216 // otherwise - Change was made, replace I with returned instruction
217 //
218 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000219 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000221 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000223 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 Instruction *visitURem(BinaryOperator &I);
225 Instruction *visitSRem(BinaryOperator &I);
226 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000227 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 Instruction *commonRemTransforms(BinaryOperator &I);
229 Instruction *commonIRemTransforms(BinaryOperator &I);
230 Instruction *commonDivTransforms(BinaryOperator &I);
231 Instruction *commonIDivTransforms(BinaryOperator &I);
232 Instruction *visitUDiv(BinaryOperator &I);
233 Instruction *visitSDiv(BinaryOperator &I);
234 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000235 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000236 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000238 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000239 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000240 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000241 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 Instruction *visitOr (BinaryOperator &I);
243 Instruction *visitXor(BinaryOperator &I);
244 Instruction *visitShl(BinaryOperator &I);
245 Instruction *visitAShr(BinaryOperator &I);
246 Instruction *visitLShr(BinaryOperator &I);
247 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000248 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 Instruction *visitFCmpInst(FCmpInst &I);
251 Instruction *visitICmpInst(ICmpInst &I);
252 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
253 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254 Instruction *LHS,
255 ConstantInt *RHS);
256 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257 ConstantInt *DivRHS);
258
Dan Gohman17f46f72009-07-28 01:40:03 +0000259 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 ICmpInst::Predicate Cond, Instruction &I);
261 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
262 BinaryOperator &I);
263 Instruction *commonCastTransforms(CastInst &CI);
264 Instruction *commonIntCastTransforms(CastInst &CI);
265 Instruction *commonPointerCastTransforms(CastInst &CI);
266 Instruction *visitTrunc(TruncInst &CI);
267 Instruction *visitZExt(ZExtInst &CI);
268 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000269 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000271 Instruction *visitFPToUI(FPToUIInst &FI);
272 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 Instruction *visitUIToFP(CastInst &CI);
274 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000275 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000276 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 Instruction *visitBitCast(BitCastInst &CI);
278 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000280 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000281 Instruction *visitSelectInst(SelectInst &SI);
282 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 Instruction *visitCallInst(CallInst &CI);
284 Instruction *visitInvokeInst(InvokeInst &II);
285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandezb1687302009-10-23 21:09:37 +0000287 Instruction *visitAllocaInst(AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 Instruction *visitFreeInst(FreeInst &FI);
Victor Hernandez93946082009-10-24 04:23:03 +0000289 Instruction *visitFree(Instruction &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 Instruction *visitLoadInst(LoadInst &LI);
291 Instruction *visitStoreInst(StoreInst &SI);
292 Instruction *visitBranchInst(BranchInst &BI);
293 Instruction *visitSwitchInst(SwitchInst &SI);
294 Instruction *visitInsertElementInst(InsertElementInst &IE);
295 Instruction *visitExtractElementInst(ExtractElementInst &EI);
296 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000297 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298
299 // visitInstruction - Specify what to return for unhandled instructions...
300 Instruction *visitInstruction(Instruction &I) { return 0; }
301
302 private:
303 Instruction *visitCallSite(CallSite CS);
304 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000305 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000306 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000308 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000309 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
310
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311
312 public:
313 // InsertNewInstBefore - insert an instruction New before instruction Old
314 // in the program. Add the new instruction to the worklist.
315 //
316 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
317 assert(New && New->getParent() == 0 &&
318 "New instruction already inserted into a basic block!");
319 BasicBlock *BB = Old.getParent();
320 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000321 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 return New;
323 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000324
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 // ReplaceInstUsesWith - This method is to be used when an instruction is
326 // found to be dead, replacable with another preexisting expression. Here
327 // we add all uses of I to the worklist, replace all uses of I with the new
328 // value, then return I, so that the inst combiner will know that I was
329 // modified.
330 //
331 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000332 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000333
334 // If we are replacing the instruction with itself, this must be in a
335 // segment of unreachable code, so just clobber the instruction.
336 if (&I == V)
337 V = UndefValue::get(I.getType());
338
339 I.replaceAllUsesWith(V);
340 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 }
342
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 // EraseInstFromFunction - When dealing with an instruction that has side
344 // effects or produces a void value, we can't rely on DCE to delete the
345 // instruction. Instead, visit methods should return the value returned by
346 // this function.
347 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000348 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000349
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000351 // Make sure that we reprocess all operands now that we reduced their
352 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000353 if (I.getNumOperands() < 8) {
354 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355 if (Instruction *Op = dyn_cast<Instruction>(*i))
356 Worklist.Add(Op);
357 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000358 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000360 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 return 0; // Don't do anything with FI
362 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000363
364 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
365 APInt &KnownOne, unsigned Depth = 0) const {
366 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
367 }
368
369 bool MaskedValueIsZero(Value *V, const APInt &Mask,
370 unsigned Depth = 0) const {
371 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
372 }
373 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
374 return llvm::ComputeNumSignBits(Op, TD, Depth);
375 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376
377 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378
379 /// SimplifyCommutative - This performs a few simplifications for
380 /// commutative operators.
381 bool SimplifyCommutative(BinaryOperator &I);
382
383 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
384 /// most-complex to least-complex order.
385 bool SimplifyCompare(CmpInst &I);
386
Chris Lattner676c78e2009-01-31 08:15:18 +0000387 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388 /// based on the demanded bits.
389 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
390 APInt& KnownZero, APInt& KnownOne,
391 unsigned Depth);
392 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000394 unsigned Depth=0);
395
396 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397 /// SimplifyDemandedBits knows about. See if the instruction has any
398 /// properties that allow us to simplify its operands.
399 bool SimplifyDemandedInstructionBits(Instruction &Inst);
400
Evan Cheng63295ab2009-02-03 10:05:09 +0000401 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403
Chris Lattnerf7843b72009-09-27 19:57:57 +0000404 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405 // which has a PHI node as operand #0, see if we can fold the instruction
406 // into the PHI (which is only possible if all operands to the PHI are
407 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000408 //
409 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410 // that would normally be unprofitable because they strongly encourage jump
411 // threading.
412 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413
414 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415 // operator and they all are only used by the PHI, PHI together their
416 // inputs, and do the operation once, to the result of the PHI.
417 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
418 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000419 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
420
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421
422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
424
425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426 bool isSub, Instruction &I);
427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandezb1687302009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000434
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435
436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000437
Dan Gohman8fd520a2009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000442
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 };
Chris Lattner5119c702009-08-30 05:55:36 +0000444} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445
Dan Gohman089efff2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 return 3;
458 return 4;
459 }
460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
462}
463
464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
467 return V->hasOneUse() || isa<Constant>(V);
468}
469
470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 }
477 return Ty;
478}
479
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000480/// getBitCastOperand - If the specified operand is a CastInst, a constant
481/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000484 if (Operator *O = dyn_cast<Operator>(V)) {
485 if (O->getOpcode() == Instruction::BitCast)
486 return O->getOperand(0);
487 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488 if (GEP->hasAllZeroIndices())
489 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000490 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 return 0;
492}
493
494/// This function is a wrapper around CastInst::isEliminableCastPair. It
495/// simply extracts arguments and returns what that function returns.
496static Instruction::CastOps
497isEliminableCastPair(
498 const CastInst *CI, ///< The first cast instruction
499 unsigned opcode, ///< The opcode of the second cast instruction
500 const Type *DstTy, ///< The target type for the second cast instruction
501 TargetData *TD ///< The target data for pointer size
502) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000503
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
505 const Type *MidTy = CI->getType(); // B from above
506
507 // Get the opcodes of the two Cast instructions
508 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
510
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000511 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000512 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000513 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000514
515 // We don't want to form an inttoptr or ptrtoint that converts to an integer
516 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000517 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000518 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000519 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000520 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000521 Res = 0;
522
523 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524}
525
526/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527/// in any code being generated. It does not require codegen if V is simple
528/// enough or if the cast can be folded into other casts.
529static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
530 const Type *Ty, TargetData *TD) {
531 if (V->getType() == Ty || isa<Constant>(V)) return false;
532
533 // If this is another cast that can be eliminated, it isn't codegen either.
534 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000535 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 return false;
537 return true;
538}
539
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540// SimplifyCommutative - This performs a few simplifications for commutative
541// operators:
542//
543// 1. Order operands such that they are listed from right (least complex) to
544// left (most complex). This puts constants before unary operators before
545// binary operators.
546//
547// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
549//
550bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
551 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000552 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553 Changed = !I.swapOperands();
554
555 if (!I.isAssociative()) return Changed;
556 Instruction::BinaryOps Opcode = I.getOpcode();
557 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000560 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 cast<Constant>(I.getOperand(1)),
562 cast<Constant>(Op->getOperand(1)));
563 I.setOperand(0, Op->getOperand(0));
564 I.setOperand(1, Folded);
565 return true;
566 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568 isOnlyUse(Op) && isOnlyUse(Op1)) {
569 Constant *C1 = cast<Constant>(Op->getOperand(1));
570 Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000573 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000574 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 Op1->getOperand(0),
576 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000577 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 I.setOperand(0, New);
579 I.setOperand(1, Folded);
580 return true;
581 }
582 }
583 return Changed;
584}
585
586/// SimplifyCompare - For a CmpInst this function just orders the operands
587/// so that theyare listed from right (least complex) to left (most complex).
588/// This puts constants before unary operators before binary operators.
589bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman5d138f92009-08-29 23:39:38 +0000590 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 return false;
592 I.swapOperands();
593 // Compare instructions are not associative so there's nothing else we can do.
594 return true;
595}
596
597// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
598// if the LHS is a constant zero (which is the 'negate' form).
599//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000600static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000601 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 return BinaryOperator::getNegArgument(V);
603
604 // Constants can be considered to be negated values if they can be folded.
605 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000606 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000607
608 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
609 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000610 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000611
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 return 0;
613}
614
Dan Gohman7ce405e2009-06-04 22:49:04 +0000615// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
616// instruction if the LHS is a constant negative zero (which is the 'negate'
617// form).
618//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000619static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000620 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000621 return BinaryOperator::getFNegArgument(V);
622
623 // Constants can be considered to be negated values if they can be folded.
624 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000625 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000626
627 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
628 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000629 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000630
631 return 0;
632}
633
Chris Lattnerf05d95c2009-10-26 01:06:31 +0000634/// isFreeToInvert - Return true if the specified value is free to invert (apply
635/// ~ to). This happens in cases where the ~ can be eliminated.
636static inline bool isFreeToInvert(Value *V) {
637 // ~(~(X)) -> X.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 if (BinaryOperator::isNot(V))
Chris Lattnerf05d95c2009-10-26 01:06:31 +0000639 return true;
640
641 // Constants can be considered to be not'ed values.
642 if (isa<ConstantInt>(V))
643 return true;
644
645 // Compares can be inverted if they have a single use.
646 if (CmpInst *CI = dyn_cast<CmpInst>(V))
647 return CI->hasOneUse();
648
649 return false;
650}
651
652static inline Value *dyn_castNotVal(Value *V) {
653 // If this is not(not(x)) don't return that this is a not: we want the two
654 // not's to be folded first.
655 if (BinaryOperator::isNot(V)) {
656 Value *Operand = BinaryOperator::getNotArgument(V);
657 if (!isFreeToInvert(Operand))
658 return Operand;
659 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660
661 // Constants can be considered to be not'ed values...
662 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000663 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 return 0;
665}
666
Chris Lattnerf05d95c2009-10-26 01:06:31 +0000667
668
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669// dyn_castFoldableMul - If this value is a multiply that can be folded into
670// other computations (because it has a constant operand), return the
671// non-constant operand of the multiply, and set CST to point to the multiplier.
672// Otherwise, return null.
673//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000674static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 if (V->hasOneUse() && V->getType()->isInteger())
676 if (Instruction *I = dyn_cast<Instruction>(V)) {
677 if (I->getOpcode() == Instruction::Mul)
678 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
679 return I->getOperand(0);
680 if (I->getOpcode() == Instruction::Shl)
681 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
682 // The multiplier is really 1 << CST.
683 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
684 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000685 CST = ConstantInt::get(V->getType()->getContext(),
686 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 return I->getOperand(0);
688 }
689 }
690 return 0;
691}
692
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000694static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000695 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000696 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697}
698/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000699static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000700 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000701 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000703/// MultiplyOverflows - True if the multiply can not be expressed in an int
704/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000705static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000706 uint32_t W = C1->getBitWidth();
707 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
708 if (sign) {
709 LHSExt.sext(W * 2);
710 RHSExt.sext(W * 2);
711 } else {
712 LHSExt.zext(W * 2);
713 RHSExt.zext(W * 2);
714 }
715
716 APInt MulExt = LHSExt * RHSExt;
717
718 if (sign) {
719 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
720 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
721 return MulExt.slt(Min) || MulExt.sgt(Max);
722 } else
723 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
724}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726
727/// ShrinkDemandedConstant - Check to see if the specified operand of the
728/// specified instruction is a constant integer. If so, check to see if there
729/// are any bits set in the constant that are not demanded. If so, shrink the
730/// constant and return true.
731static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000732 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 assert(I && "No instruction?");
734 assert(OpNo < I->getNumOperands() && "Operand index too large");
735
736 // If the operand is not a constant integer, nothing to do.
737 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
738 if (!OpC) return false;
739
740 // If there are no bits set that aren't demanded, nothing to do.
741 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
742 if ((~Demanded & OpC->getValue()) == 0)
743 return false;
744
745 // This instruction is producing bits that are not demanded. Shrink the RHS.
746 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000747 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748 return true;
749}
750
751// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
752// set of known zero and one bits, compute the maximum and minimum values that
753// could have the specified known zero and known one bits, returning them in
754// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000755static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 const APInt& KnownOne,
757 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000758 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
759 KnownZero.getBitWidth() == Min.getBitWidth() &&
760 KnownZero.getBitWidth() == Max.getBitWidth() &&
761 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 APInt UnknownBits = ~(KnownZero|KnownOne);
763
764 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
765 // bit if it is unknown.
766 Min = KnownOne;
767 Max = KnownOne|UnknownBits;
768
Dan Gohman7934d592009-04-25 17:12:48 +0000769 if (UnknownBits.isNegative()) { // Sign bit is unknown
770 Min.set(Min.getBitWidth()-1);
771 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 }
773}
774
775// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
776// a set of known zero and one bits, compute the maximum and minimum values that
777// could have the specified known zero and known one bits, returning them in
778// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000779static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000780 const APInt &KnownOne,
781 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000782 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
783 KnownZero.getBitWidth() == Min.getBitWidth() &&
784 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
786 APInt UnknownBits = ~(KnownZero|KnownOne);
787
788 // The minimum value is when the unknown bits are all zeros.
789 Min = KnownOne;
790 // The maximum value is when the unknown bits are all ones.
791 Max = KnownOne|UnknownBits;
792}
793
Chris Lattner676c78e2009-01-31 08:15:18 +0000794/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
795/// SimplifyDemandedBits knows about. See if the instruction has any
796/// properties that allow us to simplify its operands.
797bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000798 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000799 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
800 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
801
802 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
803 KnownZero, KnownOne, 0);
804 if (V == 0) return false;
805 if (V == &Inst) return true;
806 ReplaceInstUsesWith(Inst, V);
807 return true;
808}
809
810/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
811/// specified instruction operand if possible, updating it in place. It returns
812/// true if it made any change and false otherwise.
813bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
814 APInt &KnownZero, APInt &KnownOne,
815 unsigned Depth) {
816 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
817 KnownZero, KnownOne, Depth);
818 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000819 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000820 return true;
821}
822
823
824/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
825/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826/// that only the bits set in DemandedMask of the result of V are ever used
827/// downstream. Consequently, depending on the mask and V, it may be possible
828/// to replace V with a constant or one of its operands. In such cases, this
829/// function does the replacement and returns true. In all other cases, it
830/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000831/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832/// to be zero in the expression. These are provided to potentially allow the
833/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
834/// the expression. KnownOne and KnownZero always follow the invariant that
835/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
836/// the bits in KnownOne and KnownZero may only be accurate for those bits set
837/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
838/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000839///
840/// This returns null if it did not change anything and it permits no
841/// simplification. This returns V itself if it did some simplification of V's
842/// operands based on the information about what bits are demanded. This returns
843/// some other non-null value if it found out that V is equal to another value
844/// in the context where the specified bits are demanded, but not for all users.
845Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
846 APInt &KnownZero, APInt &KnownOne,
847 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 assert(V != 0 && "Null pointer of Value???");
849 assert(Depth <= 6 && "Limit Search Depth");
850 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000851 const Type *VTy = V->getType();
852 assert((TD || !isa<PointerType>(VTy)) &&
853 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000854 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
855 (!VTy->isIntOrIntVector() ||
856 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000857 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000859 "Value *V, DemandedMask, KnownZero and KnownOne "
860 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
862 // We know all of the bits for a constant!
863 KnownOne = CI->getValue() & DemandedMask;
864 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000865 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 }
Dan Gohman7934d592009-04-25 17:12:48 +0000867 if (isa<ConstantPointerNull>(V)) {
868 // We know all of the bits for a constant!
869 KnownOne.clear();
870 KnownZero = DemandedMask;
871 return 0;
872 }
873
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000874 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000876 if (DemandedMask == 0) { // Not demanding any bits from V.
877 if (isa<UndefValue>(V))
878 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000879 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 }
881
Chris Lattner08817332009-01-31 08:24:16 +0000882 if (Depth == 6) // Limit search depth.
883 return 0;
884
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000885 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
886 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
887
Dan Gohman7934d592009-04-25 17:12:48 +0000888 Instruction *I = dyn_cast<Instruction>(V);
889 if (!I) {
890 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
891 return 0; // Only analyze instructions.
892 }
893
Chris Lattner08817332009-01-31 08:24:16 +0000894 // If there are multiple uses of this value and we aren't at the root, then
895 // we can't do any simplifications of the operands, because DemandedMask
896 // only reflects the bits demanded by *one* of the users.
897 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000898 // Despite the fact that we can't simplify this instruction in all User's
899 // context, we can at least compute the knownzero/knownone bits, and we can
900 // do simplifications that apply to *just* the one user if we know that
901 // this instruction has a simpler value in that context.
902 if (I->getOpcode() == Instruction::And) {
903 // If either the LHS or the RHS are Zero, the result is zero.
904 ComputeMaskedBits(I->getOperand(1), DemandedMask,
905 RHSKnownZero, RHSKnownOne, Depth+1);
906 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
907 LHSKnownZero, LHSKnownOne, Depth+1);
908
909 // If all of the demanded bits are known 1 on one side, return the other.
910 // These bits cannot contribute to the result of the 'and' in this
911 // context.
912 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
913 (DemandedMask & ~LHSKnownZero))
914 return I->getOperand(0);
915 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
916 (DemandedMask & ~RHSKnownZero))
917 return I->getOperand(1);
918
919 // If all of the demanded bits in the inputs are known zeros, return zero.
920 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000921 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000922
923 } else if (I->getOpcode() == Instruction::Or) {
924 // We can simplify (X|Y) -> X or Y in the user's context if we know that
925 // only bits from X or Y are demanded.
926
927 // If either the LHS or the RHS are One, the result is One.
928 ComputeMaskedBits(I->getOperand(1), DemandedMask,
929 RHSKnownZero, RHSKnownOne, Depth+1);
930 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
931 LHSKnownZero, LHSKnownOne, Depth+1);
932
933 // If all of the demanded bits are known zero on one side, return the
934 // other. These bits cannot contribute to the result of the 'or' in this
935 // context.
936 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
937 (DemandedMask & ~LHSKnownOne))
938 return I->getOperand(0);
939 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
940 (DemandedMask & ~RHSKnownOne))
941 return I->getOperand(1);
942
943 // If all of the potentially set bits on one side are known to be set on
944 // the other side, just use the 'other' side.
945 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
946 (DemandedMask & (~RHSKnownZero)))
947 return I->getOperand(0);
948 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
949 (DemandedMask & (~LHSKnownZero)))
950 return I->getOperand(1);
951 }
952
Chris Lattner08817332009-01-31 08:24:16 +0000953 // Compute the KnownZero/KnownOne bits to simplify things downstream.
954 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
955 return 0;
956 }
957
958 // If this is the root being simplified, allow it to have multiple uses,
959 // just set the DemandedMask to all bits so that we can try to simplify the
960 // operands. This allows visitTruncInst (for example) to simplify the
961 // operand of a trunc without duplicating all the logic below.
962 if (Depth == 0 && !V->hasOneUse())
963 DemandedMask = APInt::getAllOnesValue(BitWidth);
964
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000966 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000967 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000968 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 case Instruction::And:
970 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000971 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972 RHSKnownZero, RHSKnownOne, Depth+1) ||
973 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000975 return I;
976 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
977 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978
979 // If all of the demanded bits are known 1 on one side, return the other.
980 // These bits cannot contribute to the result of the 'and'.
981 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
982 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000983 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
985 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000986 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987
988 // If all of the demanded bits in the inputs are known zeros, return zero.
989 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000990 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991
992 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000993 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000994 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995
996 // Output known-1 bits are only known if set in both the LHS & RHS.
997 RHSKnownOne &= LHSKnownOne;
998 // Output known-0 are known to be clear if zero in either the LHS | RHS.
999 RHSKnownZero |= LHSKnownZero;
1000 break;
1001 case Instruction::Or:
1002 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +00001003 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1004 RHSKnownZero, RHSKnownOne, Depth+1) ||
1005 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001007 return I;
1008 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1009 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'or'.
1013 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1014 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001015 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1017 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001018 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019
1020 // If all of the potentially set bits on one side are known to be set on
1021 // the other side, just use the 'other' side.
1022 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1023 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001024 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1026 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001027 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001031 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032
1033 // Output known-0 bits are only known if clear in both the LHS & RHS.
1034 RHSKnownZero &= LHSKnownZero;
1035 // Output known-1 are known to be set if set in either the LHS | RHS.
1036 RHSKnownOne |= LHSKnownOne;
1037 break;
1038 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001039 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1040 RHSKnownZero, RHSKnownOne, Depth+1) ||
1041 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001043 return I;
1044 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1045 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047 // If all of the demanded bits are known zero on one side, return the other.
1048 // These bits cannot contribute to the result of the 'xor'.
1049 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001050 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001052 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
1054 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1055 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1056 (RHSKnownOne & LHSKnownOne);
1057 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1058 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1059 (RHSKnownOne & LHSKnownZero);
1060
1061 // If all of the demanded bits are known to be zero on one side or the
1062 // other, turn this into an *inclusive* or.
1063 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001064 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1065 Instruction *Or =
1066 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1067 I->getName());
1068 return InsertNewInstBefore(Or, *I);
1069 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070
1071 // If all of the demanded bits on one side are known, and all of the set
1072 // bits on that side are also known to be set on the other side, turn this
1073 // into an AND, as we know the bits will be cleared.
1074 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1075 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1076 // all known
1077 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001078 Constant *AndC = Constant::getIntegerValue(VTy,
1079 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001081 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001082 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 }
1084 }
1085
1086 // If the RHS is a constant, see if we can simplify it.
1087 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001088 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001089 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
Chris Lattnereefa89c2009-10-11 22:22:13 +00001091 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1092 // are flipping are known to be set, then the xor is just resetting those
1093 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1094 // simplifying both of them.
1095 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1096 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1097 isa<ConstantInt>(I->getOperand(1)) &&
1098 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1099 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1100 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1101 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1102 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1103
1104 Constant *AndC =
1105 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1106 Instruction *NewAnd =
1107 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1108 InsertNewInstBefore(NewAnd, *I);
1109
1110 Constant *XorC =
1111 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1112 Instruction *NewXor =
1113 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1114 return InsertNewInstBefore(NewXor, *I);
1115 }
1116
1117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 RHSKnownZero = KnownZeroOut;
1119 RHSKnownOne = KnownOneOut;
1120 break;
1121 }
1122 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001123 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1) ||
1125 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001127 return I;
1128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1129 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130
1131 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001132 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1133 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001134 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135
1136 // Only known if known in both the LHS and RHS.
1137 RHSKnownOne &= LHSKnownOne;
1138 RHSKnownZero &= LHSKnownZero;
1139 break;
1140 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001141 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 DemandedMask.zext(truncBf);
1143 RHSKnownZero.zext(truncBf);
1144 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001145 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001147 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 DemandedMask.trunc(BitWidth);
1149 RHSKnownZero.trunc(BitWidth);
1150 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001151 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 break;
1153 }
1154 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001155 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001156 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001157
1158 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1159 if (const VectorType *SrcVTy =
1160 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1161 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1162 // Don't touch a bitcast between vectors of different element counts.
1163 return false;
1164 } else
1165 // Don't touch a scalar-to-vector bitcast.
1166 return false;
1167 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1168 // Don't touch a vector-to-scalar bitcast.
1169 return false;
1170
Chris Lattner676c78e2009-01-31 08:15:18 +00001171 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001173 return I;
1174 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 break;
1176 case Instruction::ZExt: {
1177 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001178 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179
1180 DemandedMask.trunc(SrcBitWidth);
1181 RHSKnownZero.trunc(SrcBitWidth);
1182 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001183 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001185 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 DemandedMask.zext(BitWidth);
1187 RHSKnownZero.zext(BitWidth);
1188 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001189 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 // The top bits are known to be zero.
1191 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1192 break;
1193 }
1194 case Instruction::SExt: {
1195 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001196 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197
1198 APInt InputDemandedBits = DemandedMask &
1199 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1200
1201 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1202 // If any of the sign extended bits are demanded, we know that the sign
1203 // bit is demanded.
1204 if ((NewBits & DemandedMask) != 0)
1205 InputDemandedBits.set(SrcBitWidth-1);
1206
1207 InputDemandedBits.trunc(SrcBitWidth);
1208 RHSKnownZero.trunc(SrcBitWidth);
1209 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001210 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001212 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 InputDemandedBits.zext(BitWidth);
1214 RHSKnownZero.zext(BitWidth);
1215 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001216 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217
1218 // If the sign bit of the input is known set or clear, then we know the
1219 // top bits of the result.
1220
1221 // If the input sign bit is known zero, or if the NewBits are not demanded
1222 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001223 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001225 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1226 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1228 RHSKnownOne |= NewBits;
1229 }
1230 break;
1231 }
1232 case Instruction::Add: {
1233 // Figure out what the input bits are. If the top bits of the and result
1234 // are not demanded, then the add doesn't demand them from its input
1235 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001236 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237
1238 // If there is a constant on the RHS, there are a variety of xformations
1239 // we can do.
1240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241 // If null, this should be simplified elsewhere. Some of the xforms here
1242 // won't work if the RHS is zero.
1243 if (RHS->isZero())
1244 break;
1245
1246 // If the top bit of the output is demanded, demand everything from the
1247 // input. Otherwise, we demand all the input bits except NLZ top bits.
1248 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1249
1250 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001253 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254
1255 // If the RHS of the add has bits set that can't affect the input, reduce
1256 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001257 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001258 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259
1260 // Avoid excess work.
1261 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1262 break;
1263
1264 // Turn it into OR if input bits are zero.
1265 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1266 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001267 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001269 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 }
1271
1272 // We can say something about the output known-zero and known-one bits,
1273 // depending on potential carries from the input constant and the
1274 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1275 // bits set and the RHS constant is 0x01001, then we know we have a known
1276 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1277
1278 // To compute this, we first compute the potential carry bits. These are
1279 // the bits which may be modified. I'm not aware of a better way to do
1280 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001281 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1283
1284 // Now that we know which bits have carries, compute the known-1/0 sets.
1285
1286 // Bits are known one if they are known zero in one operand and one in the
1287 // other, and there is no input carry.
1288 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1289 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1290
1291 // Bits are known zero if they are known zero in both operands and there
1292 // is no input carry.
1293 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1294 } else {
1295 // If the high-bits of this ADD are not demanded, then it does not demand
1296 // the high bits of its LHS or RHS.
1297 if (DemandedMask[BitWidth-1] == 0) {
1298 // Right fill the mask of bits for this ADD to demand the most
1299 // significant bit and all those below it.
1300 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001301 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1302 LHSKnownZero, LHSKnownOne, Depth+1) ||
1303 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001305 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 }
1307 }
1308 break;
1309 }
1310 case Instruction::Sub:
1311 // If the high-bits of this SUB are not demanded, then it does not demand
1312 // the high bits of its LHS or RHS.
1313 if (DemandedMask[BitWidth-1] == 0) {
1314 // Right fill the mask of bits for this SUB to demand the most
1315 // significant bit and all those below it.
1316 uint32_t NLZ = DemandedMask.countLeadingZeros();
1317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001322 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001324 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1325 // the known zeros and ones.
1326 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 break;
1328 case Instruction::Shl:
1329 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1330 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1331 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001332 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001334 return I;
1335 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 RHSKnownZero <<= ShiftAmt;
1337 RHSKnownOne <<= ShiftAmt;
1338 // low bits known zero.
1339 if (ShiftAmt)
1340 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1341 }
1342 break;
1343 case Instruction::LShr:
1344 // For a logical shift right
1345 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1346 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1347
1348 // Unsigned shift right.
1349 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001350 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001352 return I;
1353 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1356 if (ShiftAmt) {
1357 // Compute the new bits that are at the top now.
1358 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1359 RHSKnownZero |= HighBits; // high bits known zero.
1360 }
1361 }
1362 break;
1363 case Instruction::AShr:
1364 // If this is an arithmetic shift right and only the low-bit is set, we can
1365 // always convert this into a logical shr, even if the shift amount is
1366 // variable. The low bit of the shift cannot be an input sign bit unless
1367 // the shift amount is >= the size of the datatype, which is undefined.
1368 if (DemandedMask == 1) {
1369 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001370 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001372 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 }
1374
1375 // If the sign bit is the only bit demanded by this ashr, then there is no
1376 // need to do it, the shift doesn't change the high bit.
1377 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001378 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379
1380 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1381 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1382
1383 // Signed shift right.
1384 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1385 // If any of the "high bits" are demanded, we should set the sign bit as
1386 // demanded.
1387 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1388 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001389 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001391 return I;
1392 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 // Compute the new bits that are at the top now.
1394 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1395 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1396 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1397
1398 // Handle the sign bits.
1399 APInt SignBit(APInt::getSignBit(BitWidth));
1400 // Adjust to where it is now in the mask.
1401 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1402
1403 // If the input sign bit is known to be zero, or if none of the top bits
1404 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001405 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406 (HighBits & ~DemandedMask) == HighBits) {
1407 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001408 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001409 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001410 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1412 RHSKnownOne |= HighBits;
1413 }
1414 }
1415 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001416 case Instruction::SRem:
1417 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001418 APInt RA = Rem->getValue().abs();
1419 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001420 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001421 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001422
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001423 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001424 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001425 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001426 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001427 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001428
1429 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1430 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001431
1432 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001433
Chris Lattner676c78e2009-01-31 08:15:18 +00001434 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001435 }
1436 }
1437 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001438 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001439 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1440 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001441 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1442 KnownZero2, KnownOne2, Depth+1) ||
1443 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001444 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001445 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001446
Chris Lattneree5417c2009-01-21 18:09:24 +00001447 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001448 Leaders = std::max(Leaders,
1449 KnownZero2.countLeadingOnes());
1450 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001451 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 }
Chris Lattner989ba312008-06-18 04:33:20 +00001453 case Instruction::Call:
1454 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1455 switch (II->getIntrinsicID()) {
1456 default: break;
1457 case Intrinsic::bswap: {
1458 // If the only bits demanded come from one byte of the bswap result,
1459 // just shift the input byte into position to eliminate the bswap.
1460 unsigned NLZ = DemandedMask.countLeadingZeros();
1461 unsigned NTZ = DemandedMask.countTrailingZeros();
1462
1463 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1464 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1465 // have 14 leading zeros, round to 8.
1466 NLZ &= ~7;
1467 NTZ &= ~7;
1468 // If we need exactly one byte, we can do this transformation.
1469 if (BitWidth-NLZ-NTZ == 8) {
1470 unsigned ResultBit = NTZ;
1471 unsigned InputBit = BitWidth-NTZ-8;
1472
1473 // Replace this with either a left or right shift to get the byte into
1474 // the right place.
1475 Instruction *NewVal;
1476 if (InputBit > ResultBit)
1477 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001478 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001479 else
1480 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001481 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001482 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001483 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001484 }
1485
1486 // TODO: Could compute known zero/one bits based on the input.
1487 break;
1488 }
1489 }
1490 }
Chris Lattner4946e222008-06-18 18:11:55 +00001491 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001492 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001493 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494
1495 // If the client is only demanding bits that we know, return the known
1496 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001497 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1498 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499 return false;
1500}
1501
1502
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001503/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001504/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505/// actually used by the caller. This method analyzes which elements of the
1506/// operand are undef and returns that information in UndefElts.
1507///
1508/// If the information about demanded elements can be used to simplify the
1509/// operation, the operation is simplified, then the resultant value is
1510/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001511Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1512 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 unsigned Depth) {
1514 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001515 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001516 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517
1518 if (isa<UndefValue>(V)) {
1519 // If the entire vector is undefined, just return this info.
1520 UndefElts = EltMask;
1521 return 0;
1522 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1523 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001524 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001526
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001527 UndefElts = 0;
1528 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1529 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001530 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531
1532 std::vector<Constant*> Elts;
1533 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001534 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001536 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1538 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001539 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 } else { // Otherwise, defined.
1541 Elts.push_back(CP->getOperand(i));
1542 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001543
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001545 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 return NewCP != CP ? NewCP : 0;
1547 } else if (isa<ConstantAggregateZero>(V)) {
1548 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1549 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001550
1551 // Check if this is identity. If so, return 0 since we are not simplifying
1552 // anything.
1553 if (DemandedElts == ((1ULL << VWidth) -1))
1554 return 0;
1555
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001557 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001558 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001560 for (unsigned i = 0; i != VWidth; ++i) {
1561 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1562 Elts.push_back(Elt);
1563 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001564 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001565 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566 }
1567
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001568 // Limit search depth.
1569 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001570 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001571
1572 // If multiple users are using the root value, procede with
1573 // simplification conservatively assuming that all elements
1574 // are needed.
1575 if (!V->hasOneUse()) {
1576 // Quit if we find multiple users of a non-root value though.
1577 // They'll be handled when it's their turn to be visited by
1578 // the main instcombine process.
1579 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001581 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001582
1583 // Conservatively assume that all elements are needed.
1584 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585 }
1586
1587 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001588 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589
1590 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001591 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592 Value *TmpV;
1593 switch (I->getOpcode()) {
1594 default: break;
1595
1596 case Instruction::InsertElement: {
1597 // If this is a variable index, we don't know which element it overwrites.
1598 // demand exactly the same input as we produce.
1599 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1600 if (Idx == 0) {
1601 // Note that we can't propagate undef elt info, because we don't know
1602 // which elt is getting updated.
1603 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1604 UndefElts2, Depth+1);
1605 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1606 break;
1607 }
1608
1609 // If this is inserting an element that isn't demanded, remove this
1610 // insertelement.
1611 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001612 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1613 Worklist.Add(I);
1614 return I->getOperand(0);
1615 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616
1617 // Otherwise, the element inserted overwrites whatever was there, so the
1618 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001619 APInt DemandedElts2 = DemandedElts;
1620 DemandedElts2.clear(IdxNo);
1621 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622 UndefElts, Depth+1);
1623 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1624
1625 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001626 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001627 break;
1628 }
1629 case Instruction::ShuffleVector: {
1630 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001631 uint64_t LHSVWidth =
1632 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001633 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001634 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001635 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001636 unsigned MaskVal = Shuffle->getMaskValue(i);
1637 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001638 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001639 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001640 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001641 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001642 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001643 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001644 }
1645 }
1646 }
1647
Nate Begemanb4d176f2009-02-11 22:36:25 +00001648 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001650 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001651 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1652
Nate Begemanb4d176f2009-02-11 22:36:25 +00001653 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001654 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1655 UndefElts3, Depth+1);
1656 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1657
1658 bool NewUndefElts = false;
1659 for (unsigned i = 0; i < VWidth; i++) {
1660 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001661 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001662 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001663 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001664 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001665 NewUndefElts = true;
1666 UndefElts.set(i);
1667 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001668 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001669 if (UndefElts3[MaskVal - LHSVWidth]) {
1670 NewUndefElts = true;
1671 UndefElts.set(i);
1672 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001673 }
1674 }
1675
1676 if (NewUndefElts) {
1677 // Add additional discovered undefs.
1678 std::vector<Constant*> Elts;
1679 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001680 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001681 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001682 else
Owen Anderson35b47072009-08-13 21:58:54 +00001683 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001684 Shuffle->getMaskValue(i)));
1685 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001686 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001687 MadeChange = true;
1688 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 break;
1690 }
1691 case Instruction::BitCast: {
1692 // Vector->vector casts only.
1693 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1694 if (!VTy) break;
1695 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001696 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697 unsigned Ratio;
1698
1699 if (VWidth == InVWidth) {
1700 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1701 // elements as are demanded of us.
1702 Ratio = 1;
1703 InputDemandedElts = DemandedElts;
1704 } else if (VWidth > InVWidth) {
1705 // Untested so far.
1706 break;
1707
1708 // If there are more elements in the result than there are in the source,
1709 // then an input element is live if any of the corresponding output
1710 // elements are live.
1711 Ratio = VWidth/InVWidth;
1712 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001713 if (DemandedElts[OutIdx])
1714 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001715 }
1716 } else {
1717 // Untested so far.
1718 break;
1719
1720 // If there are more elements in the source than there are in the result,
1721 // then an input element is live if the corresponding output element is
1722 // live.
1723 Ratio = InVWidth/VWidth;
1724 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001725 if (DemandedElts[InIdx/Ratio])
1726 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 }
1728
1729 // div/rem demand all inputs, because they don't want divide by zero.
1730 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1731 UndefElts2, Depth+1);
1732 if (TmpV) {
1733 I->setOperand(0, TmpV);
1734 MadeChange = true;
1735 }
1736
1737 UndefElts = UndefElts2;
1738 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001739 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740 // If there are more elements in the result than there are in the source,
1741 // then an output element is undef if the corresponding input element is
1742 // undef.
1743 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001744 if (UndefElts2[OutIdx/Ratio])
1745 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001746 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001747 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001748 // If there are more elements in the source than there are in the result,
1749 // then a result element is undef if all of the corresponding input
1750 // elements are undef.
1751 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1752 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001753 if (!UndefElts2[InIdx]) // Not undef?
1754 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755 }
1756 break;
1757 }
1758 case Instruction::And:
1759 case Instruction::Or:
1760 case Instruction::Xor:
1761 case Instruction::Add:
1762 case Instruction::Sub:
1763 case Instruction::Mul:
1764 // div/rem demand all inputs, because they don't want divide by zero.
1765 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1766 UndefElts, Depth+1);
1767 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1768 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1769 UndefElts2, Depth+1);
1770 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1771
1772 // Output elements are undefined if both are undefined. Consider things
1773 // like undef&0. The result is known zero, not undef.
1774 UndefElts &= UndefElts2;
1775 break;
1776
1777 case Instruction::Call: {
1778 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1779 if (!II) break;
1780 switch (II->getIntrinsicID()) {
1781 default: break;
1782
1783 // Binary vector operations that work column-wise. A dest element is a
1784 // function of the corresponding input elements from the two inputs.
1785 case Intrinsic::x86_sse_sub_ss:
1786 case Intrinsic::x86_sse_mul_ss:
1787 case Intrinsic::x86_sse_min_ss:
1788 case Intrinsic::x86_sse_max_ss:
1789 case Intrinsic::x86_sse2_sub_sd:
1790 case Intrinsic::x86_sse2_mul_sd:
1791 case Intrinsic::x86_sse2_min_sd:
1792 case Intrinsic::x86_sse2_max_sd:
1793 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1794 UndefElts, Depth+1);
1795 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1796 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1797 UndefElts2, Depth+1);
1798 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1799
1800 // If only the low elt is demanded and this is a scalarizable intrinsic,
1801 // scalarize it now.
1802 if (DemandedElts == 1) {
1803 switch (II->getIntrinsicID()) {
1804 default: break;
1805 case Intrinsic::x86_sse_sub_ss:
1806 case Intrinsic::x86_sse_mul_ss:
1807 case Intrinsic::x86_sse2_sub_sd:
1808 case Intrinsic::x86_sse2_mul_sd:
1809 // TODO: Lower MIN/MAX/ABS/etc
1810 Value *LHS = II->getOperand(1);
1811 Value *RHS = II->getOperand(2);
1812 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001813 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001814 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001815 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001816 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817
1818 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001819 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001820 case Intrinsic::x86_sse_sub_ss:
1821 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001822 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001823 II->getName()), *II);
1824 break;
1825 case Intrinsic::x86_sse_mul_ss:
1826 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001827 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828 II->getName()), *II);
1829 break;
1830 }
1831
1832 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001833 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001834 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001835 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001836 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001837 return New;
1838 }
1839 }
1840
1841 // Output elements are undefined if both are undefined. Consider things
1842 // like undef&0. The result is known zero, not undef.
1843 UndefElts &= UndefElts2;
1844 break;
1845 }
1846 break;
1847 }
1848 }
1849 return MadeChange ? I : 0;
1850}
1851
Dan Gohman5d56fd42008-05-19 22:14:15 +00001852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853/// AssociativeOpt - Perform an optimization on an associative operator. This
1854/// function is designed to check a chain of associative operators for a
1855/// potential to apply a certain optimization. Since the optimization may be
1856/// applicable if the expression was reassociated, this checks the chain, then
1857/// reassociates the expression as necessary to expose the optimization
1858/// opportunity. This makes use of a special Functor, which must define
1859/// 'shouldApply' and 'apply' methods.
1860///
1861template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001862static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 unsigned Opcode = Root.getOpcode();
1864 Value *LHS = Root.getOperand(0);
1865
1866 // Quick check, see if the immediate LHS matches...
1867 if (F.shouldApply(LHS))
1868 return F.apply(Root);
1869
1870 // Otherwise, if the LHS is not of the same opcode as the root, return.
1871 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1872 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1873 // Should we apply this transform to the RHS?
1874 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1875
1876 // If not to the RHS, check to see if we should apply to the LHS...
1877 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1878 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1879 ShouldApply = true;
1880 }
1881
1882 // If the functor wants to apply the optimization to the RHS of LHSI,
1883 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1884 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 // Now all of the instructions are in the current basic block, go ahead
1886 // and perform the reassociation.
1887 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1888
1889 // First move the selected RHS to the LHS of the root...
1890 Root.setOperand(0, LHSI->getOperand(1));
1891
1892 // Make what used to be the LHS of the root be the user of the root...
1893 Value *ExtraOperand = TmpLHSI->getOperand(1);
1894 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001895 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 return 0;
1897 }
1898 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1899 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001901 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 ARI = Root;
1903
1904 // Now propagate the ExtraOperand down the chain of instructions until we
1905 // get to LHSI.
1906 while (TmpLHSI != LHSI) {
1907 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1908 // Move the instruction to immediately before the chain we are
1909 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001910 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911 ARI = NextLHSI;
1912
1913 Value *NextOp = NextLHSI->getOperand(1);
1914 NextLHSI->setOperand(1, ExtraOperand);
1915 TmpLHSI = NextLHSI;
1916 ExtraOperand = NextOp;
1917 }
1918
1919 // Now that the instructions are reassociated, have the functor perform
1920 // the transformation...
1921 return F.apply(Root);
1922 }
1923
1924 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1925 }
1926 return 0;
1927}
1928
Dan Gohman089efff2008-05-13 00:00:25 +00001929namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930
Nick Lewycky27f6c132008-05-23 04:34:58 +00001931// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001932struct AddRHS {
1933 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001934 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001935 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1936 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001937 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001938 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 }
1940};
1941
1942// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1943// iff C1&C2 == 0
1944struct AddMaskingAnd {
1945 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001946 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001947 bool shouldApply(Value *LHS) const {
1948 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001949 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001950 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001951 }
1952 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001953 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001954 }
1955};
1956
Dan Gohman089efff2008-05-13 00:00:25 +00001957}
1958
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001959static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1960 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001961 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001962 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963
1964 // Figure out if the constant is the left or the right argument.
1965 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1966 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1967
1968 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1969 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001970 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1971 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001972 }
1973
1974 Value *Op0 = SO, *Op1 = ConstOperand;
1975 if (!ConstIsRHS)
1976 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001977
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001979 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1980 SO->getName()+".op");
1981 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1982 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1983 SO->getName()+".cmp");
1984 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1985 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1986 SO->getName()+".cmp");
1987 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988}
1989
1990// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1991// constant as the other operand, try to fold the binary operator into the
1992// select arguments. This also works for Cast instructions, which obviously do
1993// not have a second operand.
1994static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1995 InstCombiner *IC) {
1996 // Don't modify shared select instructions
1997 if (!SI->hasOneUse()) return 0;
1998 Value *TV = SI->getOperand(1);
1999 Value *FV = SI->getOperand(2);
2000
2001 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2002 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00002003 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004
2005 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2006 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2007
Gabor Greifd6da1d02008-04-06 20:25:17 +00002008 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2009 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002010 }
2011 return 0;
2012}
2013
2014
Chris Lattnerf7843b72009-09-27 19:57:57 +00002015/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2016/// has a PHI node as operand #0, see if we can fold the instruction into the
2017/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00002018///
2019/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2020/// that would normally be unprofitable because they strongly encourage jump
2021/// threading.
2022Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2023 bool AllowAggressive) {
2024 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 PHINode *PN = cast<PHINode>(I.getOperand(0));
2026 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002027 if (NumPHIValues == 0 ||
2028 // We normally only transform phis with a single use, unless we're trying
2029 // hard to make jump threading happen.
2030 (!PN->hasOneUse() && !AllowAggressive))
2031 return 0;
2032
2033
Chris Lattnerf7843b72009-09-27 19:57:57 +00002034 // Check to see if all of the operands of the PHI are simple constants
2035 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002036 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2037 // bail out. We don't do arbitrary constant expressions here because moving
2038 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039 BasicBlock *NonConstBB = 0;
2040 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002041 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2042 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 if (NonConstBB) return 0; // More than one non-const value.
2044 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2045 NonConstBB = PN->getIncomingBlock(i);
2046
2047 // If the incoming non-constant value is in I's block, we have an infinite
2048 // loop.
2049 if (NonConstBB == I.getParent())
2050 return 0;
2051 }
2052
2053 // If there is exactly one non-constant value, we can insert a copy of the
2054 // operation in that block. However, if this is a critical edge, we would be
2055 // inserting the computation one some other paths (e.g. inside a loop). Only
2056 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002057 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002058 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2059 if (!BI || !BI->isUnconditional()) return 0;
2060 }
2061
2062 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002063 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002065 InsertNewInstBefore(NewPN, *PN);
2066 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067
2068 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002069 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2070 // We only currently try to fold the condition of a select when it is a phi,
2071 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002072 Value *TrueV = SI->getTrueValue();
2073 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002074 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002075 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002076 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002077 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2078 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002079 Value *InV = 0;
2080 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002081 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002082 } else {
2083 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002084 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2085 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002086 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002087 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002088 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002089 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002090 }
2091 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 Constant *C = cast<Constant>(I.getOperand(1));
2093 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002094 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2096 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002097 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002099 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 } else {
2101 assert(PN->getIncomingBlock(i) == NonConstBB);
2102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002103 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 PN->getIncomingValue(i), C, "phitmp",
2105 NonConstBB->getTerminator());
2106 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002107 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108 CI->getPredicate(),
2109 PN->getIncomingValue(i), C, "phitmp",
2110 NonConstBB->getTerminator());
2111 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002112 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002113
2114 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002115 }
2116 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2117 }
2118 } else {
2119 CastInst *CI = cast<CastInst>(&I);
2120 const Type *RetTy = CI->getType();
2121 for (unsigned i = 0; i != NumPHIValues; ++i) {
2122 Value *InV;
2123 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002124 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 } else {
2126 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002127 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128 I.getType(), "phitmp",
2129 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002130 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002131 }
2132 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2133 }
2134 }
2135 return ReplaceInstUsesWith(I, NewPN);
2136}
2137
Chris Lattner55476162008-01-29 06:52:45 +00002138
Chris Lattner3554f972008-05-20 05:46:13 +00002139/// WillNotOverflowSignedAdd - Return true if we can prove that:
2140/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2141/// This basically requires proving that the add in the original type would not
2142/// overflow to change the sign bit or have a carry out.
2143bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2144 // There are different heuristics we can use for this. Here are some simple
2145 // ones.
2146
2147 // Add has the property that adding any two 2's complement numbers can only
2148 // have one carry bit which can change a sign. As such, if LHS and RHS each
2149 // have at least two sign bits, we know that the addition of the two values will
2150 // sign extend fine.
2151 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2152 return true;
2153
2154
2155 // If one of the operands only has one non-zero bit, and if the other operand
2156 // has a known-zero bit in a more significant place than it (not including the
2157 // sign bit) the ripple may go up to and fill the zero, but won't change the
2158 // sign. For example, (X & ~4) + 1.
2159
2160 // TODO: Implement.
2161
2162 return false;
2163}
2164
Chris Lattner55476162008-01-29 06:52:45 +00002165
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2167 bool Changed = SimplifyCommutative(I);
2168 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2169
2170 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2171 // X + undef -> undef
2172 if (isa<UndefValue>(RHS))
2173 return ReplaceInstUsesWith(I, RHS);
2174
2175 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002176 if (RHSC->isNullValue())
2177 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2180 // X + (signbit) --> X ^ signbit
2181 const APInt& Val = CI->getValue();
2182 uint32_t BitWidth = Val.getBitWidth();
2183 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002184 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185
2186 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2187 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002188 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002189 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002190
Eli Friedmana21526d2009-07-13 22:27:52 +00002191 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002192 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002193 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002194 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002195 }
2196
2197 if (isa<PHINode>(LHS))
2198 if (Instruction *NV = FoldOpIntoPhi(I))
2199 return NV;
2200
2201 ConstantInt *XorRHS = 0;
2202 Value *XorLHS = 0;
2203 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002204 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002205 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2207
2208 uint32_t Size = TySizeBits / 2;
2209 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2210 APInt CFF80Val(-C0080Val);
2211 do {
2212 if (TySizeBits > Size) {
2213 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2214 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2215 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2216 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2217 // This is a sign extend if the top bits are known zero.
2218 if (!MaskedValueIsZero(XorLHS,
2219 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2220 Size = 0; // Not a sign ext, but can't be any others either.
2221 break;
2222 }
2223 }
2224 Size >>= 1;
2225 C0080Val = APIntOps::lshr(C0080Val, Size);
2226 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2227 } while (Size >= 1);
2228
2229 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002230 // with funny bit widths then this switch statement should be removed. It
2231 // is just here to get the size of the "middle" type back up to something
2232 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002233 const Type *MiddleType = 0;
2234 switch (Size) {
2235 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002236 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2237 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2238 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002239 }
2240 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002241 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002242 return new SExtInst(NewTrunc, I.getType(), I.getName());
2243 }
2244 }
2245 }
2246
Owen Anderson35b47072009-08-13 21:58:54 +00002247 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002248 return BinaryOperator::CreateXor(LHS, RHS);
2249
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002250 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002251 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002252 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002253 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254
2255 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2256 if (RHSI->getOpcode() == Instruction::Sub)
2257 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2258 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2259 }
2260 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2261 if (LHSI->getOpcode() == Instruction::Sub)
2262 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2263 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2264 }
2265 }
2266
2267 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002268 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002269 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002270 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002271 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002272 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002273 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002274 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002275 }
2276
Gabor Greifa645dd32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002278 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279
2280 // A + -B --> A - B
2281 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002282 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002283 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284
2285
2286 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002287 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002289 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290
2291 // X*C1 + X*C2 --> X * (C1+C2)
2292 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002293 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002294 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 }
2296
2297 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002298 if (dyn_castFoldableMul(RHS, C2) == LHS)
2299 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002300
2301 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002302 if (dyn_castNotVal(LHS) == RHS ||
2303 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002304 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305
2306
2307 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002308 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2309 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002311
2312 // A+B --> A|B iff A and B have no bits set in common.
2313 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2314 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2315 APInt LHSKnownOne(IT->getBitWidth(), 0);
2316 APInt LHSKnownZero(IT->getBitWidth(), 0);
2317 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2318 if (LHSKnownZero != 0) {
2319 APInt RHSKnownOne(IT->getBitWidth(), 0);
2320 APInt RHSKnownZero(IT->getBitWidth(), 0);
2321 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2322
2323 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002324 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002325 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002326 }
2327 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002328
Nick Lewycky83598a72008-02-03 07:42:09 +00002329 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002330 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002331 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002332 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2333 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002334 if (W != Y) {
2335 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002336 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002337 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002338 std::swap(W, X);
2339 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002340 std::swap(Y, Z);
2341 std::swap(W, X);
2342 }
2343 }
2344
2345 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002346 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002347 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002348 }
2349 }
2350 }
2351
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002352 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2353 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002354 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002355 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356
2357 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002358 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002359 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361 if (Anded == CRHS) {
2362 // See if all bits from the first bit set in the Add RHS up are included
2363 // in the mask. First, get the rightmost bit.
2364 const APInt& AddRHSV = CRHS->getValue();
2365
2366 // Form a mask of all bits from the lowest bit added through the top.
2367 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2368
2369 // See if the and mask includes all of these bits.
2370 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2371
2372 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2373 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002374 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002375 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002376 }
2377 }
2378 }
2379
2380 // Try to fold constant add into select arguments.
2381 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2382 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2383 return R;
2384 }
2385
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002386 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002387 {
2388 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002389 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002390 if (!SI) {
2391 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002392 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002393 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002394 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002395 Value *TV = SI->getTrueValue();
2396 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002397 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002398
2399 // Can we fold the add into the argument of the select?
2400 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002401 if (match(FV, m_Zero()) &&
2402 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002403 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002404 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002405 if (match(TV, m_Zero()) &&
2406 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002407 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002408 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002409 }
2410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002411
Chris Lattner3554f972008-05-20 05:46:13 +00002412 // Check for (add (sext x), y), see if we can merge this into an
2413 // integer add followed by a sext.
2414 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2415 // (add (sext x), cst) --> (sext (add x, cst'))
2416 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2417 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002418 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002419 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002420 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002421 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2422 // Insert the new, smaller add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002423 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2424 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002425 return new SExtInst(NewAdd, I.getType());
2426 }
2427 }
2428
2429 // (add (sext x), (sext y)) --> (sext (add int x, y))
2430 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2431 // Only do this if x/y have the same type, if at last one of them has a
2432 // single use (so we don't increase the number of sexts), and if the
2433 // integer add will not overflow.
2434 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2435 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2436 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2437 RHSConv->getOperand(0))) {
2438 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002439 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002441 return new SExtInst(NewAdd, I.getType());
2442 }
2443 }
2444 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002445
2446 return Changed ? &I : 0;
2447}
2448
2449Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2450 bool Changed = SimplifyCommutative(I);
2451 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2452
2453 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2454 // X + 0 --> X
2455 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002456 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002457 (I.getType())->getValueAPF()))
2458 return ReplaceInstUsesWith(I, LHS);
2459 }
2460
2461 if (isa<PHINode>(LHS))
2462 if (Instruction *NV = FoldOpIntoPhi(I))
2463 return NV;
2464 }
2465
2466 // -A + B --> B - A
2467 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002468 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002469 return BinaryOperator::CreateFSub(RHS, LHSV);
2470
2471 // A + -B --> A - B
2472 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002473 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002474 return BinaryOperator::CreateFSub(LHS, V);
2475
2476 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2477 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2478 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2479 return ReplaceInstUsesWith(I, LHS);
2480
Chris Lattner3554f972008-05-20 05:46:13 +00002481 // Check for (add double (sitofp x), y), see if we can merge this into an
2482 // integer add followed by a promotion.
2483 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2484 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2485 // ... if the constant fits in the integer value. This is useful for things
2486 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2487 // requires a constant pool load, and generally allows the add to be better
2488 // instcombined.
2489 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2490 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002491 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002492 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002493 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002494 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2495 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002496 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2497 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002498 return new SIToFPInst(NewAdd, I.getType());
2499 }
2500 }
2501
2502 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2503 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2504 // Only do this if x/y have the same type, if at last one of them has a
2505 // single use (so we don't increase the number of int->fp conversions),
2506 // and if the integer add will not overflow.
2507 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2508 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2509 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2510 RHSConv->getOperand(0))) {
2511 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002512 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2513 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002514 return new SIToFPInst(NewAdd, I.getType());
2515 }
2516 }
2517 }
2518
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 return Changed ? &I : 0;
2520}
2521
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002522Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2524
Dan Gohman7ce405e2009-06-04 22:49:04 +00002525 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527
2528 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002529 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531
2532 if (isa<UndefValue>(Op0))
2533 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2534 if (isa<UndefValue>(Op1))
2535 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2536
2537 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2538 // Replace (-1 - A) with (~A)...
2539 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002540 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002541
2542 // C - ~X == X + (1+C)
2543 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002544 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002545 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002546
2547 // -(X >>u 31) -> (X >>s 31)
2548 // -(X >>s 31) -> (X >>u 31)
2549 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002550 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002551 if (SI->getOpcode() == Instruction::LShr) {
2552 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2553 // Check to see if we are shifting out everything but the sign bit.
2554 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2555 SI->getType()->getPrimitiveSizeInBits()-1) {
2556 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002557 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 SI->getOperand(0), CU, SI->getName());
2559 }
2560 }
2561 }
2562 else if (SI->getOpcode() == Instruction::AShr) {
2563 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2564 // Check to see if we are shifting out everything but the sign bit.
2565 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2566 SI->getType()->getPrimitiveSizeInBits()-1) {
2567 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002568 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569 SI->getOperand(0), CU, SI->getName());
2570 }
2571 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002572 }
2573 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002574 }
2575
2576 // Try to fold constant sub into select arguments.
2577 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2579 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002580
2581 // C - zext(bool) -> bool ? C - 1 : C
2582 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002583 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002584 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585 }
2586
Owen Anderson35b47072009-08-13 21:58:54 +00002587 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002588 return BinaryOperator::CreateXor(Op0, Op1);
2589
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002591 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002592 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002593 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002594 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002596 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002597 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2599 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2600 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002601 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002602 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002603 }
2604 }
2605
2606 if (Op1I->hasOneUse()) {
2607 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2608 // is not used by anyone else...
2609 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002610 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002611 // Swap the two operands of the subexpr...
2612 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2613 Op1I->setOperand(0, IIOp1);
2614 Op1I->setOperand(1, IIOp0);
2615
2616 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002617 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618 }
2619
2620 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2621 //
2622 if (Op1I->getOpcode() == Instruction::And &&
2623 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2624 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2625
Chris Lattnerc7694852009-08-30 07:44:24 +00002626 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002627 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002628 }
2629
2630 // 0 - (X sdiv C) -> (X sdiv -C)
2631 if (Op1I->getOpcode() == Instruction::SDiv)
2632 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2633 if (CSI->isZero())
2634 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002635 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002636 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002637
2638 // X - X*C --> X * (1-C)
2639 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002640 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002641 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002642 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002643 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002644 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 }
2646 }
2647 }
2648
Dan Gohman7ce405e2009-06-04 22:49:04 +00002649 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2650 if (Op0I->getOpcode() == Instruction::Add) {
2651 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2652 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2653 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2654 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2655 } else if (Op0I->getOpcode() == Instruction::Sub) {
2656 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002657 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002658 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002659 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002660 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002661
2662 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002663 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002665 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002666
2667 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002668 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002669 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002670 }
2671 return 0;
2672}
2673
Dan Gohman7ce405e2009-06-04 22:49:04 +00002674Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2675 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2676
2677 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002678 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002679 return BinaryOperator::CreateFAdd(Op0, V);
2680
2681 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2682 if (Op1I->getOpcode() == Instruction::FAdd) {
2683 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002684 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002685 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002686 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002687 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002688 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002689 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002690 }
2691
2692 return 0;
2693}
2694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002695/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2696/// comparison only checks the sign bit. If it only checks the sign bit, set
2697/// TrueIfSigned if the result of the comparison is true when the input value is
2698/// signed.
2699static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2700 bool &TrueIfSigned) {
2701 switch (pred) {
2702 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2703 TrueIfSigned = true;
2704 return RHS->isZero();
2705 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2706 TrueIfSigned = true;
2707 return RHS->isAllOnesValue();
2708 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2709 TrueIfSigned = false;
2710 return RHS->isAllOnesValue();
2711 case ICmpInst::ICMP_UGT:
2712 // True if LHS u> RHS and RHS == high-bit-mask - 1
2713 TrueIfSigned = true;
2714 return RHS->getValue() ==
2715 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2716 case ICmpInst::ICMP_UGE:
2717 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2718 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002719 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720 default:
2721 return false;
2722 }
2723}
2724
2725Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2726 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728
Chris Lattner3508c5c2009-10-11 21:36:10 +00002729 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002730 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731
Chris Lattner6438c582009-10-11 07:53:15 +00002732 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002733 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2734 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735
2736 // ((X << C1)*C2) == (X * (C2 << C1))
2737 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2738 if (SI->getOpcode() == Instruction::Shl)
2739 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002740 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002741 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742
2743 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00002744 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 if (CI->equalsInt(1)) // X * 1 == X
2746 return ReplaceInstUsesWith(I, Op0);
2747 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002748 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749
2750 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2751 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002752 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002753 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002755 } else if (isa<VectorType>(Op1C->getType())) {
2756 if (Op1C->isNullValue())
2757 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00002758
Chris Lattner3508c5c2009-10-11 21:36:10 +00002759 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00002760 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002761 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002762
2763 // As above, vector X*splat(1.0) -> X in all defined cases.
2764 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002765 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2766 if (CI->equalsInt(1))
2767 return ReplaceInstUsesWith(I, Op0);
2768 }
2769 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770 }
2771
2772 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2773 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00002774 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002776 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2777 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002778 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779
2780 }
2781
2782 // Try to fold constant mul into select arguments.
2783 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2784 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2785 return R;
2786
2787 if (isa<PHINode>(Op0))
2788 if (Instruction *NV = FoldOpIntoPhi(I))
2789 return NV;
2790 }
2791
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002792 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00002793 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002794 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795
Nick Lewycky1c246402008-11-21 07:33:58 +00002796 // (X / Y) * Y = X - (X % Y)
2797 // (X / Y) * -Y = (X % Y) - X
2798 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00002799 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00002800 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2801 if (!BO ||
2802 (BO->getOpcode() != Instruction::UDiv &&
2803 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00002804 Op1C = Op0;
2805 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002806 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002807 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00002808 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00002809 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00002810 (BO->getOpcode() == Instruction::UDiv ||
2811 BO->getOpcode() == Instruction::SDiv)) {
2812 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2813
Dan Gohman07878902009-08-12 16:33:09 +00002814 // If the division is exact, X % Y is zero.
2815 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2816 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00002817 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00002818 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002819 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00002820 }
2821
Chris Lattnerc7694852009-08-30 07:44:24 +00002822 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00002823 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00002824 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002825 else
Chris Lattnerc7694852009-08-30 07:44:24 +00002826 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002827 Rem->takeName(BO);
2828
Chris Lattner3508c5c2009-10-11 21:36:10 +00002829 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00002830 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00002831 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002832 }
2833 }
2834
Chris Lattner6438c582009-10-11 07:53:15 +00002835 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00002836 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00002837 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002838
Chris Lattner6438c582009-10-11 07:53:15 +00002839 // X*(1 << Y) --> X << Y
2840 // (1 << Y)*X --> X << Y
2841 {
2842 Value *Y;
2843 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00002844 return BinaryOperator::CreateShl(Op1, Y);
2845 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00002846 return BinaryOperator::CreateShl(Op0, Y);
2847 }
2848
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 // If one of the operands of the multiply is a cast from a boolean value, then
2850 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00002851 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2852 if (!isa<VectorType>(I.getType())) {
2853 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00002854 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00002855
Chris Lattner4ca76f72009-10-11 21:29:45 +00002856 Value *BoolCast = 0, *OtherOp = 0;
2857 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00002858 BoolCast = Op0, OtherOp = Op1;
2859 else if (MaskedValueIsZero(Op1, Negative2))
2860 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00002861
Chris Lattner291872e2009-10-11 21:22:21 +00002862 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00002863 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2864 BoolCast, "tmp");
2865 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 }
2867 }
2868
2869 return Changed ? &I : 0;
2870}
2871
Dan Gohman7ce405e2009-06-04 22:49:04 +00002872Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2873 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00002875
2876 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00002877 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2878 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002879 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2880 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2881 if (Op1F->isExactlyValue(1.0))
2882 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00002883 } else if (isa<VectorType>(Op1C->getType())) {
2884 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002885 // As above, vector X*splat(1.0) -> X in all defined cases.
2886 if (Constant *Splat = Op1V->getSplatValue()) {
2887 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2888 if (F->isExactlyValue(1.0))
2889 return ReplaceInstUsesWith(I, Op0);
2890 }
2891 }
2892 }
2893
2894 // Try to fold constant mul into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897 return R;
2898
2899 if (isa<PHINode>(Op0))
2900 if (Instruction *NV = FoldOpIntoPhi(I))
2901 return NV;
2902 }
2903
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002904 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00002905 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002906 return BinaryOperator::CreateFMul(Op0v, Op1v);
2907
2908 return Changed ? &I : 0;
2909}
2910
Chris Lattner76972db2008-07-14 00:15:52 +00002911/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2912/// instruction.
2913bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2914 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2915
2916 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2917 int NonNullOperand = -1;
2918 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2919 if (ST->isNullValue())
2920 NonNullOperand = 2;
2921 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2922 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2923 if (ST->isNullValue())
2924 NonNullOperand = 1;
2925
2926 if (NonNullOperand == -1)
2927 return false;
2928
2929 Value *SelectCond = SI->getOperand(0);
2930
2931 // Change the div/rem to use 'Y' instead of the select.
2932 I.setOperand(1, SI->getOperand(NonNullOperand));
2933
2934 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2935 // problem. However, the select, or the condition of the select may have
2936 // multiple uses. Based on our knowledge that the operand must be non-zero,
2937 // propagate the known value for the select into other uses of it, and
2938 // propagate a known value of the condition into its other users.
2939
2940 // If the select and condition only have a single use, don't bother with this,
2941 // early exit.
2942 if (SI->use_empty() && SelectCond->hasOneUse())
2943 return true;
2944
2945 // Scan the current block backward, looking for other uses of SI.
2946 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2947
2948 while (BBI != BBFront) {
2949 --BBI;
2950 // If we found a call to a function, we can't assume it will return, so
2951 // information from below it cannot be propagated above it.
2952 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2953 break;
2954
2955 // Replace uses of the select or its condition with the known values.
2956 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2957 I != E; ++I) {
2958 if (*I == SI) {
2959 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00002960 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002961 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002962 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2963 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00002964 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002965 }
2966 }
2967
2968 // If we past the instruction, quit looking for it.
2969 if (&*BBI == SI)
2970 SI = 0;
2971 if (&*BBI == SelectCond)
2972 SelectCond = 0;
2973
2974 // If we ran out of things to eliminate, break out of the loop.
2975 if (SelectCond == 0 && SI == 0)
2976 break;
2977
2978 }
2979 return true;
2980}
2981
2982
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983/// This function implements the transforms on div instructions that work
2984/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2985/// used by the visitors to those instructions.
2986/// @brief Transforms common to all three div instructions
2987Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2988 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2989
Chris Lattner653ef3c2008-02-19 06:12:18 +00002990 // undef / X -> 0 for integer.
2991 // undef / X -> undef for FP (the undef could be a snan).
2992 if (isa<UndefValue>(Op0)) {
2993 if (Op0->getType()->isFPOrFPVector())
2994 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002996 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002997
2998 // X / undef -> undef
2999 if (isa<UndefValue>(Op1))
3000 return ReplaceInstUsesWith(I, Op1);
3001
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003002 return 0;
3003}
3004
3005/// This function implements the transforms common to both integer division
3006/// instructions (udiv and sdiv). It is called by the visitors to those integer
3007/// division instructions.
3008/// @brief Common integer divide transforms
3009Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3011
Chris Lattnercefb36c2008-05-16 02:59:42 +00003012 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003013 if (Op0 == Op1) {
3014 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003015 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003016 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003017 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003018 }
3019
Owen Andersoneacb44d2009-07-24 23:12:02 +00003020 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003021 return ReplaceInstUsesWith(I, CI);
3022 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024 if (Instruction *Common = commonDivTransforms(I))
3025 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003026
3027 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3028 // This does not apply for fdiv.
3029 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3030 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003031
3032 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3033 // div X, 1 == X
3034 if (RHS->equalsInt(1))
3035 return ReplaceInstUsesWith(I, Op0);
3036
3037 // (X / C1) / C2 -> X / (C1*C2)
3038 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3039 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3040 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003041 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003042 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003044 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003045 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003046 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 }
3048
3049 if (!RHS->isZero()) { // avoid X udiv 0
3050 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3052 return R;
3053 if (isa<PHINode>(Op0))
3054 if (Instruction *NV = FoldOpIntoPhi(I))
3055 return NV;
3056 }
3057 }
3058
3059 // 0 / X == 0, we don't need to preserve faults!
3060 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3061 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003064 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003065 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003066 return ReplaceInstUsesWith(I, Op0);
3067
Nick Lewycky94418732008-11-27 20:21:08 +00003068 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3069 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3070 // div X, 1 == X
3071 if (X->isOne())
3072 return ReplaceInstUsesWith(I, Op0);
3073 }
3074
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 return 0;
3076}
3077
3078Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3080
3081 // Handle the integer div common cases
3082 if (Instruction *Common = commonIDivTransforms(I))
3083 return Common;
3084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003086 // X udiv C^2 -> X >> C
3087 // Check to see if this is an unsigned division with an exact power of 2,
3088 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003090 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003091 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003092
3093 // X udiv C, where C >= signbit
3094 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003095 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003096 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003097 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003098 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003099 }
3100
3101 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3102 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3103 if (RHSI->getOpcode() == Instruction::Shl &&
3104 isa<ConstantInt>(RHSI->getOperand(0))) {
3105 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3106 if (C1.isPowerOf2()) {
3107 Value *N = RHSI->getOperand(1);
3108 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003109 if (uint32_t C2 = C1.logBase2())
3110 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003111 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112 }
3113 }
3114 }
3115
3116 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3117 // where C1&C2 are powers of two.
3118 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3119 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3120 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3121 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3122 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3123 // Compute the shift amounts
3124 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3125 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003126 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003127 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128
3129 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003130 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003131 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003132
3133 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003134 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003135 }
3136 }
3137 return 0;
3138}
3139
3140Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3142
3143 // Handle the integer div common cases
3144 if (Instruction *Common = commonIDivTransforms(I))
3145 return Common;
3146
3147 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3148 // sdiv X, -1 == -X
3149 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003150 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003151
Dan Gohman07878902009-08-12 16:33:09 +00003152 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003153 if (cast<SDivOperator>(&I)->isExact() &&
3154 RHS->getValue().isNonNegative() &&
3155 RHS->getValue().isPowerOf2()) {
3156 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3157 RHS->getValue().exactLogBase2());
3158 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3159 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003160
3161 // -X/C --> X/-C provided the negation doesn't overflow.
3162 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3163 if (isa<Constant>(Sub->getOperand(0)) &&
3164 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003165 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003166 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3167 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 }
3169
3170 // If the sign bits of both operands are zero (i.e. we can prove they are
3171 // unsigned inputs), turn this into a udiv.
3172 if (I.getType()->isInteger()) {
3173 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003174 if (MaskedValueIsZero(Op0, Mask)) {
3175 if (MaskedValueIsZero(Op1, Mask)) {
3176 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3177 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3178 }
3179 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003180 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003181 ShiftedInt->getValue().isPowerOf2()) {
3182 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3183 // Safe because the only negative value (1 << Y) can take on is
3184 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3185 // the sign bit set.
3186 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3187 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003189 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190
3191 return 0;
3192}
3193
3194Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3195 return commonDivTransforms(I);
3196}
3197
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198/// This function implements the transforms on rem instructions that work
3199/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3200/// is used by the visitors to those instructions.
3201/// @brief Transforms common to all three rem instructions
3202Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
Chris Lattner653ef3c2008-02-19 06:12:18 +00003205 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3206 if (I.getType()->isFPOrFPVector())
3207 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003208 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003209 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003210 if (isa<UndefValue>(Op1))
3211 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3212
3213 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003214 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3215 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216
3217 return 0;
3218}
3219
3220/// This function implements the transforms common to both integer remainder
3221/// instructions (urem and srem). It is called by the visitors to those integer
3222/// remainder instructions.
3223/// @brief Common integer remainder transforms
3224Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3226
3227 if (Instruction *common = commonRemTransforms(I))
3228 return common;
3229
Dale Johannesena51f7372009-01-21 00:35:19 +00003230 // 0 % X == 0 for integer, we don't need to preserve faults!
3231 if (Constant *LHS = dyn_cast<Constant>(Op0))
3232 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003234
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003235 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3236 // X % 0 == undef, we don't need to preserve faults!
3237 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003238 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239
3240 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242
3243 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3244 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3245 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3246 return R;
3247 } else if (isa<PHINode>(Op0I)) {
3248 if (Instruction *NV = FoldOpIntoPhi(I))
3249 return NV;
3250 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003251
3252 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003253 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003254 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003255 }
3256 }
3257
3258 return 0;
3259}
3260
3261Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3263
3264 if (Instruction *common = commonIRemTransforms(I))
3265 return common;
3266
3267 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3268 // X urem C^2 -> X and C
3269 // Check to see if this is an unsigned remainder with an exact power of 2,
3270 // if so, convert to a bitwise and.
3271 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3272 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003273 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003274 }
3275
3276 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3277 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3278 if (RHSI->getOpcode() == Instruction::Shl &&
3279 isa<ConstantInt>(RHSI->getOperand(0))) {
3280 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003281 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003282 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003283 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 }
3285 }
3286 }
3287
3288 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3289 // where C1&C2 are powers of two.
3290 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3291 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3292 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3293 // STO == 0 and SFO == 0 handled above.
3294 if ((STO->getValue().isPowerOf2()) &&
3295 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003296 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3297 SI->getName()+".t");
3298 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3299 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003300 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003301 }
3302 }
3303 }
3304
3305 return 0;
3306}
3307
3308Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
Dan Gohmandb3dd962007-11-05 23:16:33 +00003311 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003312 if (Instruction *Common = commonIRemTransforms(I))
3313 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003314
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003315 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003316 if (!isa<Constant>(RHSNeg) ||
3317 (isa<ConstantInt>(RHSNeg) &&
3318 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003319 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003320 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003321 I.setOperand(1, RHSNeg);
3322 return &I;
3323 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003324
Dan Gohmandb3dd962007-11-05 23:16:33 +00003325 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003326 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003327 if (I.getType()->isInteger()) {
3328 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3329 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3330 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003331 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003332 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003333 }
3334
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003335 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003336 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3337 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003338
Nick Lewyckyfd746832008-12-20 16:48:00 +00003339 bool hasNegative = false;
3340 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3341 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3342 if (RHS->getValue().isNegative())
3343 hasNegative = true;
3344
3345 if (hasNegative) {
3346 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003347 for (unsigned i = 0; i != VWidth; ++i) {
3348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3349 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003350 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003351 else
3352 Elts[i] = RHS;
3353 }
3354 }
3355
Owen Anderson2f422e02009-07-28 21:19:26 +00003356 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003357 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003358 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003359 I.setOperand(1, NewRHSV);
3360 return &I;
3361 }
3362 }
3363 }
3364
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 return 0;
3366}
3367
3368Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3369 return commonRemTransforms(I);
3370}
3371
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372// isOneBitSet - Return true if there is exactly one bit set in the specified
3373// constant.
3374static bool isOneBitSet(const ConstantInt *CI) {
3375 return CI->getValue().isPowerOf2();
3376}
3377
3378// isHighOnes - Return true if the constant is of the form 1+0+.
3379// This is the same as lowones(~X).
3380static bool isHighOnes(const ConstantInt *CI) {
3381 return (~CI->getValue() + 1).isPowerOf2();
3382}
3383
3384/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3385/// are carefully arranged to allow folding of expressions such as:
3386///
3387/// (A < B) | (A > B) --> (A != B)
3388///
3389/// Note that this is only valid if the first and second predicates have the
3390/// same sign. Is illegal to do: (A u< B) | (A s> B)
3391///
3392/// Three bits are used to represent the condition, as follows:
3393/// 0 A > B
3394/// 1 A == B
3395/// 2 A < B
3396///
3397/// <=> Value Definition
3398/// 000 0 Always false
3399/// 001 1 A > B
3400/// 010 2 A == B
3401/// 011 3 A >= B
3402/// 100 4 A < B
3403/// 101 5 A != B
3404/// 110 6 A <= B
3405/// 111 7 Always true
3406///
3407static unsigned getICmpCode(const ICmpInst *ICI) {
3408 switch (ICI->getPredicate()) {
3409 // False -> 0
3410 case ICmpInst::ICMP_UGT: return 1; // 001
3411 case ICmpInst::ICMP_SGT: return 1; // 001
3412 case ICmpInst::ICMP_EQ: return 2; // 010
3413 case ICmpInst::ICMP_UGE: return 3; // 011
3414 case ICmpInst::ICMP_SGE: return 3; // 011
3415 case ICmpInst::ICMP_ULT: return 4; // 100
3416 case ICmpInst::ICMP_SLT: return 4; // 100
3417 case ICmpInst::ICMP_NE: return 5; // 101
3418 case ICmpInst::ICMP_ULE: return 6; // 110
3419 case ICmpInst::ICMP_SLE: return 6; // 110
3420 // True -> 7
3421 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003422 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 return 0;
3424 }
3425}
3426
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003427/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3428/// predicate into a three bit mask. It also returns whether it is an ordered
3429/// predicate by reference.
3430static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3431 isOrdered = false;
3432 switch (CC) {
3433 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3434 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003435 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3436 case FCmpInst::FCMP_UGT: return 1; // 001
3437 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3438 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003439 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3440 case FCmpInst::FCMP_UGE: return 3; // 011
3441 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3442 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003443 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3444 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003445 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3446 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003447 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003448 default:
3449 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003450 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003451 return 0;
3452 }
3453}
3454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455/// getICmpValue - This is the complement of getICmpCode, which turns an
3456/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003457/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003458/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003459static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003460 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003462 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003463 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003464 case 1:
3465 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003466 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003468 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3469 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470 case 3:
3471 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003472 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003473 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003474 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003475 case 4:
3476 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003477 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003479 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3480 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003481 case 6:
3482 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003483 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003485 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003486 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 }
3488}
3489
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003490/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3491/// opcode and two operands into either a FCmp instruction. isordered is passed
3492/// in to determine which kind of predicate to use in the new fcmp instruction.
3493static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003494 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003495 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003496 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003497 case 0:
3498 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003499 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003500 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003501 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003502 case 1:
3503 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003504 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003505 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003506 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003507 case 2:
3508 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003509 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003510 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003511 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003512 case 3:
3513 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003514 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003515 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003516 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003517 case 4:
3518 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003519 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003520 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003521 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003522 case 5:
3523 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003524 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003525 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003526 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003527 case 6:
3528 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003529 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003530 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003531 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003532 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003533 }
3534}
3535
Chris Lattner2972b822008-11-16 04:55:20 +00003536/// PredicatesFoldable - Return true if both predicates match sign or if at
3537/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003538static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003539 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3540 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3541 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542}
3543
3544namespace {
3545// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3546struct FoldICmpLogical {
3547 InstCombiner &IC;
3548 Value *LHS, *RHS;
3549 ICmpInst::Predicate pred;
3550 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3551 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3552 pred(ICI->getPredicate()) {}
3553 bool shouldApply(Value *V) const {
3554 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3555 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003556 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3557 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 return false;
3559 }
3560 Instruction *apply(Instruction &Log) const {
3561 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3562 if (ICI->getOperand(0) != LHS) {
3563 assert(ICI->getOperand(1) == LHS);
3564 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3565 }
3566
3567 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3568 unsigned LHSCode = getICmpCode(ICI);
3569 unsigned RHSCode = getICmpCode(RHSICI);
3570 unsigned Code;
3571 switch (Log.getOpcode()) {
3572 case Instruction::And: Code = LHSCode & RHSCode; break;
3573 case Instruction::Or: Code = LHSCode | RHSCode; break;
3574 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003575 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003576 }
3577
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003578 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003579 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003580 if (Instruction *I = dyn_cast<Instruction>(RV))
3581 return I;
3582 // Otherwise, it's a constant boolean value...
3583 return IC.ReplaceInstUsesWith(Log, RV);
3584 }
3585};
3586} // end anonymous namespace
3587
3588// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3589// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3590// guaranteed to be a binary operator.
3591Instruction *InstCombiner::OptAndOp(Instruction *Op,
3592 ConstantInt *OpRHS,
3593 ConstantInt *AndRHS,
3594 BinaryOperator &TheAnd) {
3595 Value *X = Op->getOperand(0);
3596 Constant *Together = 0;
3597 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003598 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003599
3600 switch (Op->getOpcode()) {
3601 case Instruction::Xor:
3602 if (Op->hasOneUse()) {
3603 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003604 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003605 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003606 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003607 }
3608 break;
3609 case Instruction::Or:
3610 if (Together == AndRHS) // (X | C) & C --> C
3611 return ReplaceInstUsesWith(TheAnd, AndRHS);
3612
3613 if (Op->hasOneUse() && Together != OpRHS) {
3614 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003615 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003617 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003618 }
3619 break;
3620 case Instruction::Add:
3621 if (Op->hasOneUse()) {
3622 // Adding a one to a single bit bit-field should be turned into an XOR
3623 // of the bit. First thing to check is to see if this AND is with a
3624 // single bit constant.
3625 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3626
3627 // If there is only one bit set...
3628 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3629 // Ok, at this point, we know that we are masking the result of the
3630 // ADD down to exactly one bit. If the constant we are adding has
3631 // no bits set below this bit, then we can eliminate the ADD.
3632 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3633
3634 // Check to see if any bits below the one bit set in AndRHSV are set.
3635 if ((AddRHS & (AndRHSV-1)) == 0) {
3636 // If not, the only thing that can effect the output of the AND is
3637 // the bit specified by AndRHSV. If that bit is set, the effect of
3638 // the XOR is to toggle the bit. If it is clear, then the ADD has
3639 // no effect.
3640 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3641 TheAnd.setOperand(0, X);
3642 return &TheAnd;
3643 } else {
3644 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003645 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003646 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003647 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648 }
3649 }
3650 }
3651 }
3652 break;
3653
3654 case Instruction::Shl: {
3655 // We know that the AND will not produce any of the bits shifted in, so if
3656 // the anded constant includes them, clear them now!
3657 //
3658 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3659 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3660 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003661 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003662
3663 if (CI->getValue() == ShlMask) {
3664 // Masking out bits that the shift already masks
3665 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3666 } else if (CI != AndRHS) { // Reducing bits set in and.
3667 TheAnd.setOperand(1, CI);
3668 return &TheAnd;
3669 }
3670 break;
3671 }
3672 case Instruction::LShr:
3673 {
3674 // We know that the AND will not produce any of the bits shifted in, so if
3675 // the anded constant includes them, clear them now! This only applies to
3676 // unsigned shifts, because a signed shr may bring in set bits!
3677 //
3678 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3679 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3680 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003681 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003682
3683 if (CI->getValue() == ShrMask) {
3684 // Masking out bits that the shift already masks.
3685 return ReplaceInstUsesWith(TheAnd, Op);
3686 } else if (CI != AndRHS) {
3687 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3688 return &TheAnd;
3689 }
3690 break;
3691 }
3692 case Instruction::AShr:
3693 // Signed shr.
3694 // See if this is shifting in some sign extension, then masking it out
3695 // with an and.
3696 if (Op->hasOneUse()) {
3697 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3698 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3699 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003700 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003701 if (C == AndRHS) { // Masking out bits shifted in.
3702 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3703 // Make the argument unsigned.
3704 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003705 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003706 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 }
3708 }
3709 break;
3710 }
3711 return 0;
3712}
3713
3714
3715/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3716/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3717/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3718/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3719/// insert new instructions.
3720Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3721 bool isSigned, bool Inside,
3722 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003723 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003724 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3725 "Lo is not <= Hi in range emission code!");
3726
3727 if (Inside) {
3728 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003729 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730
3731 // V >= Min && V < Hi --> V < Hi
3732 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3733 ICmpInst::Predicate pred = (isSigned ?
3734 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003735 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 }
3737
3738 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003739 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003740 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003741 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003742 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003743 }
3744
3745 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003746 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003747
3748 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003749 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003750 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3751 ICmpInst::Predicate pred = (isSigned ?
3752 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003753 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003754 }
3755
3756 // Emit V-Lo >u Hi-1-Lo
3757 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003758 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003759 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003760 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003761 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762}
3763
3764// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3765// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3766// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3767// not, since all 1s are not contiguous.
3768static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3769 const APInt& V = Val->getValue();
3770 uint32_t BitWidth = Val->getType()->getBitWidth();
3771 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3772
3773 // look for the first zero bit after the run of ones
3774 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3775 // look for the first non-zero bit
3776 ME = V.getActiveBits();
3777 return true;
3778}
3779
3780/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3781/// where isSub determines whether the operator is a sub. If we can fold one of
3782/// the following xforms:
3783///
3784/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3785/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3786/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3787///
3788/// return (A +/- B).
3789///
3790Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3791 ConstantInt *Mask, bool isSub,
3792 Instruction &I) {
3793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3794 if (!LHSI || LHSI->getNumOperands() != 2 ||
3795 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3796
3797 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3798
3799 switch (LHSI->getOpcode()) {
3800 default: return 0;
3801 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003802 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3804 if ((Mask->getValue().countLeadingZeros() +
3805 Mask->getValue().countPopulation()) ==
3806 Mask->getValue().getBitWidth())
3807 break;
3808
3809 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3810 // part, we don't need any explicit masks to take them out of A. If that
3811 // is all N is, ignore it.
3812 uint32_t MB = 0, ME = 0;
3813 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3814 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3815 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3816 if (MaskedValueIsZero(RHS, Mask))
3817 break;
3818 }
3819 }
3820 return 0;
3821 case Instruction::Or:
3822 case Instruction::Xor:
3823 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3824 if ((Mask->getValue().countLeadingZeros() +
3825 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003826 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003827 break;
3828 return 0;
3829 }
3830
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00003832 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3833 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003834}
3835
Chris Lattner0631ea72008-11-16 05:06:21 +00003836/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3837Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3838 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003839 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003840 ConstantInt *LHSCst, *RHSCst;
3841 ICmpInst::Predicate LHSCC, RHSCC;
3842
Chris Lattnerf3803482008-11-16 05:10:52 +00003843 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003844 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003845 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003846 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003847 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003848 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003849
3850 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3851 // where C is a power of 2
3852 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3853 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003854 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00003855 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003856 }
3857
3858 // From here on, we only handle:
3859 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3860 if (Val != Val2) return 0;
3861
Chris Lattner0631ea72008-11-16 05:06:21 +00003862 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3863 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3864 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3865 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3866 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3867 return 0;
3868
3869 // We can't fold (ugt x, C) & (sgt x, C2).
3870 if (!PredicatesFoldable(LHSCC, RHSCC))
3871 return 0;
3872
3873 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003874 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003875 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00003876 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003877 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003878 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003879 else
Chris Lattner665298f2008-11-16 05:14:43 +00003880 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3881
3882 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003883 std::swap(LHS, RHS);
3884 std::swap(LHSCst, RHSCst);
3885 std::swap(LHSCC, RHSCC);
3886 }
3887
3888 // At this point, we know we have have two icmp instructions
3889 // comparing a value against two constants and and'ing the result
3890 // together. Because of the above check, we know that we only have
3891 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3892 // (from the FoldICmpLogical check above), that the two constants
3893 // are not equal and that the larger constant is on the RHS
3894 assert(LHSCst != RHSCst && "Compares not folded above?");
3895
3896 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003897 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_EQ:
3899 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003900 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3902 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3903 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003904 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003905 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3906 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3907 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3908 return ReplaceInstUsesWith(I, LHS);
3909 }
3910 case ICmpInst::ICMP_NE:
3911 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003914 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003915 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003916 break; // (X != 13 & X u< 15) -> no change
3917 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003918 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003919 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003920 break; // (X != 13 & X s< 15) -> no change
3921 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3922 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3923 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3924 return ReplaceInstUsesWith(I, RHS);
3925 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003926 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003927 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003928 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00003929 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003930 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003931 }
3932 break; // (X != 13 & X != 15) -> no change
3933 }
3934 break;
3935 case ICmpInst::ICMP_ULT:
3936 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003937 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003938 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3939 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003941 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3942 break;
3943 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3944 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3945 return ReplaceInstUsesWith(I, LHS);
3946 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3947 break;
3948 }
3949 break;
3950 case ICmpInst::ICMP_SLT:
3951 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003952 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003953 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3954 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003955 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003956 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3957 break;
3958 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3959 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3960 return ReplaceInstUsesWith(I, LHS);
3961 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3962 break;
3963 }
3964 break;
3965 case ICmpInst::ICMP_UGT:
3966 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003967 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003968 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3969 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3970 return ReplaceInstUsesWith(I, RHS);
3971 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3972 break;
3973 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003974 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003975 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003976 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003977 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003978 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003979 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003980 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3981 break;
3982 }
3983 break;
3984 case ICmpInst::ICMP_SGT:
3985 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003986 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003987 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3988 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3989 return ReplaceInstUsesWith(I, RHS);
3990 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3991 break;
3992 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003993 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003994 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003995 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003996 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003997 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003998 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003999 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4000 break;
4001 }
4002 break;
4003 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004004
4005 return 0;
4006}
4007
Chris Lattner93a359a2009-07-23 05:14:02 +00004008Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4009 FCmpInst *RHS) {
4010
4011 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4012 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4013 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4014 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4015 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4016 // If either of the constants are nans, then the whole thing returns
4017 // false.
4018 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004019 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004020 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004021 LHS->getOperand(0), RHS->getOperand(0));
4022 }
Chris Lattnercf373552009-07-23 05:32:17 +00004023
4024 // Handle vector zeros. This occurs because the canonical form of
4025 // "fcmp ord x,x" is "fcmp ord x, 0".
4026 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4027 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004028 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004029 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004030 return 0;
4031 }
4032
4033 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4034 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4035 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4036
4037
4038 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4039 // Swap RHS operands to match LHS.
4040 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4041 std::swap(Op1LHS, Op1RHS);
4042 }
4043
4044 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4045 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4046 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004047 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004048
4049 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004050 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004051 if (Op0CC == FCmpInst::FCMP_TRUE)
4052 return ReplaceInstUsesWith(I, RHS);
4053 if (Op1CC == FCmpInst::FCMP_TRUE)
4054 return ReplaceInstUsesWith(I, LHS);
4055
4056 bool Op0Ordered;
4057 bool Op1Ordered;
4058 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4059 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4060 if (Op1Pred == 0) {
4061 std::swap(LHS, RHS);
4062 std::swap(Op0Pred, Op1Pred);
4063 std::swap(Op0Ordered, Op1Ordered);
4064 }
4065 if (Op0Pred == 0) {
4066 // uno && ueq -> uno && (uno || eq) -> ueq
4067 // ord && olt -> ord && (ord && lt) -> olt
4068 if (Op0Ordered == Op1Ordered)
4069 return ReplaceInstUsesWith(I, RHS);
4070
4071 // uno && oeq -> uno && (ord && eq) -> false
4072 // uno && ord -> false
4073 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004074 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004075 // ord && ueq -> ord && (uno || eq) -> oeq
4076 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4077 Op0LHS, Op0RHS, Context));
4078 }
4079 }
4080
4081 return 0;
4082}
4083
Chris Lattner0631ea72008-11-16 05:06:21 +00004084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004085Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4086 bool Changed = SimplifyCommutative(I);
4087 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4088
4089 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004090 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091
4092 // and X, X = X
4093 if (Op0 == Op1)
4094 return ReplaceInstUsesWith(I, Op1);
4095
4096 // See if we can simplify any instructions used by the instruction whose sole
4097 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004098 if (SimplifyDemandedInstructionBits(I))
4099 return &I;
4100 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004101 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4102 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4103 return ReplaceInstUsesWith(I, I.getOperand(0));
4104 } else if (isa<ConstantAggregateZero>(Op1)) {
4105 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4106 }
4107 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004109 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004110 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004111 APInt NotAndRHS(~AndRHSMask);
4112
4113 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004115 Value *Op0LHS = Op0I->getOperand(0);
4116 Value *Op0RHS = Op0I->getOperand(1);
4117 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004118 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004119 case Instruction::Xor:
4120 case Instruction::Or:
4121 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004122 if (!Op0I->hasOneUse()) break;
4123
4124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4125 // Not masking anything out for the LHS, move to RHS.
4126 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4127 Op0RHS->getName()+".masked");
4128 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4129 }
4130 if (!isa<Constant>(Op0RHS) &&
4131 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4132 // Not masking anything out for the RHS, move to LHS.
4133 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4134 Op0LHS->getName()+".masked");
4135 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004136 }
4137
4138 break;
4139 case Instruction::Add:
4140 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4141 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4142 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4143 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004144 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004147 break;
4148
4149 case Instruction::Sub:
4150 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4151 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4152 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4153 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004154 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004155
Nick Lewyckya349ba42008-07-10 05:51:40 +00004156 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4157 // has 1's for all bits that the subtraction with A might affect.
4158 if (Op0I->hasOneUse()) {
4159 uint32_t BitWidth = AndRHSMask.getBitWidth();
4160 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4161 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4162
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004163 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004164 if (!(A && A->isZero()) && // avoid infinite recursion.
4165 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004166 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004167 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4168 }
4169 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004171
4172 case Instruction::Shl:
4173 case Instruction::LShr:
4174 // (1 << x) & 1 --> zext(x == 0)
4175 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004176 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004177 Value *NewICmp =
4178 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004179 return new ZExtInst(NewICmp, I.getType());
4180 }
4181 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004182 }
4183
4184 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4185 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4186 return Res;
4187 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4188 // If this is an integer truncation or change from signed-to-unsigned, and
4189 // if the source is an and/or with immediate, transform it. This
4190 // frequently occurs for bitfield accesses.
4191 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4192 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4193 CastOp->getNumOperands() == 2)
Chris Lattnerf05d95c2009-10-26 01:06:31 +00004194 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004195 if (CastOp->getOpcode() == Instruction::And) {
4196 // Change: and (cast (and X, C1) to T), C2
4197 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4198 // This will fold the two constants together, which may allow
4199 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004200 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201 CastOp->getOperand(0), I.getType(),
4202 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004204 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004205 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004206 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004207 } else if (CastOp->getOpcode() == Instruction::Or) {
4208 // Change: and (cast (or X, C1) to T), C2
4209 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004210 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004211 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004212 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213 return ReplaceInstUsesWith(I, AndRHS);
4214 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004215 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216 }
4217 }
4218
4219 // Try to fold constant and into select arguments.
4220 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4221 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4222 return R;
4223 if (isa<PHINode>(Op0))
4224 if (Instruction *NV = FoldOpIntoPhi(I))
4225 return NV;
4226 }
4227
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004228 Value *Op0NotVal = dyn_castNotVal(Op0);
4229 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004230
4231 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004233
4234 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4235 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004236 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4237 I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004238 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004239 }
4240
4241 {
4242 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004243 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004244 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4245 return ReplaceInstUsesWith(I, Op1);
4246
4247 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004248 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004249 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004250 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004251 }
4252 }
4253
Dan Gohmancdff2122009-08-12 16:23:25 +00004254 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4256 return ReplaceInstUsesWith(I, Op0);
4257
4258 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004259 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004260 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004261 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004262 }
4263 }
4264
4265 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004266 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004267 if (A == Op1) { // (A^B)&A -> A&(A^B)
4268 I.swapOperands(); // Simplify below
4269 std::swap(Op0, Op1);
4270 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4271 cast<BinaryOperator>(Op0)->swapOperands();
4272 I.swapOperands(); // Simplify below
4273 std::swap(Op0, Op1);
4274 }
4275 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004276
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004277 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004278 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004279 if (B == Op0) { // B&(A^B) -> B&(B^A)
4280 cast<BinaryOperator>(Op1)->swapOperands();
4281 std::swap(A, B);
4282 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004283 if (A == Op0) // A&(A^B) -> A & ~B
4284 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004285 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004286
4287 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004288 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4289 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004290 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004291 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4292 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004293 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004294 }
4295
4296 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4297 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004298 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004299 return R;
4300
Chris Lattner0631ea72008-11-16 05:06:21 +00004301 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4302 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4303 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004304 }
4305
4306 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4307 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4308 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4309 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4310 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004311 if (SrcTy == Op1C->getOperand(0)->getType() &&
4312 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313 // Only do this if the casts both really cause code to be generated.
4314 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4315 I.getType(), TD) &&
4316 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4317 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004318 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4319 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004320 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 }
4322 }
4323
4324 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4325 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4326 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4327 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4328 SI0->getOperand(1) == SI1->getOperand(1) &&
4329 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004330 Value *NewOp =
4331 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4332 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004333 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004334 SI1->getOperand(1));
4335 }
4336 }
4337
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004338 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004339 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004340 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4341 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4342 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004343 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004344
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004345 return Changed ? &I : 0;
4346}
4347
Chris Lattner567f5112008-10-05 02:13:19 +00004348/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4349/// capable of providing pieces of a bswap. The subexpression provides pieces
4350/// of a bswap if it is proven that each of the non-zero bytes in the output of
4351/// the expression came from the corresponding "byte swapped" byte in some other
4352/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4353/// we know that the expression deposits the low byte of %X into the high byte
4354/// of the bswap result and that all other bytes are zero. This expression is
4355/// accepted, the high byte of ByteValues is set to X to indicate a correct
4356/// match.
4357///
4358/// This function returns true if the match was unsuccessful and false if so.
4359/// On entry to the function the "OverallLeftShift" is a signed integer value
4360/// indicating the number of bytes that the subexpression is later shifted. For
4361/// example, if the expression is later right shifted by 16 bits, the
4362/// OverallLeftShift value would be -2 on entry. This is used to specify which
4363/// byte of ByteValues is actually being set.
4364///
4365/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4366/// byte is masked to zero by a user. For example, in (X & 255), X will be
4367/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4368/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4369/// always in the local (OverallLeftShift) coordinate space.
4370///
4371static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4372 SmallVector<Value*, 8> &ByteValues) {
4373 if (Instruction *I = dyn_cast<Instruction>(V)) {
4374 // If this is an or instruction, it may be an inner node of the bswap.
4375 if (I->getOpcode() == Instruction::Or) {
4376 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4377 ByteValues) ||
4378 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4379 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004380 }
Chris Lattner567f5112008-10-05 02:13:19 +00004381
4382 // If this is a logical shift by a constant multiple of 8, recurse with
4383 // OverallLeftShift and ByteMask adjusted.
4384 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4385 unsigned ShAmt =
4386 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4387 // Ensure the shift amount is defined and of a byte value.
4388 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4389 return true;
4390
4391 unsigned ByteShift = ShAmt >> 3;
4392 if (I->getOpcode() == Instruction::Shl) {
4393 // X << 2 -> collect(X, +2)
4394 OverallLeftShift += ByteShift;
4395 ByteMask >>= ByteShift;
4396 } else {
4397 // X >>u 2 -> collect(X, -2)
4398 OverallLeftShift -= ByteShift;
4399 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004400 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004401 }
4402
4403 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4404 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4405
4406 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4407 ByteValues);
4408 }
4409
4410 // If this is a logical 'and' with a mask that clears bytes, clear the
4411 // corresponding bytes in ByteMask.
4412 if (I->getOpcode() == Instruction::And &&
4413 isa<ConstantInt>(I->getOperand(1))) {
4414 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4415 unsigned NumBytes = ByteValues.size();
4416 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4417 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4418
4419 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4420 // If this byte is masked out by a later operation, we don't care what
4421 // the and mask is.
4422 if ((ByteMask & (1 << i)) == 0)
4423 continue;
4424
4425 // If the AndMask is all zeros for this byte, clear the bit.
4426 APInt MaskB = AndMask & Byte;
4427 if (MaskB == 0) {
4428 ByteMask &= ~(1U << i);
4429 continue;
4430 }
4431
4432 // If the AndMask is not all ones for this byte, it's not a bytezap.
4433 if (MaskB != Byte)
4434 return true;
4435
4436 // Otherwise, this byte is kept.
4437 }
4438
4439 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4440 ByteValues);
4441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004442 }
4443
Chris Lattner567f5112008-10-05 02:13:19 +00004444 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4445 // the input value to the bswap. Some observations: 1) if more than one byte
4446 // is demanded from this input, then it could not be successfully assembled
4447 // into a byteswap. At least one of the two bytes would not be aligned with
4448 // their ultimate destination.
4449 if (!isPowerOf2_32(ByteMask)) return true;
4450 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004451
Chris Lattner567f5112008-10-05 02:13:19 +00004452 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4453 // is demanded, it needs to go into byte 0 of the result. This means that the
4454 // byte needs to be shifted until it lands in the right byte bucket. The
4455 // shift amount depends on the position: if the byte is coming from the high
4456 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4457 // low part, it must be shifted left.
4458 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4459 if (InputByteNo < ByteValues.size()/2) {
4460 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4461 return true;
4462 } else {
4463 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4464 return true;
4465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004466
4467 // If the destination byte value is already defined, the values are or'd
4468 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004469 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004470 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004471 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472 return false;
4473}
4474
4475/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4476/// If so, insert the new bswap intrinsic and return it.
4477Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4478 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004479 if (!ITy || ITy->getBitWidth() % 16 ||
4480 // ByteMask only allows up to 32-byte values.
4481 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004482 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4483
4484 /// ByteValues - For each byte of the result, we keep track of which value
4485 /// defines each byte.
4486 SmallVector<Value*, 8> ByteValues;
4487 ByteValues.resize(ITy->getBitWidth()/8);
4488
4489 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004490 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4491 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004492 return 0;
4493
4494 // Check to see if all of the bytes come from the same value.
4495 Value *V = ByteValues[0];
4496 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4497
4498 // Check to make sure that all of the bytes come from the same value.
4499 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4500 if (ByteValues[i] != V)
4501 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004502 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004503 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004504 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004505 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004506}
4507
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004508/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4509/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4510/// we can simplify this expression to "cond ? C : D or B".
4511static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004512 Value *C, Value *D,
4513 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004514 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004515 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004516 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004517 return 0;
4518
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004519 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004520 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004521 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004522 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004523 return SelectInst::Create(Cond, C, B);
4524 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004525 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004526 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004527 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004528 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004529 return 0;
4530}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004531
Chris Lattner0c678e52008-11-16 05:20:07 +00004532/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4533Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4534 ICmpInst *LHS, ICmpInst *RHS) {
4535 Value *Val, *Val2;
4536 ConstantInt *LHSCst, *RHSCst;
4537 ICmpInst::Predicate LHSCC, RHSCC;
4538
4539 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004540 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004541 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004542 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004543 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004544 return 0;
4545
4546 // From here on, we only handle:
4547 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4548 if (Val != Val2) return 0;
4549
4550 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4551 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4552 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4553 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4554 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4555 return 0;
4556
4557 // We can't fold (ugt x, C) | (sgt x, C2).
4558 if (!PredicatesFoldable(LHSCC, RHSCC))
4559 return 0;
4560
4561 // Ensure that the larger constant is on the RHS.
4562 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004563 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004564 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004565 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004566 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4567 else
4568 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4569
4570 if (ShouldSwap) {
4571 std::swap(LHS, RHS);
4572 std::swap(LHSCst, RHSCst);
4573 std::swap(LHSCC, RHSCC);
4574 }
4575
4576 // At this point, we know we have have two icmp instructions
4577 // comparing a value against two constants and or'ing the result
4578 // together. Because of the above check, we know that we only have
4579 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4580 // FoldICmpLogical check above), that the two constants are not
4581 // equal.
4582 assert(LHSCst != RHSCst && "Compares not folded above?");
4583
4584 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004585 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004586 case ICmpInst::ICMP_EQ:
4587 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004588 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004589 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004590 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004591 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004592 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004593 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004594 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004595 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004596 }
4597 break; // (X == 13 | X == 15) -> no change
4598 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4599 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4600 break;
4601 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4602 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4603 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4604 return ReplaceInstUsesWith(I, RHS);
4605 }
4606 break;
4607 case ICmpInst::ICMP_NE:
4608 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004609 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4611 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4612 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4613 return ReplaceInstUsesWith(I, LHS);
4614 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4615 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4616 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004617 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004618 }
4619 break;
4620 case ICmpInst::ICMP_ULT:
4621 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004622 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004623 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4624 break;
4625 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4626 // If RHSCst is [us]MAXINT, it is always false. Not handling
4627 // this can cause overflow.
4628 if (RHSCst->isMaxValue(false))
4629 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004630 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004631 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004632 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4633 break;
4634 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4635 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4636 return ReplaceInstUsesWith(I, RHS);
4637 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4638 break;
4639 }
4640 break;
4641 case ICmpInst::ICMP_SLT:
4642 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004643 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004644 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4645 break;
4646 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4647 // If RHSCst is [us]MAXINT, it is always false. Not handling
4648 // this can cause overflow.
4649 if (RHSCst->isMaxValue(true))
4650 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004651 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004652 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004653 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4654 break;
4655 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4656 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4657 return ReplaceInstUsesWith(I, RHS);
4658 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4659 break;
4660 }
4661 break;
4662 case ICmpInst::ICMP_UGT:
4663 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004664 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004665 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4666 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4667 return ReplaceInstUsesWith(I, LHS);
4668 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4669 break;
4670 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4671 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004672 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004673 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4674 break;
4675 }
4676 break;
4677 case ICmpInst::ICMP_SGT:
4678 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004679 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004680 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4681 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4682 return ReplaceInstUsesWith(I, LHS);
4683 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4684 break;
4685 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4686 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004687 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004688 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4689 break;
4690 }
4691 break;
4692 }
4693 return 0;
4694}
4695
Chris Lattner57e66fa2009-07-23 05:46:22 +00004696Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4697 FCmpInst *RHS) {
4698 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4699 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4700 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4701 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4702 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4703 // If either of the constants are nans, then the whole thing returns
4704 // true.
4705 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004707
4708 // Otherwise, no need to compare the two constants, compare the
4709 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004710 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004711 LHS->getOperand(0), RHS->getOperand(0));
4712 }
4713
4714 // Handle vector zeros. This occurs because the canonical form of
4715 // "fcmp uno x,x" is "fcmp uno x, 0".
4716 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4717 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004718 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004719 LHS->getOperand(0), RHS->getOperand(0));
4720
4721 return 0;
4722 }
4723
4724 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4725 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4726 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4727
4728 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4729 // Swap RHS operands to match LHS.
4730 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4731 std::swap(Op1LHS, Op1RHS);
4732 }
4733 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4734 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4735 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004736 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004737 Op0LHS, Op0RHS);
4738 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004739 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004740 if (Op0CC == FCmpInst::FCMP_FALSE)
4741 return ReplaceInstUsesWith(I, RHS);
4742 if (Op1CC == FCmpInst::FCMP_FALSE)
4743 return ReplaceInstUsesWith(I, LHS);
4744 bool Op0Ordered;
4745 bool Op1Ordered;
4746 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4747 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4748 if (Op0Ordered == Op1Ordered) {
4749 // If both are ordered or unordered, return a new fcmp with
4750 // or'ed predicates.
4751 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4752 Op0LHS, Op0RHS, Context);
4753 if (Instruction *I = dyn_cast<Instruction>(RV))
4754 return I;
4755 // Otherwise, it's a constant boolean value...
4756 return ReplaceInstUsesWith(I, RV);
4757 }
4758 }
4759 return 0;
4760}
4761
Bill Wendlingdae376a2008-12-01 08:23:25 +00004762/// FoldOrWithConstants - This helper function folds:
4763///
Bill Wendling236a1192008-12-02 05:09:00 +00004764/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004765///
4766/// into:
4767///
Bill Wendling236a1192008-12-02 05:09:00 +00004768/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004769///
Bill Wendling236a1192008-12-02 05:09:00 +00004770/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004771Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004772 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004773 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4774 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004775
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004776 Value *V1 = 0;
4777 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004778 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004779
Bill Wendling86ee3162008-12-02 06:18:11 +00004780 APInt Xor = CI1->getValue() ^ CI2->getValue();
4781 if (!Xor.isAllOnesValue()) return 0;
4782
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004783 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004784 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004785 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004786 }
4787
4788 return 0;
4789}
4790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4792 bool Changed = SimplifyCommutative(I);
4793 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4794
4795 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004796 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004797
4798 // or X, X = X
4799 if (Op0 == Op1)
4800 return ReplaceInstUsesWith(I, Op0);
4801
4802 // See if we can simplify any instructions used by the instruction whose sole
4803 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004804 if (SimplifyDemandedInstructionBits(I))
4805 return &I;
4806 if (isa<VectorType>(I.getType())) {
4807 if (isa<ConstantAggregateZero>(Op1)) {
4808 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4809 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4810 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4811 return ReplaceInstUsesWith(I, I.getOperand(1));
4812 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004813 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004814
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004815 // or X, -1 == -1
4816 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4817 ConstantInt *C1 = 0; Value *X = 0;
4818 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004819 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004820 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004821 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004822 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004823 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004824 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004825 }
4826
4827 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004828 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004829 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004830 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004831 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004832 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004833 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834 }
4835
4836 // Try to fold constant and into select arguments.
4837 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4838 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4839 return R;
4840 if (isa<PHINode>(Op0))
4841 if (Instruction *NV = FoldOpIntoPhi(I))
4842 return NV;
4843 }
4844
4845 Value *A = 0, *B = 0;
4846 ConstantInt *C1 = 0, *C2 = 0;
4847
Dan Gohmancdff2122009-08-12 16:23:25 +00004848 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004849 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4850 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004851 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004852 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4853 return ReplaceInstUsesWith(I, Op0);
4854
4855 // (A | B) | C and A | (B | C) -> bswap if possible.
4856 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004857 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4858 match(Op1, m_Or(m_Value(), m_Value())) ||
4859 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4860 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004861 if (Instruction *BSwap = MatchBSwap(I))
4862 return BSwap;
4863 }
4864
4865 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004866 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004867 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004868 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004869 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004870 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004871 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004872 }
4873
4874 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004875 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004876 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004877 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004878 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004879 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004880 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004881 }
4882
4883 // (A & C)|(B & D)
4884 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004885 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4886 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004887 Value *V1 = 0, *V2 = 0, *V3 = 0;
4888 C1 = dyn_cast<ConstantInt>(C);
4889 C2 = dyn_cast<ConstantInt>(D);
4890 if (C1 && C2) { // (A & C1)|(B & C2)
4891 // If we have: ((V + N) & C1) | (V & C2)
4892 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4893 // replace with V+N.
4894 if (C1->getValue() == ~C2->getValue()) {
4895 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004896 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004897 // Add commutes, try both ways.
4898 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4899 return ReplaceInstUsesWith(I, A);
4900 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4901 return ReplaceInstUsesWith(I, A);
4902 }
4903 // Or commutes, try both ways.
4904 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004905 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004906 // Add commutes, try both ways.
4907 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4908 return ReplaceInstUsesWith(I, B);
4909 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4910 return ReplaceInstUsesWith(I, B);
4911 }
4912 }
4913 V1 = 0; V2 = 0; V3 = 0;
4914 }
4915
4916 // Check to see if we have any common things being and'ed. If so, find the
4917 // terms for V1 & (V2|V3).
4918 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4919 if (A == B) // (A & C)|(A & D) == A & (C|D)
4920 V1 = A, V2 = C, V3 = D;
4921 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4922 V1 = A, V2 = B, V3 = C;
4923 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4924 V1 = C, V2 = A, V3 = D;
4925 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4926 V1 = C, V2 = A, V3 = B;
4927
4928 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004929 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00004930 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004931 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004932 }
Dan Gohman279952c2008-10-28 22:38:57 +00004933
Dan Gohman35b76162008-10-30 20:40:10 +00004934 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004935 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004936 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004937 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004938 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004939 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004940 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004941 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004942 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004943
Bill Wendling22ca8352008-11-30 13:52:49 +00004944 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004945 if ((match(C, m_Not(m_Specific(D))) &&
4946 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004947 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004948 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004949 if ((match(A, m_Not(m_Specific(D))) &&
4950 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004951 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004952 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004953 if ((match(C, m_Not(m_Specific(B))) &&
4954 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004955 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004956 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004957 if ((match(A, m_Not(m_Specific(B))) &&
4958 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004959 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004960 }
4961
4962 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4963 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4964 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4965 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4966 SI0->getOperand(1) == SI1->getOperand(1) &&
4967 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004968 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4969 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004970 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004971 SI1->getOperand(1));
4972 }
4973 }
4974
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004975 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004976 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4977 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004978 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004979 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004980 }
4981 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004982 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4983 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004984 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004985 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004986 }
4987
Dan Gohmancdff2122009-08-12 16:23:25 +00004988 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004989 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004990 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004991 } else {
4992 A = 0;
4993 }
4994 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004995 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004997 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998
4999 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5000 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005001 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00005002 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005003 }
5004 }
5005
5006 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5007 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005008 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009 return R;
5010
Chris Lattner0c678e52008-11-16 05:20:07 +00005011 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5012 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5013 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005014 }
5015
5016 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005018 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5019 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005020 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5021 !isa<ICmpInst>(Op1C->getOperand(0))) {
5022 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005023 if (SrcTy == Op1C->getOperand(0)->getType() &&
5024 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005025 // Only do this if the casts both really cause code to be
5026 // generated.
5027 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5028 I.getType(), TD) &&
5029 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5030 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005031 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5032 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005033 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005034 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035 }
5036 }
Chris Lattner91882432007-10-24 05:38:08 +00005037 }
5038
5039
5040 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5041 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005042 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5043 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5044 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005045 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005046
5047 return Changed ? &I : 0;
5048}
5049
Dan Gohman089efff2008-05-13 00:00:25 +00005050namespace {
5051
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005052// XorSelf - Implements: X ^ X --> 0
5053struct XorSelf {
5054 Value *RHS;
5055 XorSelf(Value *rhs) : RHS(rhs) {}
5056 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5057 Instruction *apply(BinaryOperator &Xor) const {
5058 return &Xor;
5059 }
5060};
5061
Dan Gohman089efff2008-05-13 00:00:25 +00005062}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005063
5064Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5065 bool Changed = SimplifyCommutative(I);
5066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5067
Evan Chenge5cd8032008-03-25 20:07:13 +00005068 if (isa<UndefValue>(Op1)) {
5069 if (isa<UndefValue>(Op0))
5070 // Handle undef ^ undef -> 0 special case. This is a common
5071 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005073 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005074 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005075
5076 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005077 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005078 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005079 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005080 }
5081
5082 // See if we can simplify any instructions used by the instruction whose sole
5083 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005084 if (SimplifyDemandedInstructionBits(I))
5085 return &I;
5086 if (isa<VectorType>(I.getType()))
5087 if (isa<ConstantAggregateZero>(Op1))
5088 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005089
5090 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005091 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5093 if (Op0I->getOpcode() == Instruction::And ||
5094 Op0I->getOpcode() == Instruction::Or) {
Chris Lattnerf05d95c2009-10-26 01:06:31 +00005095 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5096 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5097 if (dyn_castNotVal(Op0I->getOperand(1)))
5098 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005099 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005100 Value *NotY =
5101 Builder->CreateNot(Op0I->getOperand(1),
5102 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005103 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005105 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005106 }
Chris Lattnerf05d95c2009-10-26 01:06:31 +00005107
5108 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5109 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5110 if (isFreeToInvert(Op0I->getOperand(0)) &&
5111 isFreeToInvert(Op0I->getOperand(1))) {
5112 Value *NotX =
5113 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5114 Value *NotY =
5115 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5116 if (Op0I->getOpcode() == Instruction::And)
5117 return BinaryOperator::CreateOr(NotX, NotY);
5118 return BinaryOperator::CreateAnd(NotX, NotY);
5119 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120 }
5121 }
5122 }
5123
5124
5125 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005126 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005127 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005128 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005129 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005130 ICI->getOperand(0), ICI->getOperand(1));
5131
Nick Lewycky1405e922007-08-06 20:04:16 +00005132 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005133 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005134 FCI->getOperand(0), FCI->getOperand(1));
5135 }
5136
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005137 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5138 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5139 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5140 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5141 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005142 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5143 (RHS == ConstantExpr::getCast(Opcode,
5144 ConstantInt::getTrue(*Context),
5145 Op0C->getDestTy()))) {
5146 CI->setPredicate(CI->getInversePredicate());
5147 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005148 }
5149 }
5150 }
5151 }
5152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5154 // ~(c-X) == X-c-1 == X+(-c-1)
5155 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5156 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005157 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5158 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005159 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005160 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005161 }
5162
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005163 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005164 if (Op0I->getOpcode() == Instruction::Add) {
5165 // ~(X-c) --> (-c-1)-X
5166 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005167 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005168 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005169 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005170 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005171 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005172 } else if (RHS->getValue().isSignBit()) {
5173 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005174 Constant *C = ConstantInt::get(*Context,
5175 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005176 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005177
5178 }
5179 } else if (Op0I->getOpcode() == Instruction::Or) {
5180 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5181 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005182 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005183 // Anything in both C1 and C2 is known to be zero, remove it from
5184 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005185 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5186 NewRHS = ConstantExpr::getAnd(NewRHS,
5187 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005188 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005189 I.setOperand(0, Op0I->getOperand(0));
5190 I.setOperand(1, NewRHS);
5191 return &I;
5192 }
5193 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005194 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005195 }
5196
5197 // Try to fold constant and into select arguments.
5198 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5200 return R;
5201 if (isa<PHINode>(Op0))
5202 if (Instruction *NV = FoldOpIntoPhi(I))
5203 return NV;
5204 }
5205
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005206 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005207 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005208 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005210 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005211 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005212 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005213
5214
5215 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5216 if (Op1I) {
5217 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005218 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005219 if (A == Op0) { // B^(B|A) == (A|B)^B
5220 Op1I->swapOperands();
5221 I.swapOperands();
5222 std::swap(Op0, Op1);
5223 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5224 I.swapOperands(); // Simplified below.
5225 std::swap(Op0, Op1);
5226 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005227 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005228 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005229 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005230 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005231 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005232 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005233 if (A == Op0) { // A^(A&B) -> A^(B&A)
5234 Op1I->swapOperands();
5235 std::swap(A, B);
5236 }
5237 if (B == Op0) { // A^(B&A) -> (B&A)^A
5238 I.swapOperands(); // Simplified below.
5239 std::swap(Op0, Op1);
5240 }
5241 }
5242 }
5243
5244 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5245 if (Op0I) {
5246 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005247 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005248 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005249 if (A == Op1) // (B|A)^B == (A|B)^B
5250 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005251 if (B == Op1) // (A|B)^B == A & ~B
5252 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005253 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005254 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005255 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005256 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005257 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005258 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005259 if (A == Op1) // (A&B)^A -> (B&A)^A
5260 std::swap(A, B);
5261 if (B == Op1 && // (B&A)^A == ~B & A
5262 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005263 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005264 }
5265 }
5266 }
5267
5268 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5269 if (Op0I && Op1I && Op0I->isShift() &&
5270 Op0I->getOpcode() == Op1I->getOpcode() &&
5271 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5272 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005273 Value *NewOp =
5274 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5275 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005276 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005277 Op1I->getOperand(1));
5278 }
5279
5280 if (Op0I && Op1I) {
5281 Value *A, *B, *C, *D;
5282 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005283 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5284 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005285 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005286 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287 }
5288 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005289 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5290 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005291 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005292 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005293 }
5294
5295 // (A & B)^(C & D)
5296 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005297 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5298 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005299 // (X & Y)^(X & Y) -> (Y^Z) & X
5300 Value *X = 0, *Y = 0, *Z = 0;
5301 if (A == C)
5302 X = A, Y = B, Z = D;
5303 else if (A == D)
5304 X = A, Y = B, Z = C;
5305 else if (B == C)
5306 X = B, Y = A, Z = D;
5307 else if (B == D)
5308 X = B, Y = A, Z = C;
5309
5310 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005311 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005312 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005313 }
5314 }
5315 }
5316
5317 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5318 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005319 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005320 return R;
5321
5322 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005323 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005324 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5325 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5326 const Type *SrcTy = Op0C->getOperand(0)->getType();
5327 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5328 // Only do this if the casts both really cause code to be generated.
5329 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5330 I.getType(), TD) &&
5331 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5332 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005333 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5334 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005335 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005336 }
5337 }
Chris Lattner91882432007-10-24 05:38:08 +00005338 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005339
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005340 return Changed ? &I : 0;
5341}
5342
Owen Anderson24be4c12009-07-03 00:17:18 +00005343static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005344 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005345 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005346}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005347
Dan Gohman8fd520a2009-06-15 22:12:54 +00005348static bool HasAddOverflow(ConstantInt *Result,
5349 ConstantInt *In1, ConstantInt *In2,
5350 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005351 if (IsSigned)
5352 if (In2->getValue().isNegative())
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().slt(In1->getValue());
5356 else
5357 return Result->getValue().ult(In1->getValue());
5358}
5359
Dan Gohman8fd520a2009-06-15 22:12:54 +00005360/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005361/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005362static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005363 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005364 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005365 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005366
Dan Gohman8fd520a2009-06-15 22:12:54 +00005367 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5368 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005369 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005370 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5371 ExtractElement(In1, Idx, Context),
5372 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005373 IsSigned))
5374 return true;
5375 }
5376 return false;
5377 }
5378
5379 return HasAddOverflow(cast<ConstantInt>(Result),
5380 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5381 IsSigned);
5382}
5383
5384static bool HasSubOverflow(ConstantInt *Result,
5385 ConstantInt *In1, ConstantInt *In2,
5386 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005387 if (IsSigned)
5388 if (In2->getValue().isNegative())
5389 return Result->getValue().slt(In1->getValue());
5390 else
5391 return Result->getValue().sgt(In1->getValue());
5392 else
5393 return Result->getValue().ugt(In1->getValue());
5394}
5395
Dan Gohman8fd520a2009-06-15 22:12:54 +00005396/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5397/// overflowed for this type.
5398static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005399 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005400 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005401 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005402
5403 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5404 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005405 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005406 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5407 ExtractElement(In1, Idx, Context),
5408 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005409 IsSigned))
5410 return true;
5411 }
5412 return false;
5413 }
5414
5415 return HasSubOverflow(cast<ConstantInt>(Result),
5416 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5417 IsSigned);
5418}
5419
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005420/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5421/// code necessary to compute the offset from the base pointer (without adding
5422/// in the base pointer). Return the result as a signed integer of intptr size.
5423static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005424 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005425 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson35b47072009-08-13 21:58:54 +00005426 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersonaac28372009-07-31 20:28:14 +00005427 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005428
5429 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005430 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5432
Gabor Greif17396002008-06-12 21:37:33 +00005433 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5434 ++i, ++GTI) {
5435 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005436 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005437 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5438 if (OpC->isZero()) continue;
5439
5440 // Handle a struct index, which adds its field offset to the pointer.
5441 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5442 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5443
Chris Lattnerc7694852009-08-30 07:44:24 +00005444 Result = IC.Builder->CreateAdd(Result,
5445 ConstantInt::get(IntPtrTy, Size),
5446 GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005447 continue;
5448 }
5449
Owen Andersoneacb44d2009-07-24 23:12:02 +00005450 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005451 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005452 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5453 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnerc7694852009-08-30 07:44:24 +00005454 // Emit an add instruction.
5455 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005456 continue;
5457 }
5458 // Convert to correct type.
Chris Lattnerc7694852009-08-30 07:44:24 +00005459 if (Op->getType() != IntPtrTy)
5460 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005461 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005462 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnerc7694852009-08-30 07:44:24 +00005463 // We'll let instcombine(mul) convert this to a shl if possible.
5464 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005465 }
5466
5467 // Emit an add instruction.
Chris Lattnerc7694852009-08-30 07:44:24 +00005468 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005469 }
5470 return Result;
5471}
5472
Chris Lattnereba75862008-04-22 02:53:33 +00005473
Dan Gohmanff9b4732009-07-17 22:16:21 +00005474/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5475/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5476/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5477/// be complex, and scales are involved. The above expression would also be
5478/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5479/// This later form is less amenable to optimization though, and we are allowed
5480/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005481///
5482/// If we can't emit an optimized form for this expression, this returns null.
5483///
5484static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5485 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005486 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005487 gep_type_iterator GTI = gep_type_begin(GEP);
5488
5489 // Check to see if this gep only has a single variable index. If so, and if
5490 // any constant indices are a multiple of its scale, then we can compute this
5491 // in terms of the scale of the variable index. For example, if the GEP
5492 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5493 // because the expression will cross zero at the same point.
5494 unsigned i, e = GEP->getNumOperands();
5495 int64_t Offset = 0;
5496 for (i = 1; i != e; ++i, ++GTI) {
5497 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5498 // Compute the aggregate offset of constant indices.
5499 if (CI->isZero()) continue;
5500
5501 // Handle a struct index, which adds its field offset to the pointer.
5502 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5503 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5504 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005505 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005506 Offset += Size*CI->getSExtValue();
5507 }
5508 } else {
5509 // Found our variable index.
5510 break;
5511 }
5512 }
5513
5514 // If there are no variable indices, we must have a constant offset, just
5515 // evaluate it the general way.
5516 if (i == e) return 0;
5517
5518 Value *VariableIdx = GEP->getOperand(i);
5519 // Determine the scale factor of the variable element. For example, this is
5520 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005521 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005522
5523 // Verify that there are no other variable indices. If so, emit the hard way.
5524 for (++i, ++GTI; i != e; ++i, ++GTI) {
5525 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5526 if (!CI) return 0;
5527
5528 // Compute the aggregate offset of constant indices.
5529 if (CI->isZero()) continue;
5530
5531 // Handle a struct index, which adds its field offset to the pointer.
5532 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5533 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5534 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005535 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005536 Offset += Size*CI->getSExtValue();
5537 }
5538 }
5539
5540 // Okay, we know we have a single variable index, which must be a
5541 // pointer/array/vector index. If there is no offset, life is simple, return
5542 // the index.
5543 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5544 if (Offset == 0) {
5545 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5546 // we don't need to bother extending: the extension won't affect where the
5547 // computation crosses zero.
5548 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson35b47072009-08-13 21:58:54 +00005549 VariableIdx = new TruncInst(VariableIdx,
5550 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005551 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005552 return VariableIdx;
5553 }
5554
5555 // Otherwise, there is an index. The computation we will do will be modulo
5556 // the pointer size, so get it.
5557 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5558
5559 Offset &= PtrSizeMask;
5560 VariableScale &= PtrSizeMask;
5561
5562 // To do this transformation, any constant index must be a multiple of the
5563 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5564 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5565 // multiple of the variable scale.
5566 int64_t NewOffs = Offset / (int64_t)VariableScale;
5567 if (Offset != NewOffs*(int64_t)VariableScale)
5568 return 0;
5569
5570 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson35b47072009-08-13 21:58:54 +00005571 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattnereba75862008-04-22 02:53:33 +00005572 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005573 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005574 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005575 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005576 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005577 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005578}
5579
5580
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005581/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5582/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005583Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005584 ICmpInst::Predicate Cond,
5585 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005586 // Look through bitcasts.
5587 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5588 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005589
5590 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005591 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005592 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005593 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005594 // know pointers can't overflow since the gep is inbounds. See if we can
5595 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005596 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5597
5598 // If not, synthesize the offset the hard way.
5599 if (Offset == 0)
5600 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005601 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005602 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005603 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005604 // If the base pointers are different, but the indices are the same, just
5605 // compare the base pointer.
5606 if (PtrBase != GEPRHS->getOperand(0)) {
5607 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5608 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5609 GEPRHS->getOperand(0)->getType();
5610 if (IndicesTheSame)
5611 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5612 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5613 IndicesTheSame = false;
5614 break;
5615 }
5616
5617 // If all indices are the same, just compare the base pointers.
5618 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005619 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005620 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5621
5622 // Otherwise, the base pointers are different and the indices are
5623 // different, bail out.
5624 return 0;
5625 }
5626
5627 // If one of the GEPs has all zero indices, recurse.
5628 bool AllZeros = true;
5629 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5630 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5631 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5632 AllZeros = false;
5633 break;
5634 }
5635 if (AllZeros)
5636 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5637 ICmpInst::getSwappedPredicate(Cond), I);
5638
5639 // If the other GEP has all zero indices, recurse.
5640 AllZeros = true;
5641 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5642 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5643 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5644 AllZeros = false;
5645 break;
5646 }
5647 if (AllZeros)
5648 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5649
5650 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5651 // If the GEPs only differ by one index, compare it.
5652 unsigned NumDifferences = 0; // Keep track of # differences.
5653 unsigned DiffOperand = 0; // The operand that differs.
5654 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5655 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5656 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5657 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5658 // Irreconcilable differences.
5659 NumDifferences = 2;
5660 break;
5661 } else {
5662 if (NumDifferences++) break;
5663 DiffOperand = i;
5664 }
5665 }
5666
5667 if (NumDifferences == 0) // SAME GEP?
5668 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005669 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005670 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005672 else if (NumDifferences == 1) {
5673 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5674 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5675 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005676 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005677 }
5678 }
5679
5680 // Only lower this if the icmp is the only user of the GEP or if we expect
5681 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005682 if (TD &&
5683 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005684 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5685 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5686 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5687 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005688 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005689 }
5690 }
5691 return 0;
5692}
5693
Chris Lattnere6b62d92008-05-19 20:18:56 +00005694/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5695///
5696Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5697 Instruction *LHSI,
5698 Constant *RHSC) {
5699 if (!isa<ConstantFP>(RHSC)) return 0;
5700 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5701
5702 // Get the width of the mantissa. We don't want to hack on conversions that
5703 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005704 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005705 if (MantissaWidth == -1) return 0; // Unknown.
5706
5707 // Check to see that the input is converted from an integer type that is small
5708 // enough that preserves all bits. TODO: check here for "known" sign bits.
5709 // 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 +00005710 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005711
5712 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005713 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5714 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005715 ++InputSize;
5716
5717 // If the conversion would lose info, don't hack on this.
5718 if ((int)InputSize > MantissaWidth)
5719 return 0;
5720
5721 // Otherwise, we can potentially simplify the comparison. We know that it
5722 // will always come through as an integer value and we know the constant is
5723 // not a NAN (it would have been previously simplified).
5724 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5725
5726 ICmpInst::Predicate Pred;
5727 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005728 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005729 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005730 case FCmpInst::FCMP_OEQ:
5731 Pred = ICmpInst::ICMP_EQ;
5732 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005733 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005734 case FCmpInst::FCMP_OGT:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5736 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005737 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005738 case FCmpInst::FCMP_OGE:
5739 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5740 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005741 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005742 case FCmpInst::FCMP_OLT:
5743 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5744 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005745 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005746 case FCmpInst::FCMP_OLE:
5747 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5748 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005749 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005750 case FCmpInst::FCMP_ONE:
5751 Pred = ICmpInst::ICMP_NE;
5752 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005753 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005755 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005757 }
5758
5759 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5760
5761 // Now we know that the APFloat is a normal number, zero or inf.
5762
Chris Lattnerf13ff492008-05-20 03:50:52 +00005763 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005764 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005765 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005766
Bill Wendling20636df2008-11-09 04:26:50 +00005767 if (!LHSUnsigned) {
5768 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5769 // and large values.
5770 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5771 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5772 APFloat::rmNearestTiesToEven);
5773 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5774 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5775 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5777 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005778 }
5779 } else {
5780 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5781 // +INF and large values.
5782 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5783 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5784 APFloat::rmNearestTiesToEven);
5785 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5786 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5787 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005788 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005790 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005791 }
5792
Bill Wendling20636df2008-11-09 04:26:50 +00005793 if (!LHSUnsigned) {
5794 // See if the RHS value is < SignedMin.
5795 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5796 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5797 APFloat::rmNearestTiesToEven);
5798 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5799 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5800 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005801 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005803 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005804 }
5805
Bill Wendling20636df2008-11-09 04:26:50 +00005806 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5807 // [0, UMAX], but it may still be fractional. See if it is fractional by
5808 // casting the FP value to the integer value and back, checking for equality.
5809 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005810 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005811 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5812 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005813 if (!RHS.isZero()) {
5814 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005815 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5816 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005817 if (!Equal) {
5818 // If we had a comparison against a fractional value, we have to adjust
5819 // the compare predicate and sometimes the value. RHSC is rounded towards
5820 // zero at this point.
5821 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005822 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005823 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005825 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005827 case ICmpInst::ICMP_ULE:
5828 // (float)int <= 4.4 --> int <= 4
5829 // (float)int <= -4.4 --> false
5830 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005831 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005832 break;
5833 case ICmpInst::ICMP_SLE:
5834 // (float)int <= 4.4 --> int <= 4
5835 // (float)int <= -4.4 --> int < -4
5836 if (RHS.isNegative())
5837 Pred = ICmpInst::ICMP_SLT;
5838 break;
5839 case ICmpInst::ICMP_ULT:
5840 // (float)int < -4.4 --> false
5841 // (float)int < 4.4 --> int <= 4
5842 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005843 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005844 Pred = ICmpInst::ICMP_ULE;
5845 break;
5846 case ICmpInst::ICMP_SLT:
5847 // (float)int < -4.4 --> int < -4
5848 // (float)int < 4.4 --> int <= 4
5849 if (!RHS.isNegative())
5850 Pred = ICmpInst::ICMP_SLE;
5851 break;
5852 case ICmpInst::ICMP_UGT:
5853 // (float)int > 4.4 --> int > 4
5854 // (float)int > -4.4 --> true
5855 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005856 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005857 break;
5858 case ICmpInst::ICMP_SGT:
5859 // (float)int > 4.4 --> int > 4
5860 // (float)int > -4.4 --> int >= -4
5861 if (RHS.isNegative())
5862 Pred = ICmpInst::ICMP_SGE;
5863 break;
5864 case ICmpInst::ICMP_UGE:
5865 // (float)int >= -4.4 --> true
5866 // (float)int >= 4.4 --> int > 4
5867 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005869 Pred = ICmpInst::ICMP_UGT;
5870 break;
5871 case ICmpInst::ICMP_SGE:
5872 // (float)int >= -4.4 --> int >= -4
5873 // (float)int >= 4.4 --> int > 4
5874 if (!RHS.isNegative())
5875 Pred = ICmpInst::ICMP_SGT;
5876 break;
5877 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005878 }
5879 }
5880
5881 // Lower this FP comparison into an appropriate integer version of the
5882 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005883 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005884}
5885
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005886Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5887 bool Changed = SimplifyCompare(I);
5888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5889
5890 // Fold trivial predicates.
5891 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner41c09932009-09-02 05:12:37 +00005892 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005893 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner41c09932009-09-02 05:12:37 +00005894 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005895
5896 // Simplify 'fcmp pred X, X'
5897 if (Op0 == Op1) {
5898 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005899 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005900 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5901 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5902 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner41c09932009-09-02 05:12:37 +00005903 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005904 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5905 case FCmpInst::FCMP_OLT: // True if ordered and less than
5906 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner41c09932009-09-02 05:12:37 +00005907 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005908
5909 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5910 case FCmpInst::FCMP_ULT: // True if unordered or less than
5911 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5912 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5913 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5914 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005915 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005916 return &I;
5917
5918 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5919 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5920 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5921 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5922 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5923 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005924 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005925 return &I;
5926 }
5927 }
5928
5929 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005930 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005931
5932 // Handle fcmp with constant RHS
5933 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005934 // If the constant is a nan, see if we can fold the comparison based on it.
5935 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5936 if (CFP->getValueAPF().isNaN()) {
5937 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005938 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005939 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5940 "Comparison must be either ordered or unordered!");
5941 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005942 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005943 }
5944 }
5945
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947 switch (LHSI->getOpcode()) {
5948 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005949 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5950 // block. If in the same block, we're encouraging jump threading. If
5951 // not, we are just pessimizing the code by making an i1 phi.
5952 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00005953 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00005954 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005955 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005956 case Instruction::SIToFP:
5957 case Instruction::UIToFP:
5958 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5959 return NV;
5960 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005961 case Instruction::Select:
5962 // If either operand of the select is a constant, we can fold the
5963 // comparison into the select arms, which will cause one to be
5964 // constant folded and the select turned into a bitwise or.
5965 Value *Op1 = 0, *Op2 = 0;
5966 if (LHSI->hasOneUse()) {
5967 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5968 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005969 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005970 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005971 Op2 = Builder->CreateFCmp(I.getPredicate(),
5972 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005973 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5974 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005975 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005976 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005977 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5978 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005979 }
5980 }
5981
5982 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005983 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005984 break;
5985 }
5986 }
5987
5988 return Changed ? &I : 0;
5989}
5990
5991Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5992 bool Changed = SimplifyCompare(I);
5993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5994 const Type *Ty = Op0->getType();
5995
5996 // icmp X, X
5997 if (Op0 == Op1)
Chris Lattner41c09932009-09-02 05:12:37 +00005998 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005999 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006000
6001 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00006002 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lambf78cd322007-12-18 21:32:20 +00006003
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006004 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6005 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattner95ac4eb2009-10-05 02:47:47 +00006006 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006007 isa<ConstantPointerNull>(Op0)) &&
Chris Lattner95ac4eb2009-10-05 02:47:47 +00006008 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006009 isa<ConstantPointerNull>(Op1)))
Owen Anderson35b47072009-08-13 21:58:54 +00006010 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00006011 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006012
6013 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006014 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006015 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006016 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006018 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006019 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006020 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006022 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006023
6024 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006025 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006026 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006027 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006028 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006029 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006030 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006031 case ICmpInst::ICMP_SGT:
6032 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006033 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006034 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006035 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006036 return BinaryOperator::CreateAnd(Not, Op0);
6037 }
6038 case ICmpInst::ICMP_UGE:
6039 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6040 // FALL THROUGH
6041 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006042 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006043 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006044 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006045 case ICmpInst::ICMP_SGE:
6046 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6047 // FALL THROUGH
6048 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006049 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006050 return BinaryOperator::CreateOr(Not, Op0);
6051 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006052 }
6053 }
6054
Dan Gohman7934d592009-04-25 17:12:48 +00006055 unsigned BitWidth = 0;
6056 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006057 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058 else if (Ty->isIntOrIntVector())
6059 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006060
6061 bool isSignBit = false;
6062
Dan Gohman58c09632008-09-16 18:46:06 +00006063 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006065 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006066
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006067 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006069 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006070 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006071 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006072 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006073
Dan Gohman58c09632008-09-16 18:46:06 +00006074 // If we have an icmp le or icmp ge instruction, turn it into the
6075 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6076 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006077 switch (I.getPredicate()) {
6078 default: break;
6079 case ICmpInst::ICMP_ULE:
6080 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006081 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006082 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006083 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006084 case ICmpInst::ICMP_SLE:
6085 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006086 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006087 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006088 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006089 case ICmpInst::ICMP_UGE:
6090 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006092 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006093 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006094 case ICmpInst::ICMP_SGE:
6095 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006097 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006098 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006099 }
6100
Chris Lattnera1308652008-07-11 05:40:05 +00006101 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006102 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006103 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006104 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105 }
6106
6107 // See if we can fold the comparison based on range information we can get
6108 // by checking whether bits are known to be zero or one in the input.
6109 if (BitWidth != 0) {
6110 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006114 isSignBit ? APInt::getSignBit(BitWidth)
6115 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006116 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006118 if (SimplifyDemandedBits(I.getOperandUse(1),
6119 APInt::getAllOnesValue(BitWidth),
6120 Op1KnownZero, Op1KnownOne, 0))
6121 return &I;
6122
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006123 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006124 // in. Compute the Min, Max and RHS values based on the known bits. For the
6125 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006126 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006128 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006129 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130 Op0Min, Op0Max);
6131 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132 Op1Min, Op1Max);
6133 } else {
6134 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135 Op0Min, Op0Max);
6136 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137 Op1Min, Op1Max);
6138 }
6139
Chris Lattnera1308652008-07-11 05:40:05 +00006140 // If Min and Max are known to be the same, then SimplifyDemandedBits
6141 // figured out that the LHS is a constant. Just constant fold this now so
6142 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006143 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006144 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006145 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006146 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006147 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006148 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006149
Chris Lattnera1308652008-07-11 05:40:05 +00006150 // Based on the range information we know about the LHS, see if we can
6151 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006152 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006153 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006154 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006156 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006161 break;
6162 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006163 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006164 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006165 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006166 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006168 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006171 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006172 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006173
6174 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6175 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006176 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006177 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006178 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006179 break;
6180 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006181 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006182 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006183 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006184 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006185
6186 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006187 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006191 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006192
6193 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6194 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006195 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006196 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006197 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006198 break;
6199 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006200 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006201 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006202 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006203 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006204 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006209 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006210 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006211 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006212 case ICmpInst::ICMP_SGT:
6213 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006215 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006216 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006217
6218 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006219 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006222 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006223 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006224 }
6225 break;
6226 case ICmpInst::ICMP_SGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006229 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006230 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006231 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_SLE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006236 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006237 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006238 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006239 break;
6240 case ICmpInst::ICMP_UGE:
6241 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006243 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006244 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006245 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006246 break;
6247 case ICmpInst::ICMP_ULE:
6248 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006250 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006251 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006252 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006253 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006254 }
Dan Gohman7934d592009-04-25 17:12:48 +00006255
6256 // Turn a signed comparison into an unsigned one if both operands
6257 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006258 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006259 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006261 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006262 }
6263
6264 // Test if the ICmpInst instruction is used exclusively by a select as
6265 // part of a minimum or maximum operation. If so, refrain from doing
6266 // any other folding. This helps out other analyses which understand
6267 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268 // and CodeGen. And in this case, at least one of the comparison
6269 // operands has at least one user besides the compare (the select),
6270 // which would often largely negate the benefit of folding anyway.
6271 if (I.hasOneUse())
6272 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275 return 0;
6276
6277 // See if we are doing a comparison between a constant and an instruction that
6278 // can be folded into the comparison.
6279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006280 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6281 // instruction, see if that instruction also has constants so that the
6282 // instruction can be folded into the icmp
6283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6284 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285 return Res;
6286 }
6287
6288 // Handle icmp with constant (but not simple integer constant) RHS
6289 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291 switch (LHSI->getOpcode()) {
6292 case Instruction::GetElementPtr:
6293 if (RHSC->isNullValue()) {
6294 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6295 bool isAllZeros = true;
6296 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297 if (!isa<Constant>(LHSI->getOperand(i)) ||
6298 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299 isAllZeros = false;
6300 break;
6301 }
6302 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006303 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006304 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006305 }
6306 break;
6307
6308 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006309 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006310 // block. If in the same block, we're encouraging jump threading. If
6311 // not, we are just pessimizing the code by making an i1 phi.
6312 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006313 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006314 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006315 break;
6316 case Instruction::Select: {
6317 // If either operand of the select is a constant, we can fold the
6318 // comparison into the select arms, which will cause one to be
6319 // constant folded and the select turned into a bitwise or.
6320 Value *Op1 = 0, *Op2 = 0;
6321 if (LHSI->hasOneUse()) {
6322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006324 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006325 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006326 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6327 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006330 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006331 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006332 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6333 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006334 }
6335 }
6336
6337 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006338 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006339 break;
6340 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006341 case Instruction::Call:
6342 // If we have (malloc != null), and if the malloc has a single use, we
6343 // can assume it is successful and remove the malloc.
6344 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6345 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006346 // Need to explicitly erase malloc call here, instead of adding it to
6347 // Worklist, because it won't get DCE'd from the Worklist since
6348 // isInstructionTriviallyDead() returns false for function calls.
6349 // It is OK to replace LHSI/MallocCall with Undef because the
6350 // instruction that uses it will be erased via Worklist.
6351 if (extractMallocCall(LHSI)) {
6352 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6353 EraseInstFromFunction(*LHSI);
6354 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006355 ConstantInt::get(Type::getInt1Ty(*Context),
6356 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006357 }
6358 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6359 if (MallocCall->hasOneUse()) {
6360 MallocCall->replaceAllUsesWith(
6361 UndefValue::get(MallocCall->getType()));
6362 EraseInstFromFunction(*MallocCall);
6363 Worklist.Add(LHSI); // The malloc's bitcast use.
6364 return ReplaceInstUsesWith(I,
6365 ConstantInt::get(Type::getInt1Ty(*Context),
6366 !I.isTrueWhenEqual()));
6367 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006368 }
6369 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006370 }
6371 }
6372
6373 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006374 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006375 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6376 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006377 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006378 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6379 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6380 return NI;
6381
6382 // Test to see if the operands of the icmp are casted versions of other
6383 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6384 // now.
6385 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6386 if (isa<PointerType>(Op0->getType()) &&
6387 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6388 // We keep moving the cast from the left operand over to the right
6389 // operand, where it can often be eliminated completely.
6390 Op0 = CI->getOperand(0);
6391
6392 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6393 // so eliminate it as well.
6394 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6395 Op1 = CI2->getOperand(0);
6396
6397 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006398 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006399 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006400 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006401 } else {
6402 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006403 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006404 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006405 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006406 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006407 }
6408 }
6409
6410 if (isa<CastInst>(Op0)) {
6411 // Handle the special case of: icmp (cast bool to X), <cst>
6412 // This comes up when you have code like
6413 // int X = A < B;
6414 // if (X) ...
6415 // For generality, we handle any zero-extension of any operand comparison
6416 // with a constant or another cast from the same type.
6417 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6418 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6419 return R;
6420 }
6421
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006422 // See if it's the same type of instruction on the left and right.
6423 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6424 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006425 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006426 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006427 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006428 default: break;
6429 case Instruction::Add:
6430 case Instruction::Sub:
6431 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006432 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006433 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006434 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006435 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6436 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6437 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006438 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006439 ? I.getUnsignedPredicate()
6440 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006441 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006442 Op1I->getOperand(0));
6443 }
6444
6445 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006446 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006447 ? I.getUnsignedPredicate()
6448 : I.getSignedPredicate();
6449 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006450 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006451 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006452 }
6453 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006454 break;
6455 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006456 if (!I.isEquality())
6457 break;
6458
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006459 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6460 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6461 // Mask = -1 >> count-trailing-zeros(Cst).
6462 if (!CI->isZero() && !CI->isOne()) {
6463 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006464 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006465 APInt::getLowBitsSet(AP.getBitWidth(),
6466 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006467 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006468 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6469 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006470 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006471 }
6472 }
6473 break;
6474 }
6475 }
6476 }
6477 }
6478
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006479 // ~x < ~y --> y < x
6480 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006481 if (match(Op0, m_Not(m_Value(A))) &&
6482 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006483 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006484 }
6485
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006486 if (I.isEquality()) {
6487 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006488
6489 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006490 if (match(Op0, m_Neg(m_Value(A))) &&
6491 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006492 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006493
Dan Gohmancdff2122009-08-12 16:23:25 +00006494 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006495 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6496 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006497 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006498 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006499 }
6500
Dan Gohmancdff2122009-08-12 16:23:25 +00006501 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006502 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006503 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006504 if (match(B, m_ConstantInt(C1)) &&
6505 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006506 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006507 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006508 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6509 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006510 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511
6512 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006513 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6514 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6515 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6516 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006517 }
6518 }
6519
Dan Gohmancdff2122009-08-12 16:23:25 +00006520 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006521 (A == Op0 || B == Op0)) {
6522 // A == (A^B) -> B == 0
6523 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006524 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006525 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006526 }
Chris Lattner3b874082008-11-16 05:38:51 +00006527
6528 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006529 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006530 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006531 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006532
6533 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006534 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006535 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006536 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006537
6538 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6539 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006540 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6541 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006542 Value *X = 0, *Y = 0, *Z = 0;
6543
6544 if (A == C) {
6545 X = B; Y = D; Z = A;
6546 } else if (A == D) {
6547 X = B; Y = C; Z = A;
6548 } else if (B == C) {
6549 X = A; Y = D; Z = B;
6550 } else if (B == D) {
6551 X = A; Y = C; Z = B;
6552 }
6553
6554 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006555 Op1 = Builder->CreateXor(X, Y, "tmp");
6556 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006558 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006559 return &I;
6560 }
6561 }
6562 }
6563 return Changed ? &I : 0;
6564}
6565
6566
6567/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6568/// and CmpRHS are both known to be integer constants.
6569Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6570 ConstantInt *DivRHS) {
6571 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6572 const APInt &CmpRHSV = CmpRHS->getValue();
6573
6574 // FIXME: If the operand types don't match the type of the divide
6575 // then don't attempt this transform. The code below doesn't have the
6576 // logic to deal with a signed divide and an unsigned compare (and
6577 // vice versa). This is because (x /s C1) <s C2 produces different
6578 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6579 // (x /u C1) <u C2. Simply casting the operands and result won't
6580 // work. :( The if statement below tests that condition and bails
6581 // if it finds it.
6582 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006583 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006584 return 0;
6585 if (DivRHS->isZero())
6586 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006587 if (DivIsSigned && DivRHS->isAllOnesValue())
6588 return 0; // The overflow computation also screws up here
6589 if (DivRHS->isOne())
6590 return 0; // Not worth bothering, and eliminates some funny cases
6591 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006592
6593 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6594 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6595 // C2 (CI). By solving for X we can turn this into a range check
6596 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006597 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598
6599 // Determine if the product overflows by seeing if the product is
6600 // not equal to the divide. Make sure we do the same kind of divide
6601 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006602 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6603 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006604
6605 // Get the ICmp opcode
6606 ICmpInst::Predicate Pred = ICI.getPredicate();
6607
6608 // Figure out the interval that is being checked. For example, a comparison
6609 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6610 // Compute this interval based on the constants involved and the signedness of
6611 // the compare/divide. This computes a half-open interval, keeping track of
6612 // whether either value in the interval overflows. After analysis each
6613 // overflow variable is set to 0 if it's corresponding bound variable is valid
6614 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6615 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006616 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006617
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 if (!DivIsSigned) { // udiv
6619 // e.g. X/5 op 3 --> [15, 20)
6620 LoBound = Prod;
6621 HiOverflow = LoOverflow = ProdOV;
6622 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006623 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006624 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006625 if (CmpRHSV == 0) { // (X / pos) op 0
6626 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006627 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006629 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006630 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6631 HiOverflow = LoOverflow = ProdOV;
6632 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006633 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 } else { // (X / pos) op neg
6635 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006636 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006637 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6638 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006639 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006640 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006641 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006642 true) ? -1 : 0;
6643 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006644 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006645 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006646 if (CmpRHSV == 0) { // (X / neg) op 0
6647 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006648 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006649 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006650 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6651 HiOverflow = 1; // [INTMIN+1, overflow)
6652 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6653 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006654 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006655 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006656 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006657 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6658 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006659 LoOverflow = AddWithOverflow(LoBound, HiBound,
6660 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006661 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006662 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6663 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006664 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006665 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006666 }
6667
6668 // Dividing by a negative swaps the condition. LT <-> GT
6669 Pred = ICmpInst::getSwappedPredicate(Pred);
6670 }
6671
6672 Value *X = DivI->getOperand(0);
6673 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006674 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006675 case ICmpInst::ICMP_EQ:
6676 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006677 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006678 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006679 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006680 ICmpInst::ICMP_UGE, X, LoBound);
6681 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006682 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 ICmpInst::ICMP_ULT, X, HiBound);
6684 else
6685 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6686 case ICmpInst::ICMP_NE:
6687 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006688 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006689 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006690 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006691 ICmpInst::ICMP_ULT, X, LoBound);
6692 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006693 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006694 ICmpInst::ICMP_UGE, X, HiBound);
6695 else
6696 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6697 case ICmpInst::ICMP_ULT:
6698 case ICmpInst::ICMP_SLT:
6699 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006700 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006701 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006702 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006703 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006704 case ICmpInst::ICMP_UGT:
6705 case ICmpInst::ICMP_SGT:
6706 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006707 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006708 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006709 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006710 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006711 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006712 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006713 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006714 }
6715}
6716
6717
6718/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6719///
6720Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6721 Instruction *LHSI,
6722 ConstantInt *RHS) {
6723 const APInt &RHSV = RHS->getValue();
6724
6725 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006726 case Instruction::Trunc:
6727 if (ICI.isEquality() && LHSI->hasOneUse()) {
6728 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6729 // of the high bits truncated out of x are known.
6730 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6731 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6732 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6733 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6734 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6735
6736 // If all the high bits are known, we can do this xform.
6737 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6738 // Pull in the high bits from known-ones set.
6739 APInt NewRHS(RHS->getValue());
6740 NewRHS.zext(SrcBits);
6741 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006742 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006743 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006744 }
6745 }
6746 break;
6747
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006748 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6749 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6750 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6751 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006752 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6753 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006754 Value *CompareVal = LHSI->getOperand(0);
6755
6756 // If the sign bit of the XorCST is not set, there is no change to
6757 // the operation, just stop using the Xor.
6758 if (!XorCST->getValue().isNegative()) {
6759 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006760 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006761 return &ICI;
6762 }
6763
6764 // Was the old condition true if the operand is positive?
6765 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6766
6767 // If so, the new one isn't.
6768 isTrueIfPositive ^= true;
6769
6770 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006771 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006772 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006773 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006774 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006775 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006776 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006777
6778 if (LHSI->hasOneUse()) {
6779 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6780 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6781 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006782 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006783 ? ICI.getUnsignedPredicate()
6784 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006785 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006786 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006787 }
6788
6789 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006790 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006791 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006792 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006793 ? ICI.getUnsignedPredicate()
6794 : ICI.getSignedPredicate();
6795 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006796 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006797 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006798 }
6799 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006800 }
6801 break;
6802 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6803 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6804 LHSI->getOperand(0)->hasOneUse()) {
6805 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6806
6807 // If the LHS is an AND of a truncating cast, we can widen the
6808 // and/compare to be the input width without changing the value
6809 // produced, eliminating a cast.
6810 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6811 // We can do this transformation if either the AND constant does not
6812 // have its sign bit set or if it is an equality comparison.
6813 // Extending a relational comparison when we're checking the sign
6814 // bit would not work.
6815 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006816 (ICI.isEquality() ||
6817 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006818 uint32_t BitWidth =
6819 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6820 APInt NewCST = AndCST->getValue();
6821 NewCST.zext(BitWidth);
6822 APInt NewCI = RHSV;
6823 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006824 Value *NewAnd =
6825 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006826 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006827 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006828 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006829 }
6830 }
6831
6832 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6833 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6834 // happens a LOT in code produced by the C front-end, for bitfield
6835 // access.
6836 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6837 if (Shift && !Shift->isShift())
6838 Shift = 0;
6839
6840 ConstantInt *ShAmt;
6841 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6842 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6843 const Type *AndTy = AndCST->getType(); // Type of the and.
6844
6845 // We can fold this as long as we can't shift unknown bits
6846 // into the mask. This can only happen with signed shift
6847 // rights, as they sign-extend.
6848 if (ShAmt) {
6849 bool CanFold = Shift->isLogicalShift();
6850 if (!CanFold) {
6851 // To test for the bad case of the signed shr, see if any
6852 // of the bits shifted in could be tested after the mask.
6853 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6854 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6855
6856 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6857 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6858 AndCST->getValue()) == 0)
6859 CanFold = true;
6860 }
6861
6862 if (CanFold) {
6863 Constant *NewCst;
6864 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006865 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006866 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006867 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006868
6869 // Check to see if we are shifting out any of the bits being
6870 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006871 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006872 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006873 // If we shifted bits out, the fold is not going to work out.
6874 // As a special case, check to see if this means that the
6875 // result is always true or false now.
6876 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006877 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006878 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006879 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006880 } else {
6881 ICI.setOperand(1, NewCst);
6882 Constant *NewAndCST;
6883 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006884 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006886 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006887 LHSI->setOperand(1, NewAndCST);
6888 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006889 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006890 return &ICI;
6891 }
6892 }
6893 }
6894
6895 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6896 // preferable because it allows the C<<Y expression to be hoisted out
6897 // of a loop if Y is invariant and X is not.
6898 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006899 ICI.isEquality() && !Shift->isArithmeticShift() &&
6900 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006901 // Compute C << Y.
6902 Value *NS;
6903 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006904 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006905 } else {
6906 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006907 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006908 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006909
6910 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006911 Value *NewAnd =
6912 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006913
6914 ICI.setOperand(0, NewAnd);
6915 return &ICI;
6916 }
6917 }
6918 break;
6919
6920 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6921 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6922 if (!ShAmt) break;
6923
6924 uint32_t TypeBits = RHSV.getBitWidth();
6925
6926 // Check that the shift amount is in range. If not, don't perform
6927 // undefined shifts. When the shift is visited it will be
6928 // simplified.
6929 if (ShAmt->uge(TypeBits))
6930 break;
6931
6932 if (ICI.isEquality()) {
6933 // If we are comparing against bits always shifted out, the
6934 // comparison cannot succeed.
6935 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006936 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006937 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006938 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006940 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006941 return ReplaceInstUsesWith(ICI, Cst);
6942 }
6943
6944 if (LHSI->hasOneUse()) {
6945 // Otherwise strength reduce the shift into an and.
6946 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6947 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006948 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006949 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006950
Chris Lattnerc7694852009-08-30 07:44:24 +00006951 Value *And =
6952 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006953 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006954 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006955 }
6956 }
6957
6958 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6959 bool TrueIfSigned = false;
6960 if (LHSI->hasOneUse() &&
6961 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6962 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006963 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006964 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00006965 Value *And =
6966 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006967 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006968 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006969 }
6970 break;
6971 }
6972
6973 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6974 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006975 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006976 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006977 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006978
Chris Lattner5ee84f82008-03-21 05:19:58 +00006979 // Check that the shift amount is in range. If not, don't perform
6980 // undefined shifts. When the shift is visited it will be
6981 // simplified.
6982 uint32_t TypeBits = RHSV.getBitWidth();
6983 if (ShAmt->uge(TypeBits))
6984 break;
6985
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006987
Chris Lattner5ee84f82008-03-21 05:19:58 +00006988 // If we are comparing against bits always shifted out, the
6989 // comparison cannot succeed.
6990 APInt Comp = RHSV << ShAmtVal;
6991 if (LHSI->getOpcode() == Instruction::LShr)
6992 Comp = Comp.lshr(ShAmtVal);
6993 else
6994 Comp = Comp.ashr(ShAmtVal);
6995
6996 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006998 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006999 return ReplaceInstUsesWith(ICI, Cst);
7000 }
7001
7002 // Otherwise, check to see if the bits shifted out are known to be zero.
7003 // If so, we can compare against the unshifted value:
7004 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007005 if (LHSI->hasOneUse() &&
7006 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007007 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007008 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007009 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007010 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007011
Evan Chengfb9292a2008-04-23 00:38:06 +00007012 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007013 // Otherwise strength reduce the shift into an and.
7014 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007015 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007016
Chris Lattnerc7694852009-08-30 07:44:24 +00007017 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7018 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007019 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007020 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007021 }
7022 break;
7023 }
7024
7025 case Instruction::SDiv:
7026 case Instruction::UDiv:
7027 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7028 // Fold this div into the comparison, producing a range check.
7029 // Determine, based on the divide type, what the range is being
7030 // checked. If there is an overflow on the low or high side, remember
7031 // it, otherwise compute the range [low, hi) bounding the new value.
7032 // See: InsertRangeTest above for the kinds of replacements possible.
7033 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7034 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7035 DivRHS))
7036 return R;
7037 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007038
7039 case Instruction::Add:
7040 // Fold: icmp pred (add, X, C1), C2
7041
7042 if (!ICI.isEquality()) {
7043 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7044 if (!LHSC) break;
7045 const APInt &LHSV = LHSC->getValue();
7046
7047 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7048 .subtract(LHSV);
7049
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007050 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007051 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007052 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007053 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007054 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007055 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007056 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007057 }
7058 } else {
7059 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007060 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007061 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007062 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007063 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007064 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007065 }
7066 }
7067 }
7068 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007069 }
7070
7071 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7072 if (ICI.isEquality()) {
7073 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7074
7075 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7076 // the second operand is a constant, simplify a bit.
7077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7078 switch (BO->getOpcode()) {
7079 case Instruction::SRem:
7080 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7081 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7082 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7083 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007084 Value *NewRem =
7085 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7086 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007087 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007088 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007089 }
7090 }
7091 break;
7092 case Instruction::Add:
7093 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7094 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7095 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007096 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007097 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007098 } else if (RHSV == 0) {
7099 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7100 // efficiently invertible, or if the add has just this one use.
7101 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7102
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007103 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007104 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007105 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007106 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007107 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007108 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007109 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007110 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111 }
7112 }
7113 break;
7114 case Instruction::Xor:
7115 // For the xor case, we can xor two constants together, eliminating
7116 // the explicit xor.
7117 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007118 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007119 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007120
7121 // FALLTHROUGH
7122 case Instruction::Sub:
7123 // Replace (([sub|xor] A, B) != 0) with (A != B)
7124 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007125 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007126 BO->getOperand(1));
7127 break;
7128
7129 case Instruction::Or:
7130 // If bits are being or'd in that are not present in the constant we
7131 // are comparing against, then the comparison could never succeed!
7132 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007133 Constant *NotCI = ConstantExpr::getNot(RHS);
7134 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007135 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007136 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007137 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138 }
7139 break;
7140
7141 case Instruction::And:
7142 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143 // If bits are being compared against that are and'd out, then the
7144 // comparison can never succeed!
7145 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007146 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007147 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007148 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149
7150 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007152 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007153 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007154 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007155
7156 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007157 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007159 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007162 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007163 }
7164
7165 // ((X & ~7) == 0) --> X < 8
7166 if (RHSV == 0 && isHighOnes(BOC)) {
7167 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007168 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007171 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007172 }
7173 }
7174 default: break;
7175 }
7176 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177 // Handle icmp {eq|ne} <intrinsic>, intcst.
7178 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007179 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007180 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007181 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007182 return &ICI;
7183 }
7184 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007185 }
7186 return 0;
7187}
7188
7189/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190/// We only handle extending casts so far.
7191///
7192Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7194 Value *LHSCIOp = LHSCI->getOperand(0);
7195 const Type *SrcTy = LHSCIOp->getType();
7196 const Type *DestTy = LHSCI->getType();
7197 Value *RHSCIOp;
7198
7199 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7200 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007201 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007203 cast<IntegerType>(DestTy)->getBitWidth()) {
7204 Value *RHSOp = 0;
7205 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007206 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007207 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208 RHSOp = RHSC->getOperand(0);
7209 // If the pointer types don't match, insert a bitcast.
7210 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007211 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007212 }
7213
7214 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007215 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007216 }
7217
7218 // The code below only handles extension cast instructions, so far.
7219 // Enforce this.
7220 if (LHSCI->getOpcode() != Instruction::ZExt &&
7221 LHSCI->getOpcode() != Instruction::SExt)
7222 return 0;
7223
7224 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007225 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007226
7227 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7228 // Not an extension from the same type?
7229 RHSCIOp = CI->getOperand(0);
7230 if (RHSCIOp->getType() != LHSCIOp->getType())
7231 return 0;
7232
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007233 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007234 // and the other is a zext), then we can't handle this.
7235 if (CI->getOpcode() != LHSCI->getOpcode())
7236 return 0;
7237
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007238 // Deal with equality cases early.
7239 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007240 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007241
7242 // A signed comparison of sign extended values simplifies into a
7243 // signed comparison.
7244 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007245 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007246
7247 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007248 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007249 }
7250
7251 // If we aren't dealing with a constant on the RHS, exit early
7252 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253 if (!CI)
7254 return 0;
7255
7256 // Compute the constant that would happen if we truncated to SrcTy then
7257 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007258 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7259 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007260 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007261
7262 // If the re-extended constant didn't change...
7263 if (Res2 == CI) {
7264 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007266 // %A = sext i16 %X to i32
7267 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007269 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007270 // because %A may have negative value.
7271 //
Chris Lattner3d816532008-07-11 04:09:09 +00007272 // However, we allow this when the compare is EQ/NE, because they are
7273 // signless.
7274 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007275 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007276 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277 }
7278
7279 // The re-extended constant changed so the constant cannot be represented
7280 // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282 // First, handle some easy cases. We know the result cannot be equal at this
7283 // point so handle the ICI.isEquality() cases
7284 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007285 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007286 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007287 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007288
7289 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290 // should have been folded away previously and not enter in here.
7291 Value *Result;
7292 if (isSignedCmp) {
7293 // We're performing a signed comparison.
7294 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007295 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007296 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007297 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 } else {
7299 // We're performing an unsigned comparison.
7300 if (isSignedExt) {
7301 // We're performing an unsigned comp with a sign extended value.
7302 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007303 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007304 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007305 } else {
7306 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007307 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007308 }
7309 }
7310
7311 // Finally, return the value computed.
7312 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007313 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007314 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007315
7316 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7317 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7318 "ICmp should be folded!");
7319 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007320 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007321 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007322}
7323
7324Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7325 return commonShiftTransforms(I);
7326}
7327
7328Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7329 return commonShiftTransforms(I);
7330}
7331
7332Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007333 if (Instruction *R = commonShiftTransforms(I))
7334 return R;
7335
7336 Value *Op0 = I.getOperand(0);
7337
7338 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7339 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7340 if (CSI->isAllOnesValue())
7341 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007342
Dan Gohman2526aea2009-06-16 19:55:29 +00007343 // See if we can turn a signed shr into an unsigned shr.
7344 if (MaskedValueIsZero(Op0,
7345 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7346 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7347
7348 // Arithmetic shifting an all-sign-bit value is a no-op.
7349 unsigned NumSignBits = ComputeNumSignBits(Op0);
7350 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7351 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007352
Chris Lattnere3c504f2007-12-06 01:59:46 +00007353 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007354}
7355
7356Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7357 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7359
7360 // shl X, 0 == X and shr X, 0 == X
7361 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007362 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7363 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007364 return ReplaceInstUsesWith(I, Op0);
7365
7366 if (isa<UndefValue>(Op0)) {
7367 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7368 return ReplaceInstUsesWith(I, Op0);
7369 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007371 }
7372 if (isa<UndefValue>(Op1)) {
7373 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7374 return ReplaceInstUsesWith(I, Op0);
7375 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007377 }
7378
Dan Gohman2bc21562009-05-21 02:28:33 +00007379 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007380 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007381 return &I;
7382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383 // Try to fold constant and into select arguments.
7384 if (isa<Constant>(Op0))
7385 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7386 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7387 return R;
7388
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007389 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7390 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7391 return Res;
7392 return 0;
7393}
7394
7395Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7396 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007397 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007398
7399 // See if we can simplify any instructions used by the instruction whose sole
7400 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007401 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007402
Dan Gohman9e1657f2009-06-14 23:30:43 +00007403 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7404 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007405 //
7406 if (Op1->uge(TypeBits)) {
7407 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007408 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007409 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007410 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007411 return &I;
7412 }
7413 }
7414
7415 // ((X*C1) << C2) == (X * (C1 << C2))
7416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7417 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7418 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007419 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007420 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007421
7422 // Try to fold constant and into select arguments.
7423 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7424 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7425 return R;
7426 if (isa<PHINode>(Op0))
7427 if (Instruction *NV = FoldOpIntoPhi(I))
7428 return NV;
7429
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007430 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7431 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7432 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7433 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7434 // place. Don't try to do this transformation in this case. Also, we
7435 // require that the input operand is a shift-by-constant so that we have
7436 // confidence that the shifts will get folded together. We could do this
7437 // xform in more cases, but it is unlikely to be profitable.
7438 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7439 isa<ConstantInt>(TrOp->getOperand(1))) {
7440 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007441 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007442 // (shift2 (shift1 & 0x00FF), c2)
7443 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007444
7445 // For logical shifts, the truncation has the effect of making the high
7446 // part of the register be zeros. Emulate this by inserting an AND to
7447 // clear the top bits as needed. This 'and' will usually be zapped by
7448 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007449 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7450 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007451 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7452
7453 // The mask we constructed says what the trunc would do if occurring
7454 // between the shifts. We want to know the effect *after* the second
7455 // shift. We know that it is a logical shift by a constant, so adjust the
7456 // mask as appropriate.
7457 if (I.getOpcode() == Instruction::Shl)
7458 MaskV <<= Op1->getZExtValue();
7459 else {
7460 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7461 MaskV = MaskV.lshr(Op1->getZExtValue());
7462 }
7463
Chris Lattnerc7694852009-08-30 07:44:24 +00007464 // shift1 & 0x00FF
7465 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7466 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007467
7468 // Return the value truncated to the interesting size.
7469 return new TruncInst(And, I.getType());
7470 }
7471 }
7472
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007473 if (Op0->hasOneUse()) {
7474 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7475 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7476 Value *V1, *V2;
7477 ConstantInt *CC;
7478 switch (Op0BO->getOpcode()) {
7479 default: break;
7480 case Instruction::Add:
7481 case Instruction::And:
7482 case Instruction::Or:
7483 case Instruction::Xor: {
7484 // These operators commute.
7485 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7486 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007487 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007488 m_Specific(Op1)))) {
7489 Value *YS = // (Y << C)
7490 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7491 // (X + (Y << C))
7492 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7493 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007494 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007495 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007496 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7497 }
7498
7499 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7500 Value *Op0BOOp1 = Op0BO->getOperand(1);
7501 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7502 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007503 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007504 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007505 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007506 Value *YS = // (Y << C)
7507 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7508 Op0BO->getName());
7509 // X & (CC << C)
7510 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7511 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007512 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007513 }
7514 }
7515
7516 // FALL THROUGH.
7517 case Instruction::Sub: {
7518 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7519 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007520 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007521 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007522 Value *YS = // (Y << C)
7523 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7524 // (X + (Y << C))
7525 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7526 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007527 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007528 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007529 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7530 }
7531
7532 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7534 match(Op0BO->getOperand(0),
7535 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007536 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007537 cast<BinaryOperator>(Op0BO->getOperand(0))
7538 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007539 Value *YS = // (Y << C)
7540 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7541 // X & (CC << C)
7542 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7543 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007544
Gabor Greifa645dd32008-05-16 19:29:10 +00007545 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007546 }
7547
7548 break;
7549 }
7550 }
7551
7552
7553 // If the operand is an bitwise operator with a constant RHS, and the
7554 // shift is the only use, we can pull it out of the shift.
7555 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7556 bool isValid = true; // Valid only for And, Or, Xor
7557 bool highBitSet = false; // Transform if high bit of constant set?
7558
7559 switch (Op0BO->getOpcode()) {
7560 default: isValid = false; break; // Do not perform transform!
7561 case Instruction::Add:
7562 isValid = isLeftShift;
7563 break;
7564 case Instruction::Or:
7565 case Instruction::Xor:
7566 highBitSet = false;
7567 break;
7568 case Instruction::And:
7569 highBitSet = true;
7570 break;
7571 }
7572
7573 // If this is a signed shift right, and the high bit is modified
7574 // by the logical operation, do not perform the transformation.
7575 // The highBitSet boolean indicates the value of the high bit of
7576 // the constant which would cause it to be modified for this
7577 // operation.
7578 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007579 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007580 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007581
7582 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007583 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007584
Chris Lattnerad7516a2009-08-30 18:50:58 +00007585 Value *NewShift =
7586 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007587 NewShift->takeName(Op0BO);
7588
Gabor Greifa645dd32008-05-16 19:29:10 +00007589 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007590 NewRHS);
7591 }
7592 }
7593 }
7594 }
7595
7596 // Find out if this is a shift of a shift by a constant.
7597 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7598 if (ShiftOp && !ShiftOp->isShift())
7599 ShiftOp = 0;
7600
7601 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7602 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7603 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7604 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7605 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7606 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7607 Value *X = ShiftOp->getOperand(0);
7608
7609 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007610
7611 const IntegerType *Ty = cast<IntegerType>(I.getType());
7612
7613 // Check for (X << c1) << c2 and (X >> c1) >> c2
7614 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007615 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7616 // saturates.
7617 if (AmtSum >= TypeBits) {
7618 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007619 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007620 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7621 }
7622
Gabor Greifa645dd32008-05-16 19:29:10 +00007623 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007624 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007625 }
7626
7627 if (ShiftOp->getOpcode() == Instruction::LShr &&
7628 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007629 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007630 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007631
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007632 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007633 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007634 }
7635
7636 if (ShiftOp->getOpcode() == Instruction::AShr &&
7637 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007638 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007639 if (AmtSum >= TypeBits)
7640 AmtSum = TypeBits-1;
7641
Chris Lattnerad7516a2009-08-30 18:50:58 +00007642 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007643
7644 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007645 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007646 }
7647
7648 // Okay, if we get here, one shift must be left, and the other shift must be
7649 // right. See if the amounts are equal.
7650 if (ShiftAmt1 == ShiftAmt2) {
7651 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7652 if (I.getOpcode() == Instruction::Shl) {
7653 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007654 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 }
7656 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7657 if (I.getOpcode() == Instruction::LShr) {
7658 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007659 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007660 }
7661 // We can simplify ((X << C) >>s C) into a trunc + sext.
7662 // NOTE: we could do this for any C, but that would make 'unusual' integer
7663 // types. For now, just stick to ones well-supported by the code
7664 // generators.
7665 const Type *SExtType = 0;
7666 switch (Ty->getBitWidth() - ShiftAmt1) {
7667 case 1 :
7668 case 8 :
7669 case 16 :
7670 case 32 :
7671 case 64 :
7672 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007673 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007674 break;
7675 default: break;
7676 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007677 if (SExtType)
7678 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007679 // Otherwise, we can't handle it yet.
7680 } else if (ShiftAmt1 < ShiftAmt2) {
7681 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7682
7683 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7684 if (I.getOpcode() == Instruction::Shl) {
7685 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7686 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007687 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007688
7689 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007690 return BinaryOperator::CreateAnd(Shift,
7691 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007692 }
7693
7694 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7695 if (I.getOpcode() == Instruction::LShr) {
7696 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007697 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007698
7699 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007700 return BinaryOperator::CreateAnd(Shift,
7701 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007702 }
7703
7704 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7705 } else {
7706 assert(ShiftAmt2 < ShiftAmt1);
7707 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7708
7709 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7710 if (I.getOpcode() == Instruction::Shl) {
7711 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7712 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007713 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7714 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007715
7716 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007717 return BinaryOperator::CreateAnd(Shift,
7718 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719 }
7720
7721 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7722 if (I.getOpcode() == Instruction::LShr) {
7723 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007724 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007725
7726 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007727 return BinaryOperator::CreateAnd(Shift,
7728 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007729 }
7730
7731 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7732 }
7733 }
7734 return 0;
7735}
7736
7737
7738/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7739/// expression. If so, decompose it, returning some value X, such that Val is
7740/// X*Scale+Offset.
7741///
7742static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007743 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007744 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7745 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007746 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7747 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007748 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007749 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007750 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7751 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7752 if (I->getOpcode() == Instruction::Shl) {
7753 // This is a value scaled by '1 << the shift amt'.
7754 Scale = 1U << RHS->getZExtValue();
7755 Offset = 0;
7756 return I->getOperand(0);
7757 } else if (I->getOpcode() == Instruction::Mul) {
7758 // This value is scaled by 'RHS'.
7759 Scale = RHS->getZExtValue();
7760 Offset = 0;
7761 return I->getOperand(0);
7762 } else if (I->getOpcode() == Instruction::Add) {
7763 // We have X+C. Check to see if we really have (X*C2)+C1,
7764 // where C1 is divisible by C2.
7765 unsigned SubScale;
7766 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007767 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7768 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007769 Offset += RHS->getZExtValue();
7770 Scale = SubScale;
7771 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007772 }
7773 }
7774 }
7775
7776 // Otherwise, we can't look past this.
7777 Scale = 1;
7778 Offset = 0;
7779 return Val;
7780}
7781
7782
7783/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7784/// try to eliminate the cast by moving the type information into the alloc.
7785Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00007786 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007787 const PointerType *PTy = cast<PointerType>(CI.getType());
7788
Chris Lattnerad7516a2009-08-30 18:50:58 +00007789 BuilderTy AllocaBuilder(*Builder);
7790 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7791
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007792 // Remove any uses of AI that are dead.
7793 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7794
7795 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7796 Instruction *User = cast<Instruction>(*UI++);
7797 if (isInstructionTriviallyDead(User)) {
7798 while (UI != E && *UI == User)
7799 ++UI; // If this instruction uses AI more than once, don't break UI.
7800
7801 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007802 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007803 EraseInstFromFunction(*User);
7804 }
7805 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007806
7807 // This requires TargetData to get the alloca alignment and size information.
7808 if (!TD) return 0;
7809
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007810 // Get the type really allocated and the type casted to.
7811 const Type *AllocElTy = AI.getAllocatedType();
7812 const Type *CastElTy = PTy->getElementType();
7813 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7814
7815 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7816 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7817 if (CastElTyAlign < AllocElTyAlign) return 0;
7818
7819 // If the allocation has multiple uses, only promote it if we are strictly
7820 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007821 // same, we open the door to infinite loops of various kinds. (A reference
7822 // from a dbg.declare doesn't count as a use for this purpose.)
7823 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7824 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007825
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007826 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7827 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007828 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7829
7830 // See if we can satisfy the modulus by pulling a scale out of the array
7831 // size argument.
7832 unsigned ArraySizeScale;
7833 int ArrayOffset;
7834 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007835 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7836 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007837
7838 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7839 // do the xform.
7840 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7841 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7842
7843 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7844 Value *Amt = 0;
7845 if (Scale == 1) {
7846 Amt = NumElements;
7847 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007848 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007849 // Insert before the alloca, not before the cast.
7850 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007851 }
7852
7853 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007854 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007855 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007856 }
7857
Victor Hernandezb1687302009-10-23 21:09:37 +00007858 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007859 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007860 New->takeName(&AI);
7861
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007862 // If the allocation has one real use plus a dbg.declare, just remove the
7863 // declare.
7864 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7865 EraseInstFromFunction(*DI);
7866 }
7867 // If the allocation has multiple real uses, insert a cast and change all
7868 // things that used it to use the new cast. This will also hack on CI, but it
7869 // will die soon.
7870 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007871 // New is the allocation instruction, pointer typed. AI is the original
7872 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007873 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007874 AI.replaceAllUsesWith(NewCast);
7875 }
7876 return ReplaceInstUsesWith(CI, New);
7877}
7878
7879/// CanEvaluateInDifferentType - Return true if we can take the specified value
7880/// and return it as type Ty without inserting any new casts and without
7881/// changing the computed value. This is used by code that tries to decide
7882/// whether promoting or shrinking integer operations to wider or smaller types
7883/// will allow us to eliminate a truncate or extend.
7884///
7885/// This is a truncation operation if Ty is smaller than V->getType(), or an
7886/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007887///
7888/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7889/// should return true if trunc(V) can be computed by computing V in the smaller
7890/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7891/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7892/// efficiently truncated.
7893///
7894/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7895/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7896/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007897bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007898 unsigned CastOpc,
7899 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007900 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007901 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902 return true;
7903
7904 Instruction *I = dyn_cast<Instruction>(V);
7905 if (!I) return false;
7906
Dan Gohman8fd520a2009-06-15 22:12:54 +00007907 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007908
Chris Lattneref70bb82007-08-02 06:11:14 +00007909 // If this is an extension or truncate, we can often eliminate it.
7910 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7911 // If this is a cast from the destination type, we can trivially eliminate
7912 // it, and this will remove a cast overall.
7913 if (I->getOperand(0)->getType() == Ty) {
7914 // If the first operand is itself a cast, and is eliminable, do not count
7915 // this as an eliminable cast. We would prefer to eliminate those two
7916 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007917 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007918 ++NumCastsRemoved;
7919 return true;
7920 }
7921 }
7922
7923 // We can't extend or shrink something that has multiple uses: doing so would
7924 // require duplicating the instruction in general, which isn't profitable.
7925 if (!I->hasOneUse()) return false;
7926
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007927 unsigned Opc = I->getOpcode();
7928 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007929 case Instruction::Add:
7930 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007931 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007932 case Instruction::And:
7933 case Instruction::Or:
7934 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007936 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007937 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007938 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007939 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007940
Eli Friedman08c45bc2009-07-13 22:46:01 +00007941 case Instruction::UDiv:
7942 case Instruction::URem: {
7943 // UDiv and URem can be truncated if all the truncated bits are zero.
7944 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945 uint32_t BitWidth = Ty->getScalarSizeInBits();
7946 if (BitWidth < OrigBitWidth) {
7947 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7948 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7949 MaskedValueIsZero(I->getOperand(1), Mask)) {
7950 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951 NumCastsRemoved) &&
7952 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7953 NumCastsRemoved);
7954 }
7955 }
7956 break;
7957 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007959 // If we are truncating the result of this SHL, and if it's a shift of a
7960 // constant amount, we can always perform a SHL in a smaller type.
7961 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007962 uint32_t BitWidth = Ty->getScalarSizeInBits();
7963 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007964 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007965 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007966 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007967 }
7968 break;
7969 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007970 // If this is a truncate of a logical shr, we can truncate it to a smaller
7971 // lshr iff we know that the bits we would otherwise be shifting in are
7972 // already zeros.
7973 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007974 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007976 if (BitWidth < OrigBitWidth &&
7977 MaskedValueIsZero(I->getOperand(0),
7978 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7979 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007981 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007982 }
7983 }
7984 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985 case Instruction::ZExt:
7986 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007987 case Instruction::Trunc:
7988 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007989 // can safely replace it. Note that replacing it does not reduce the number
7990 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007991 if (Opc == CastOpc)
7992 return true;
7993
7994 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007995 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007996 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007997 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007998 case Instruction::Select: {
7999 SelectInst *SI = cast<SelectInst>(I);
8000 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008001 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008002 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008003 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008004 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008005 case Instruction::PHI: {
8006 // We can change a phi if we can change all operands.
8007 PHINode *PN = cast<PHINode>(I);
8008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8009 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008010 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008011 return false;
8012 return true;
8013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008014 default:
8015 // TODO: Can handle more cases here.
8016 break;
8017 }
8018
8019 return false;
8020}
8021
8022/// EvaluateInDifferentType - Given an expression that
8023/// CanEvaluateInDifferentType returns true for, actually insert the code to
8024/// evaluate the expression.
8025Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8026 bool isSigned) {
8027 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00008028 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00008029 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008030
8031 // Otherwise, it must be an instruction.
8032 Instruction *I = cast<Instruction>(V);
8033 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008034 unsigned Opc = I->getOpcode();
8035 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008036 case Instruction::Add:
8037 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008038 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008039 case Instruction::And:
8040 case Instruction::Or:
8041 case Instruction::Xor:
8042 case Instruction::AShr:
8043 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008044 case Instruction::Shl:
8045 case Instruction::UDiv:
8046 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008047 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8048 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008049 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008050 break;
8051 }
8052 case Instruction::Trunc:
8053 case Instruction::ZExt:
8054 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008055 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008056 // just return the source. There's no need to insert it because it is not
8057 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008058 if (I->getOperand(0)->getType() == Ty)
8059 return I->getOperand(0);
8060
Chris Lattner4200c2062008-06-18 04:00:49 +00008061 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008062 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008063 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008064 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008065 case Instruction::Select: {
8066 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8067 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8068 Res = SelectInst::Create(I->getOperand(0), True, False);
8069 break;
8070 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008071 case Instruction::PHI: {
8072 PHINode *OPN = cast<PHINode>(I);
8073 PHINode *NPN = PHINode::Create(Ty);
8074 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8075 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8076 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8077 }
8078 Res = NPN;
8079 break;
8080 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008081 default:
8082 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008083 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008084 break;
8085 }
8086
Chris Lattner4200c2062008-06-18 04:00:49 +00008087 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008088 return InsertNewInstBefore(Res, *I);
8089}
8090
8091/// @brief Implement the transforms common to all CastInst visitors.
8092Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8093 Value *Src = CI.getOperand(0);
8094
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008095 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8096 // eliminate it now.
8097 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8098 if (Instruction::CastOps opc =
8099 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8100 // The first cast (CSrc) is eliminable so we need to fix up or replace
8101 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008102 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008103 }
8104 }
8105
8106 // If we are casting a select then fold the cast into the select
8107 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8108 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8109 return NV;
8110
8111 // If we are casting a PHI then fold the cast into the PHI
8112 if (isa<PHINode>(Src))
8113 if (Instruction *NV = FoldOpIntoPhi(CI))
8114 return NV;
8115
8116 return 0;
8117}
8118
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008119/// FindElementAtOffset - Given a type and a constant offset, determine whether
8120/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008121/// the specified offset. If so, fill them into NewIndices and return the
8122/// resultant element type, otherwise return null.
8123static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8124 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008125 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008126 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008127 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008128 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008129
8130 // Start with the index over the outer type. Note that the type size
8131 // might be zero (even if the offset isn't zero) if the indexed type
8132 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008133 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008134 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008135 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008136 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008137 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008138
Chris Lattnerce48c462009-01-11 20:15:20 +00008139 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008140 if (Offset < 0) {
8141 --FirstIdx;
8142 Offset += TySize;
8143 assert(Offset >= 0);
8144 }
8145 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146 }
8147
Owen Andersoneacb44d2009-07-24 23:12:02 +00008148 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008149
8150 // Index into the types. If we fail, set OrigBase to null.
8151 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008152 // Indexing into tail padding between struct/array elements.
8153 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008154 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008155
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008156 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008158 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159 "Offset must stay within the indexed type");
8160
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008161 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008162 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008163
8164 Offset -= SL->getElementOffset(Elt);
8165 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008166 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008167 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008168 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008169 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008170 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008171 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008172 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008173 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008174 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008175 }
8176 }
8177
Chris Lattner54dddc72009-01-24 01:00:13 +00008178 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008179}
8180
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008181/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183 Value *Src = CI.getOperand(0);
8184
8185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8186 // If casting the result of a getelementptr instruction with no offset, turn
8187 // this into a cast of the original pointer!
8188 if (GEP->hasAllZeroIndices()) {
8189 // Changing the cast operand is usually not a good idea but it is safe
8190 // here because the pointer operand is being replaced with another
8191 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008192 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008193 CI.setOperand(0, GEP->getOperand(0));
8194 return &CI;
8195 }
8196
8197 // If the GEP has a single use, and the base pointer is a bitcast, and the
8198 // GEP computes a constant offset, see if we can convert these three
8199 // instructions into fewer. This typically happens with unions and other
8200 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008201 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008202 if (GEP->hasAllConstantIndices()) {
8203 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008204 ConstantInt *OffsetV =
8205 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008206 int64_t Offset = OffsetV->getSExtValue();
8207
8208 // Get the base pointer input of the bitcast, and the type it points to.
8209 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210 const Type *GEPIdxTy =
8211 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008212 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008213 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008214 // If we were able to index down into an element, create the GEP
8215 // and bitcast the result. This eliminates one bitcast, potentially
8216 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008217 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8218 Builder->CreateInBoundsGEP(OrigBase,
8219 NewIndices.begin(), NewIndices.end()) :
8220 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008221 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008222
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008223 if (isa<BitCastInst>(CI))
8224 return new BitCastInst(NGEP, CI.getType());
8225 assert(isa<PtrToIntInst>(CI));
8226 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008227 }
8228 }
8229 }
8230 }
8231
8232 return commonCastTransforms(CI);
8233}
8234
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008235/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236/// type like i42. We don't want to introduce operations on random non-legal
8237/// integer types where they don't already exist in the code. In the future,
8238/// we should consider making this based off target-data, so that 32-bit targets
8239/// won't get i64 operations etc.
8240static bool isSafeIntegerType(const Type *Ty) {
8241 switch (Ty->getPrimitiveSizeInBits()) {
8242 case 8:
8243 case 16:
8244 case 32:
8245 case 64:
8246 return true;
8247 default:
8248 return false;
8249 }
8250}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251
Eli Friedman827e37a2009-07-13 20:58:59 +00008252/// commonIntCastTransforms - This function implements the common transforms
8253/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008254Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8255 if (Instruction *Result = commonCastTransforms(CI))
8256 return Result;
8257
8258 Value *Src = CI.getOperand(0);
8259 const Type *SrcTy = Src->getType();
8260 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008261 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8262 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008263
8264 // See if we can simplify any instructions used by the LHS whose sole
8265 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008266 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008267 return &CI;
8268
8269 // If the source isn't an instruction or has more than one use then we
8270 // can't do anything more.
8271 Instruction *SrcI = dyn_cast<Instruction>(Src);
8272 if (!SrcI || !Src->hasOneUse())
8273 return 0;
8274
8275 // Attempt to propagate the cast into the instruction for int->int casts.
8276 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008277 // Only do this if the dest type is a simple type, don't convert the
8278 // expression tree to something weird like i93 unless the source is also
8279 // strange.
8280 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008281 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8282 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008283 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008284 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008285 // eliminates the cast, so it is always a win. If this is a zero-extension,
8286 // we need to do an AND to maintain the clear top-part of the computation,
8287 // so we require that the input have eliminated at least one cast. If this
8288 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008289 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008290 bool DoXForm = false;
8291 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008292 switch (CI.getOpcode()) {
8293 default:
8294 // All the others use floating point so we shouldn't actually
8295 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008296 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008297 case Instruction::Trunc:
8298 DoXForm = true;
8299 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008300 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008301 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008302 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008303 // If it's unnecessary to issue an AND to clear the high bits, it's
8304 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008305 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008306 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8307 if (MaskedValueIsZero(TryRes, Mask))
8308 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008309
8310 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008311 if (TryI->use_empty())
8312 EraseInstFromFunction(*TryI);
8313 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008314 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008315 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008316 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008317 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008318 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008319 // If we do not have to emit the truncate + sext pair, then it's always
8320 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008321 //
8322 // It's not safe to eliminate the trunc + sext pair if one of the
8323 // eliminated cast is a truncate. e.g.
8324 // t2 = trunc i32 t1 to i16
8325 // t3 = sext i16 t2 to i32
8326 // !=
8327 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008328 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008329 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8330 if (NumSignBits > (DestBitSize - SrcBitSize))
8331 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008332
8333 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008334 if (TryI->use_empty())
8335 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008336 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008337 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008338 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008339 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008340
8341 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008342 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8343 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008344 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8345 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008346 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008347 // Just replace this cast with the result.
8348 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008349
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008350 assert(Res->getType() == DestTy);
8351 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008352 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008353 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008354 // Just replace this cast with the result.
8355 return ReplaceInstUsesWith(CI, Res);
8356 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008357 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008358
8359 // If the high bits are already zero, just replace this cast with the
8360 // result.
8361 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8362 if (MaskedValueIsZero(Res, Mask))
8363 return ReplaceInstUsesWith(CI, Res);
8364
8365 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008366 Constant *C = ConstantInt::get(*Context,
8367 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008368 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008369 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008370 case Instruction::SExt: {
8371 // If the high bits are already filled with sign bit, just replace this
8372 // cast with the result.
8373 unsigned NumSignBits = ComputeNumSignBits(Res);
8374 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008375 return ReplaceInstUsesWith(CI, Res);
8376
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008377 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008378 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008379 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008380 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008381 }
8382 }
8383
8384 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8385 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8386
8387 switch (SrcI->getOpcode()) {
8388 case Instruction::Add:
8389 case Instruction::Mul:
8390 case Instruction::And:
8391 case Instruction::Or:
8392 case Instruction::Xor:
8393 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008394 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8395 // Don't insert two casts unless at least one can be eliminated.
8396 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008397 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008398 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8399 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008400 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008401 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8402 }
8403 }
8404
8405 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8406 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8407 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008408 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008409 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008410 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008411 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008412 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 }
8414 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008415
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008416 case Instruction::Shl: {
8417 // Canonicalize trunc inside shl, if we can.
8418 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8419 if (CI && DestBitSize < SrcBitSize &&
8420 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008421 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8422 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008423 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008424 }
8425 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008427 }
8428 return 0;
8429}
8430
8431Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8432 if (Instruction *Result = commonIntCastTransforms(CI))
8433 return Result;
8434
8435 Value *Src = CI.getOperand(0);
8436 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008437 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8438 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008439
8440 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008441 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008442 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008443 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008444 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008445 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008446 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008447
Chris Lattner32177f82009-03-24 18:15:30 +00008448 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8449 ConstantInt *ShAmtV = 0;
8450 Value *ShiftOp = 0;
8451 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008452 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008453 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8454
8455 // Get a mask for the bits shifting in.
8456 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8457 if (MaskedValueIsZero(ShiftOp, Mask)) {
8458 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008459 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008460
8461 // Okay, we can shrink this. Truncate the input, then return a new
8462 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008463 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008464 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008465 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008466 }
8467 }
8468
8469 return 0;
8470}
8471
Evan Chenge3779cf2008-03-24 00:21:34 +00008472/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8473/// in order to eliminate the icmp.
8474Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8475 bool DoXform) {
8476 // If we are just checking for a icmp eq of a single bit and zext'ing it
8477 // to an integer, then shift the bit to the appropriate place and then
8478 // cast to integer to avoid the comparison.
8479 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8480 const APInt &Op1CV = Op1C->getValue();
8481
8482 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8483 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8484 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8485 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8486 if (!DoXform) return ICI;
8487
8488 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008489 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008490 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008491 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008492 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008493 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008494
8495 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008496 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008497 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008498 }
8499
8500 return ReplaceInstUsesWith(CI, In);
8501 }
8502
8503
8504
8505 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8506 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8507 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8508 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8509 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8510 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8511 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8512 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8513 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8514 // This only works for EQ and NE
8515 ICI->isEquality()) {
8516 // If Op1C some other power of two, convert:
8517 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8518 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8519 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8520 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8521
8522 APInt KnownZeroMask(~KnownZero);
8523 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8524 if (!DoXform) return ICI;
8525
8526 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8527 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8528 // (X&4) == 2 --> false
8529 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008530 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008531 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008532 return ReplaceInstUsesWith(CI, Res);
8533 }
8534
8535 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8536 Value *In = ICI->getOperand(0);
8537 if (ShiftAmt) {
8538 // Perform a logical shr by shiftamt.
8539 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008540 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8541 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008542 }
8543
8544 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008545 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008546 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008547 }
8548
8549 if (CI.getType() == In->getType())
8550 return ReplaceInstUsesWith(CI, In);
8551 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008552 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008553 }
8554 }
8555 }
8556
8557 return 0;
8558}
8559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008560Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8561 // If one of the common conversion will work ..
8562 if (Instruction *Result = commonIntCastTransforms(CI))
8563 return Result;
8564
8565 Value *Src = CI.getOperand(0);
8566
Chris Lattner215d56e2009-02-17 20:47:23 +00008567 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8568 // types and if the sizes are just right we can convert this into a logical
8569 // 'and' which will be much cheaper than the pair of casts.
8570 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8571 // Get the sizes of the types involved. We know that the intermediate type
8572 // will be smaller than A or C, but don't know the relation between A and C.
8573 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008574 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8575 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8576 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008577 // If we're actually extending zero bits, then if
8578 // SrcSize < DstSize: zext(a & mask)
8579 // SrcSize == DstSize: a & mask
8580 // SrcSize > DstSize: trunc(a) & mask
8581 if (SrcSize < DstSize) {
8582 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008583 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008584 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008585 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008586 }
8587
8588 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008589 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008590 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008591 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008592 }
8593 if (SrcSize > DstSize) {
8594 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008595 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008596 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008597 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008598 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008599 }
8600 }
8601
Evan Chenge3779cf2008-03-24 00:21:34 +00008602 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8603 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008604
Evan Chenge3779cf2008-03-24 00:21:34 +00008605 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8606 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8607 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8608 // of the (zext icmp) will be transformed.
8609 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8610 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8611 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8612 (transformZExtICmp(LHS, CI, false) ||
8613 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008614 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8615 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008616 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008617 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008618 }
8619
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008620 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008621 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8622 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8623 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8624 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008625 if (TI0->getType() == CI.getType())
8626 return
8627 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008628 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008629 }
8630
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008631 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8632 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8633 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8634 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8635 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8636 And->getOperand(1) == C)
8637 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8638 Value *TI0 = TI->getOperand(0);
8639 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008640 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008641 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008642 return BinaryOperator::CreateXor(NewAnd, ZC);
8643 }
8644 }
8645
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008646 return 0;
8647}
8648
8649Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8650 if (Instruction *I = commonIntCastTransforms(CI))
8651 return I;
8652
8653 Value *Src = CI.getOperand(0);
8654
Dan Gohman35b76162008-10-30 20:40:10 +00008655 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008656 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008657 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008658 Constant::getAllOnesValue(CI.getType()),
8659 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008660
8661 // See if the value being truncated is already sign extended. If so, just
8662 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008663 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008664 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008665 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8666 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8667 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008668 unsigned NumSignBits = ComputeNumSignBits(Op);
8669
8670 if (OpBits == DestBits) {
8671 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8672 // bits, it is already ready.
8673 if (NumSignBits > DestBits-MidBits)
8674 return ReplaceInstUsesWith(CI, Op);
8675 } else if (OpBits < DestBits) {
8676 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8677 // bits, just sext from i32.
8678 if (NumSignBits > OpBits-MidBits)
8679 return new SExtInst(Op, CI.getType(), "tmp");
8680 } else {
8681 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8682 // bits, just truncate to i32.
8683 if (NumSignBits > OpBits-MidBits)
8684 return new TruncInst(Op, CI.getType(), "tmp");
8685 }
8686 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008687
8688 // If the input is a shl/ashr pair of a same constant, then this is a sign
8689 // extension from a smaller value. If we could trust arbitrary bitwidth
8690 // integers, we could turn this into a truncate to the smaller bit and then
8691 // use a sext for the whole extension. Since we don't, look deeper and check
8692 // for a truncate. If the source and dest are the same type, eliminate the
8693 // trunc and extend and just do shifts. For example, turn:
8694 // %a = trunc i32 %i to i8
8695 // %b = shl i8 %a, 6
8696 // %c = ashr i8 %b, 6
8697 // %d = sext i8 %c to i32
8698 // into:
8699 // %a = shl i32 %i, 30
8700 // %d = ashr i32 %a, 30
8701 Value *A = 0;
8702 ConstantInt *BA = 0, *CA = 0;
8703 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008704 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008705 BA == CA && isa<TruncInst>(A)) {
8706 Value *I = cast<TruncInst>(A)->getOperand(0);
8707 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008708 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8709 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008710 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008711 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008712 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008713 return BinaryOperator::CreateAShr(I, ShAmtV);
8714 }
8715 }
8716
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008717 return 0;
8718}
8719
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008720/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8721/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008722static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008723 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008724 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008725 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008726 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8727 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008728 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008729 return 0;
8730}
8731
8732/// LookThroughFPExtensions - If this is an fp extension instruction, look
8733/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008734static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008735 if (Instruction *I = dyn_cast<Instruction>(V))
8736 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008737 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008738
8739 // If this value is a constant, return the constant in the smallest FP type
8740 // that can accurately represent it. This allows us to turn
8741 // (float)((double)X+2.0) into x+2.0f.
8742 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008743 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008744 return V; // No constant folding of this.
8745 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008746 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008747 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008748 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008749 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008750 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008751 return V;
8752 // Don't try to shrink to various long double types.
8753 }
8754
8755 return V;
8756}
8757
8758Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8759 if (Instruction *I = commonCastTransforms(CI))
8760 return I;
8761
Dan Gohman7ce405e2009-06-04 22:49:04 +00008762 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008763 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008764 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008765 // many builtins (sqrt, etc).
8766 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8767 if (OpI && OpI->hasOneUse()) {
8768 switch (OpI->getOpcode()) {
8769 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008770 case Instruction::FAdd:
8771 case Instruction::FSub:
8772 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008773 case Instruction::FDiv:
8774 case Instruction::FRem:
8775 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008776 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8777 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008778 if (LHSTrunc->getType() != SrcTy &&
8779 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008780 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008781 // If the source types were both smaller than the destination type of
8782 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008783 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8784 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008785 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8786 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008787 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008788 }
8789 }
8790 break;
8791 }
8792 }
8793 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008794}
8795
8796Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8797 return commonCastTransforms(CI);
8798}
8799
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008800Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008801 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8802 if (OpI == 0)
8803 return commonCastTransforms(FI);
8804
8805 // fptoui(uitofp(X)) --> X
8806 // fptoui(sitofp(X)) --> X
8807 // This is safe if the intermediate type has enough bits in its mantissa to
8808 // accurately represent all values of X. For example, do not do this with
8809 // i64->float->i64. This is also safe for sitofp case, because any negative
8810 // 'X' value would cause an undefined result for the fptoui.
8811 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8812 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008813 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008814 OpI->getType()->getFPMantissaWidth())
8815 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008816
8817 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008818}
8819
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008820Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008821 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8822 if (OpI == 0)
8823 return commonCastTransforms(FI);
8824
8825 // fptosi(sitofp(X)) --> X
8826 // fptosi(uitofp(X)) --> X
8827 // This is safe if the intermediate type has enough bits in its mantissa to
8828 // accurately represent all values of X. For example, do not do this with
8829 // i64->float->i64. This is also safe for sitofp case, because any negative
8830 // 'X' value would cause an undefined result for the fptoui.
8831 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8832 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008833 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008834 OpI->getType()->getFPMantissaWidth())
8835 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008836
8837 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008838}
8839
8840Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8841 return commonCastTransforms(CI);
8842}
8843
8844Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8845 return commonCastTransforms(CI);
8846}
8847
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008848Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8849 // If the destination integer type is smaller than the intptr_t type for
8850 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8851 // trunc to be exposed to other transforms. Don't do this for extending
8852 // ptrtoint's, because we don't know if the target sign or zero extends its
8853 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008854 if (TD &&
8855 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008856 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8857 TD->getIntPtrType(CI.getContext()),
8858 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008859 return new TruncInst(P, CI.getType());
8860 }
8861
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008862 return commonPointerCastTransforms(CI);
8863}
8864
Chris Lattner7c1626482008-01-08 07:23:51 +00008865Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008866 // If the source integer type is larger than the intptr_t type for
8867 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8868 // allows the trunc to be exposed to other transforms. Don't do this for
8869 // extending inttoptr's, because we don't know if the target sign or zero
8870 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008871 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008872 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008873 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8874 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008875 return new IntToPtrInst(P, CI.getType());
8876 }
8877
Chris Lattner7c1626482008-01-08 07:23:51 +00008878 if (Instruction *I = commonCastTransforms(CI))
8879 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008880
Chris Lattner7c1626482008-01-08 07:23:51 +00008881 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008882}
8883
8884Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8885 // If the operands are integer typed then apply the integer transforms,
8886 // otherwise just apply the common ones.
8887 Value *Src = CI.getOperand(0);
8888 const Type *SrcTy = Src->getType();
8889 const Type *DestTy = CI.getType();
8890
Eli Friedman5013d3f2009-07-13 20:53:00 +00008891 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008892 if (Instruction *I = commonPointerCastTransforms(CI))
8893 return I;
8894 } else {
8895 if (Instruction *Result = commonCastTransforms(CI))
8896 return Result;
8897 }
8898
8899
8900 // Get rid of casts from one type to the same type. These are useless and can
8901 // be replaced by the operand.
8902 if (DestTy == Src->getType())
8903 return ReplaceInstUsesWith(CI, Src);
8904
8905 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8906 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907 const Type *DstElTy = DstPTy->getElementType();
8908 const Type *SrcElTy = SrcPTy->getElementType();
8909
Nate Begemandf5b3612008-03-31 00:22:16 +00008910 // If the address spaces don't match, don't eliminate the bitcast, which is
8911 // required for changing types.
8912 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8913 return 0;
8914
Victor Hernandez48c3c542009-09-18 22:35:49 +00008915 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008916 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00008917 // There is no need to modify malloc calls because it is their bitcast that
8918 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00008919 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008920 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8921 return V;
8922
8923 // If the source and destination are pointers, and this cast is equivalent
8924 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8925 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008926 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008927 unsigned NumZeros = 0;
8928 while (SrcElTy != DstElTy &&
8929 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8930 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8931 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8932 ++NumZeros;
8933 }
8934
8935 // If we found a path from the src to dest, create the getelementptr now.
8936 if (SrcElTy == DstElTy) {
8937 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008938 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8939 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008940 }
8941 }
8942
Eli Friedman1d31dee2009-07-18 23:06:53 +00008943 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8944 if (DestVTy->getNumElements() == 1) {
8945 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008946 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008947 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00008948 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008949 }
8950 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8951 }
8952 }
8953
8954 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8955 if (SrcVTy->getNumElements() == 1) {
8956 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008957 Value *Elem =
8958 Builder->CreateExtractElement(Src,
8959 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008960 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8961 }
8962 }
8963 }
8964
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008965 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8966 if (SVI->hasOneUse()) {
8967 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8968 // a bitconvert to a vector with the same # elts.
8969 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008970 cast<VectorType>(DestTy)->getNumElements() ==
8971 SVI->getType()->getNumElements() &&
8972 SVI->getType()->getNumElements() ==
8973 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008974 CastInst *Tmp;
8975 // If either of the operands is a cast from CI.getType(), then
8976 // evaluating the shuffle in the casted destination's type will allow
8977 // us to eliminate at least one cast.
8978 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8979 Tmp->getOperand(0)->getType() == DestTy) ||
8980 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8981 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008982 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8983 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008984 // Return a new shuffle vector. Use the same element ID's, as we
8985 // know the vector types match #elts.
8986 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8987 }
8988 }
8989 }
8990 }
8991 return 0;
8992}
8993
8994/// GetSelectFoldableOperands - We want to turn code that looks like this:
8995/// %C = or %A, %B
8996/// %D = select %cond, %C, %A
8997/// into:
8998/// %C = select %cond, %B, 0
8999/// %D = or %A, %C
9000///
9001/// Assuming that the specified instruction is an operand to the select, return
9002/// a bitmask indicating which operands of this instruction are foldable if they
9003/// equal the other incoming value of the select.
9004///
9005static unsigned GetSelectFoldableOperands(Instruction *I) {
9006 switch (I->getOpcode()) {
9007 case Instruction::Add:
9008 case Instruction::Mul:
9009 case Instruction::And:
9010 case Instruction::Or:
9011 case Instruction::Xor:
9012 return 3; // Can fold through either operand.
9013 case Instruction::Sub: // Can only fold on the amount subtracted.
9014 case Instruction::Shl: // Can only fold on the shift amount.
9015 case Instruction::LShr:
9016 case Instruction::AShr:
9017 return 1;
9018 default:
9019 return 0; // Cannot fold
9020 }
9021}
9022
9023/// GetSelectFoldableConstant - For the same transformation as the previous
9024/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009025static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009026 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009027 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009028 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009029 case Instruction::Add:
9030 case Instruction::Sub:
9031 case Instruction::Or:
9032 case Instruction::Xor:
9033 case Instruction::Shl:
9034 case Instruction::LShr:
9035 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009036 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009037 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009038 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009039 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009040 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009041 }
9042}
9043
9044/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9045/// have the same opcode and only one use each. Try to simplify this.
9046Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9047 Instruction *FI) {
9048 if (TI->getNumOperands() == 1) {
9049 // If this is a non-volatile load or a cast from the same type,
9050 // merge.
9051 if (TI->isCast()) {
9052 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9053 return 0;
9054 } else {
9055 return 0; // unknown unary op.
9056 }
9057
9058 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009059 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009060 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009061 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009062 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009063 TI->getType());
9064 }
9065
9066 // Only handle binary operators here.
9067 if (!isa<BinaryOperator>(TI))
9068 return 0;
9069
9070 // Figure out if the operations have any operands in common.
9071 Value *MatchOp, *OtherOpT, *OtherOpF;
9072 bool MatchIsOpZero;
9073 if (TI->getOperand(0) == FI->getOperand(0)) {
9074 MatchOp = TI->getOperand(0);
9075 OtherOpT = TI->getOperand(1);
9076 OtherOpF = FI->getOperand(1);
9077 MatchIsOpZero = true;
9078 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9079 MatchOp = TI->getOperand(1);
9080 OtherOpT = TI->getOperand(0);
9081 OtherOpF = FI->getOperand(0);
9082 MatchIsOpZero = false;
9083 } else if (!TI->isCommutative()) {
9084 return 0;
9085 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9086 MatchOp = TI->getOperand(0);
9087 OtherOpT = TI->getOperand(1);
9088 OtherOpF = FI->getOperand(0);
9089 MatchIsOpZero = true;
9090 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9091 MatchOp = TI->getOperand(1);
9092 OtherOpT = TI->getOperand(0);
9093 OtherOpF = FI->getOperand(1);
9094 MatchIsOpZero = true;
9095 } else {
9096 return 0;
9097 }
9098
9099 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009100 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9101 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009102 InsertNewInstBefore(NewSI, SI);
9103
9104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9105 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009106 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009107 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009108 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009109 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009110 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009111 return 0;
9112}
9113
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009114static bool isSelect01(Constant *C1, Constant *C2) {
9115 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9116 if (!C1I)
9117 return false;
9118 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9119 if (!C2I)
9120 return false;
9121 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9122}
9123
9124/// FoldSelectIntoOp - Try fold the select into one of the operands to
9125/// facilitate further optimization.
9126Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9127 Value *FalseVal) {
9128 // See the comment above GetSelectFoldableOperands for a description of the
9129 // transformation we are doing here.
9130 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9131 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9132 !isa<Constant>(FalseVal)) {
9133 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9134 unsigned OpToFold = 0;
9135 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9136 OpToFold = 1;
9137 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9138 OpToFold = 2;
9139 }
9140
9141 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009142 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009143 Value *OOp = TVI->getOperand(2-OpToFold);
9144 // Avoid creating select between 2 constants unless it's selecting
9145 // between 0 and 1.
9146 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9147 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9148 InsertNewInstBefore(NewSel, SI);
9149 NewSel->takeName(TVI);
9150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9151 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009152 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009153 }
9154 }
9155 }
9156 }
9157 }
9158
9159 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9160 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9161 !isa<Constant>(TrueVal)) {
9162 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9163 unsigned OpToFold = 0;
9164 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9165 OpToFold = 1;
9166 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9167 OpToFold = 2;
9168 }
9169
9170 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009171 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009172 Value *OOp = FVI->getOperand(2-OpToFold);
9173 // Avoid creating select between 2 constants unless it's selecting
9174 // between 0 and 1.
9175 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9176 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9177 InsertNewInstBefore(NewSel, SI);
9178 NewSel->takeName(FVI);
9179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9180 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009181 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009182 }
9183 }
9184 }
9185 }
9186 }
9187
9188 return 0;
9189}
9190
Dan Gohman58c09632008-09-16 18:46:06 +00009191/// visitSelectInstWithICmp - Visit a SelectInst that has an
9192/// ICmpInst as its first operand.
9193///
9194Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9195 ICmpInst *ICI) {
9196 bool Changed = false;
9197 ICmpInst::Predicate Pred = ICI->getPredicate();
9198 Value *CmpLHS = ICI->getOperand(0);
9199 Value *CmpRHS = ICI->getOperand(1);
9200 Value *TrueVal = SI.getTrueValue();
9201 Value *FalseVal = SI.getFalseValue();
9202
9203 // Check cases where the comparison is with a constant that
9204 // can be adjusted to fit the min/max idiom. We may edit ICI in
9205 // place here, so make sure the select is the only user.
9206 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009207 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009208 switch (Pred) {
9209 default: break;
9210 case ICmpInst::ICMP_ULT:
9211 case ICmpInst::ICMP_SLT: {
9212 // X < MIN ? T : F --> F
9213 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9214 return ReplaceInstUsesWith(SI, FalseVal);
9215 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009216 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009217 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9218 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9219 Pred = ICmpInst::getSwappedPredicate(Pred);
9220 CmpRHS = AdjustedRHS;
9221 std::swap(FalseVal, TrueVal);
9222 ICI->setPredicate(Pred);
9223 ICI->setOperand(1, CmpRHS);
9224 SI.setOperand(1, TrueVal);
9225 SI.setOperand(2, FalseVal);
9226 Changed = true;
9227 }
9228 break;
9229 }
9230 case ICmpInst::ICMP_UGT:
9231 case ICmpInst::ICMP_SGT: {
9232 // X > MAX ? T : F --> F
9233 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9234 return ReplaceInstUsesWith(SI, FalseVal);
9235 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009236 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009237 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9238 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9239 Pred = ICmpInst::getSwappedPredicate(Pred);
9240 CmpRHS = AdjustedRHS;
9241 std::swap(FalseVal, TrueVal);
9242 ICI->setPredicate(Pred);
9243 ICI->setOperand(1, CmpRHS);
9244 SI.setOperand(1, TrueVal);
9245 SI.setOperand(2, FalseVal);
9246 Changed = true;
9247 }
9248 break;
9249 }
9250 }
9251
Dan Gohman35b76162008-10-30 20:40:10 +00009252 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9253 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009254 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009255 if (match(TrueVal, m_ConstantInt<-1>()) &&
9256 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009257 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009258 else if (match(TrueVal, m_ConstantInt<0>()) &&
9259 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009260 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9261
Dan Gohman35b76162008-10-30 20:40:10 +00009262 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9263 // If we are just checking for a icmp eq of a single bit and zext'ing it
9264 // to an integer, then shift the bit to the appropriate place and then
9265 // cast to integer to avoid the comparison.
9266 const APInt &Op1CV = CI->getValue();
9267
9268 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9269 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9270 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009271 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009272 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009273 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009274 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009275 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009276 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009277 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009278 if (In->getType() != SI.getType())
9279 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009280 true/*SExt*/, "tmp", ICI);
9281
9282 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009283 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009284 In->getName()+".not"), *ICI);
9285
9286 return ReplaceInstUsesWith(SI, In);
9287 }
9288 }
9289 }
9290
Dan Gohman58c09632008-09-16 18:46:06 +00009291 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9292 // Transform (X == Y) ? X : Y -> Y
9293 if (Pred == ICmpInst::ICMP_EQ)
9294 return ReplaceInstUsesWith(SI, FalseVal);
9295 // Transform (X != Y) ? X : Y -> X
9296 if (Pred == ICmpInst::ICMP_NE)
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9299
9300 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9301 // Transform (X == Y) ? Y : X -> X
9302 if (Pred == ICmpInst::ICMP_EQ)
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 // Transform (X != Y) ? Y : X -> Y
9305 if (Pred == ICmpInst::ICMP_NE)
9306 return ReplaceInstUsesWith(SI, TrueVal);
9307 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9308 }
9309
9310 /// NOTE: if we wanted to, this is where to detect integer ABS
9311
9312 return Changed ? &SI : 0;
9313}
9314
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009315
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009316/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9317/// PHI node (but the two may be in different blocks). See if the true/false
9318/// values (V) are live in all of the predecessor blocks of the PHI. For
9319/// example, cases like this cannot be mapped:
9320///
9321/// X = phi [ C1, BB1], [C2, BB2]
9322/// Y = add
9323/// Z = select X, Y, 0
9324///
9325/// because Y is not live in BB1/BB2.
9326///
9327static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9328 const SelectInst &SI) {
9329 // If the value is a non-instruction value like a constant or argument, it
9330 // can always be mapped.
9331 const Instruction *I = dyn_cast<Instruction>(V);
9332 if (I == 0) return true;
9333
9334 // If V is a PHI node defined in the same block as the condition PHI, we can
9335 // map the arguments.
9336 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9337
9338 if (const PHINode *VP = dyn_cast<PHINode>(I))
9339 if (VP->getParent() == CondPHI->getParent())
9340 return true;
9341
9342 // Otherwise, if the PHI and select are defined in the same block and if V is
9343 // defined in a different block, then we can transform it.
9344 if (SI.getParent() == CondPHI->getParent() &&
9345 I->getParent() != CondPHI->getParent())
9346 return true;
9347
9348 // Otherwise we have a 'hard' case and we can't tell without doing more
9349 // detailed dominator based analysis, punt.
9350 return false;
9351}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009353Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9354 Value *CondVal = SI.getCondition();
9355 Value *TrueVal = SI.getTrueValue();
9356 Value *FalseVal = SI.getFalseValue();
9357
9358 // select true, X, Y -> X
9359 // select false, X, Y -> Y
9360 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9361 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9362
9363 // select C, X, X -> X
9364 if (TrueVal == FalseVal)
9365 return ReplaceInstUsesWith(SI, TrueVal);
9366
9367 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9368 return ReplaceInstUsesWith(SI, FalseVal);
9369 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9370 return ReplaceInstUsesWith(SI, TrueVal);
9371 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9372 if (isa<Constant>(TrueVal))
9373 return ReplaceInstUsesWith(SI, TrueVal);
9374 else
9375 return ReplaceInstUsesWith(SI, FalseVal);
9376 }
9377
Owen Anderson35b47072009-08-13 21:58:54 +00009378 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009379 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9380 if (C->getZExtValue()) {
9381 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009382 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009383 } else {
9384 // Change: A = select B, false, C --> A = and !B, C
9385 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009386 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009387 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009388 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009389 }
9390 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9391 if (C->getZExtValue() == false) {
9392 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009393 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009394 } else {
9395 // Change: A = select B, C, true --> A = or !B, C
9396 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009397 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009398 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009400 }
9401 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009402
9403 // select a, b, a -> a&b
9404 // select a, a, b -> a|b
9405 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009406 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009407 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009409 }
9410
9411 // Selecting between two integer constants?
9412 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9413 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9414 // select C, 1, 0 -> zext C to int
9415 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009416 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009417 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9418 // select C, 0, 1 -> zext !C to int
9419 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009420 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009421 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009422 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009423 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009424
9425 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009426 // If one of the constants is zero (we know they can't both be) and we
9427 // have an icmp instruction with zero, and we have an 'and' with the
9428 // non-constant value, eliminate this whole mess. This corresponds to
9429 // cases like this: ((X & 27) ? 27 : 0)
9430 if (TrueValC->isZero() || FalseValC->isZero())
9431 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9432 cast<Constant>(IC->getOperand(1))->isNullValue())
9433 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9434 if (ICA->getOpcode() == Instruction::And &&
9435 isa<ConstantInt>(ICA->getOperand(1)) &&
9436 (ICA->getOperand(1) == TrueValC ||
9437 ICA->getOperand(1) == FalseValC) &&
9438 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9439 // Okay, now we know that everything is set up, we just don't
9440 // know whether we have a icmp_ne or icmp_eq and whether the
9441 // true or false val is the zero.
9442 bool ShouldNotVal = !TrueValC->isZero();
9443 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9444 Value *V = ICA;
9445 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009446 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009447 Instruction::Xor, V, ICA->getOperand(1)), SI);
9448 return ReplaceInstUsesWith(SI, V);
9449 }
9450 }
9451 }
9452
9453 // See if we are selecting two values based on a comparison of the two values.
9454 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9455 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9456 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009457 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9458 // This is not safe in general for floating point:
9459 // consider X== -0, Y== +0.
9460 // It becomes safe if either operand is a nonzero constant.
9461 ConstantFP *CFPt, *CFPf;
9462 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9463 !CFPt->getValueAPF().isZero()) ||
9464 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9465 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009466 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009467 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009468 // Transform (X != Y) ? X : Y -> X
9469 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9470 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009471 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009472
9473 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9474 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009475 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9476 // This is not safe in general for floating point:
9477 // consider X== -0, Y== +0.
9478 // It becomes safe if either operand is a nonzero constant.
9479 ConstantFP *CFPt, *CFPf;
9480 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9481 !CFPt->getValueAPF().isZero()) ||
9482 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9483 !CFPf->getValueAPF().isZero()))
9484 return ReplaceInstUsesWith(SI, FalseVal);
9485 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009486 // Transform (X != Y) ? Y : X -> Y
9487 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9488 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009489 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009490 }
Dan Gohman58c09632008-09-16 18:46:06 +00009491 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009492 }
9493
9494 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009495 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9496 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9497 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009498
9499 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9500 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9501 if (TI->hasOneUse() && FI->hasOneUse()) {
9502 Instruction *AddOp = 0, *SubOp = 0;
9503
9504 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9505 if (TI->getOpcode() == FI->getOpcode())
9506 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9507 return IV;
9508
9509 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9510 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009511 if ((TI->getOpcode() == Instruction::Sub &&
9512 FI->getOpcode() == Instruction::Add) ||
9513 (TI->getOpcode() == Instruction::FSub &&
9514 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009515 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009516 } else if ((FI->getOpcode() == Instruction::Sub &&
9517 TI->getOpcode() == Instruction::Add) ||
9518 (FI->getOpcode() == Instruction::FSub &&
9519 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009520 AddOp = TI; SubOp = FI;
9521 }
9522
9523 if (AddOp) {
9524 Value *OtherAddOp = 0;
9525 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9526 OtherAddOp = AddOp->getOperand(1);
9527 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9528 OtherAddOp = AddOp->getOperand(0);
9529 }
9530
9531 if (OtherAddOp) {
9532 // So at this point we know we have (Y -> OtherAddOp):
9533 // select C, (add X, Y), (sub X, Z)
9534 Value *NegVal; // Compute -Z
9535 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009536 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009537 } else {
9538 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009539 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009540 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009541 }
9542
9543 Value *NewTrueOp = OtherAddOp;
9544 Value *NewFalseOp = NegVal;
9545 if (AddOp != TI)
9546 std::swap(NewTrueOp, NewFalseOp);
9547 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009548 SelectInst::Create(CondVal, NewTrueOp,
9549 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009550
9551 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009552 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009553 }
9554 }
9555 }
9556
9557 // See if we can fold the select into one of our operands.
9558 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009559 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9560 if (FoldI)
9561 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009562 }
9563
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009564 // See if we can fold the select into a phi node if the condition is a select.
9565 if (isa<PHINode>(SI.getCondition()))
9566 // The true/false values have to be live in the PHI predecessor's blocks.
9567 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9568 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9569 if (Instruction *NV = FoldOpIntoPhi(SI))
9570 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00009571
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009572 if (BinaryOperator::isNot(CondVal)) {
9573 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9574 SI.setOperand(1, FalseVal);
9575 SI.setOperand(2, TrueVal);
9576 return &SI;
9577 }
9578
9579 return 0;
9580}
9581
Dan Gohman2d648bb2008-04-10 18:43:06 +00009582/// EnforceKnownAlignment - If the specified pointer points to an object that
9583/// we control, modify the object's alignment to PrefAlign. This isn't
9584/// often possible though. If alignment is important, a more reliable approach
9585/// is to simply align all global variables and allocation instructions to
9586/// their preferred alignment from the beginning.
9587///
9588static unsigned EnforceKnownAlignment(Value *V,
9589 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009590
Dan Gohman2d648bb2008-04-10 18:43:06 +00009591 User *U = dyn_cast<User>(V);
9592 if (!U) return Align;
9593
Dan Gohman9545fb02009-07-17 20:47:02 +00009594 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009595 default: break;
9596 case Instruction::BitCast:
9597 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9598 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009599 // If all indexes are zero, it is just the alignment of the base pointer.
9600 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009601 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009602 if (!isa<Constant>(*i) ||
9603 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009604 AllZeroOperands = false;
9605 break;
9606 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009607
9608 if (AllZeroOperands) {
9609 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009610 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009611 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009612 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009613 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009614 }
9615
9616 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9617 // If there is a large requested alignment and we can, bump up the alignment
9618 // of the global.
9619 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009620 if (GV->getAlignment() >= PrefAlign)
9621 Align = GV->getAlignment();
9622 else {
9623 GV->setAlignment(PrefAlign);
9624 Align = PrefAlign;
9625 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009626 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009627 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9628 // If there is a requested alignment and if this is an alloca, round up.
9629 if (AI->getAlignment() >= PrefAlign)
9630 Align = AI->getAlignment();
9631 else {
9632 AI->setAlignment(PrefAlign);
9633 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009634 }
9635 }
9636
9637 return Align;
9638}
9639
9640/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9641/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9642/// and it is more than the alignment of the ultimate object, see if we can
9643/// increase the alignment of the ultimate object, making this check succeed.
9644unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9645 unsigned PrefAlign) {
9646 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9647 sizeof(PrefAlign) * CHAR_BIT;
9648 APInt Mask = APInt::getAllOnesValue(BitWidth);
9649 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9650 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9651 unsigned TrailZ = KnownZero.countTrailingOnes();
9652 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9653
9654 if (PrefAlign > Align)
9655 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9656
9657 // We don't need to make any adjustment.
9658 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009659}
9660
Chris Lattner00ae5132008-01-13 23:50:23 +00009661Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009662 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009663 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009664 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009665 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009666
9667 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009668 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009669 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009670 return MI;
9671 }
9672
9673 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9674 // load/store.
9675 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9676 if (MemOpLength == 0) return 0;
9677
Chris Lattnerc669fb62008-01-14 00:28:35 +00009678 // Source and destination pointer types are always "i8*" for intrinsic. See
9679 // if the size is something we can handle with a single primitive load/store.
9680 // A single load+store correctly handles overlapping memory in the memmove
9681 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009682 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009683 if (Size == 0) return MI; // Delete this mem transfer.
9684
9685 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009686 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009687
Chris Lattnerc669fb62008-01-14 00:28:35 +00009688 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009689 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009690 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009691
9692 // Memcpy forces the use of i8* for the source and destination. That means
9693 // that if you're using memcpy to move one double around, you'll get a cast
9694 // from double* to i8*. We'd much rather use a double load+store rather than
9695 // an i64 load+store, here because this improves the odds that the source or
9696 // dest address will be promotable. See if we can find a better type than the
9697 // integer datatype.
9698 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9699 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009700 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009701 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9702 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009703 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009704 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9705 if (STy->getNumElements() == 1)
9706 SrcETy = STy->getElementType(0);
9707 else
9708 break;
9709 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9710 if (ATy->getNumElements() == 1)
9711 SrcETy = ATy->getElementType();
9712 else
9713 break;
9714 } else
9715 break;
9716 }
9717
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009718 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009719 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009720 }
9721 }
9722
9723
Chris Lattner00ae5132008-01-13 23:50:23 +00009724 // If the memcpy/memmove provides better alignment info than we can
9725 // infer, use it.
9726 SrcAlign = std::max(SrcAlign, CopyAlign);
9727 DstAlign = std::max(DstAlign, CopyAlign);
9728
Chris Lattner78628292009-08-30 19:47:22 +00009729 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9730 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009731 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9732 InsertNewInstBefore(L, *MI);
9733 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9734
9735 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009736 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009737 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009738}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009739
Chris Lattner5af8a912008-04-30 06:39:11 +00009740Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9741 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009742 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009743 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009744 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009745 return MI;
9746 }
9747
9748 // Extract the length and alignment and fill if they are constant.
9749 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9750 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009751 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009752 return 0;
9753 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009754 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009755
9756 // If the length is zero, this is a no-op
9757 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9758
9759 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9760 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009761 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009762
9763 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009764 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009765
9766 // Alignment 0 is identity for alignment 1 for memset, but not store.
9767 if (Alignment == 0) Alignment = 1;
9768
9769 // Extract the fill value and store.
9770 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009771 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009772 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009773
9774 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009775 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009776 return MI;
9777 }
9778
9779 return 0;
9780}
9781
9782
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009783/// visitCallInst - CallInst simplification. This mostly only handles folding
9784/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9785/// the heavy lifting.
9786///
9787Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00009788 if (isFreeCall(&CI))
9789 return visitFree(CI);
9790
Chris Lattneraa295aa2009-05-13 17:39:14 +00009791 // If the caller function is nounwind, mark the call as nounwind, even if the
9792 // callee isn't.
9793 if (CI.getParent()->getParent()->doesNotThrow() &&
9794 !CI.doesNotThrow()) {
9795 CI.setDoesNotThrow();
9796 return &CI;
9797 }
9798
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009799 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9800 if (!II) return visitCallSite(&CI);
9801
9802 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9803 // visitCallSite.
9804 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9805 bool Changed = false;
9806
9807 // memmove/cpy/set of zero bytes is a noop.
9808 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9809 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9810
9811 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9812 if (CI->getZExtValue() == 1) {
9813 // Replace the instruction with just byte operations. We would
9814 // transform other cases to loads/stores, but we don't know if
9815 // alignment is sufficient.
9816 }
9817 }
9818
9819 // If we have a memmove and the source operation is a constant global,
9820 // then the source and dest pointers can't alias, so we can change this
9821 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009822 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009823 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9824 if (GVSrc->isConstant()) {
9825 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009826 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9827 const Type *Tys[1];
9828 Tys[0] = CI.getOperand(3)->getType();
9829 CI.setOperand(0,
9830 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009831 Changed = true;
9832 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009833
9834 // memmove(x,x,size) -> noop.
9835 if (MMI->getSource() == MMI->getDest())
9836 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009837 }
9838
9839 // If we can determine a pointer alignment that is bigger than currently
9840 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009841 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009842 if (Instruction *I = SimplifyMemTransfer(MI))
9843 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009844 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9845 if (Instruction *I = SimplifyMemSet(MSI))
9846 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009847 }
9848
9849 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009850 }
9851
9852 switch (II->getIntrinsicID()) {
9853 default: break;
9854 case Intrinsic::bswap:
9855 // bswap(bswap(x)) -> x
9856 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9857 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9858 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9859 break;
9860 case Intrinsic::ppc_altivec_lvx:
9861 case Intrinsic::ppc_altivec_lvxl:
9862 case Intrinsic::x86_sse_loadu_ps:
9863 case Intrinsic::x86_sse2_loadu_pd:
9864 case Intrinsic::x86_sse2_loadu_dq:
9865 // Turn PPC lvx -> load if the pointer is known aligned.
9866 // Turn X86 loadups -> load if the pointer is known aligned.
9867 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009868 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9869 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009870 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009871 }
Chris Lattner989ba312008-06-18 04:33:20 +00009872 break;
9873 case Intrinsic::ppc_altivec_stvx:
9874 case Intrinsic::ppc_altivec_stvxl:
9875 // Turn stvx -> store if the pointer is known aligned.
9876 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9877 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009878 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009879 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009880 return new StoreInst(II->getOperand(1), Ptr);
9881 }
9882 break;
9883 case Intrinsic::x86_sse_storeu_ps:
9884 case Intrinsic::x86_sse2_storeu_pd:
9885 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009886 // Turn X86 storeu -> store if the pointer is known aligned.
9887 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9888 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009889 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009890 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009891 return new StoreInst(II->getOperand(2), Ptr);
9892 }
9893 break;
9894
9895 case Intrinsic::x86_sse_cvttss2si: {
9896 // These intrinsics only demands the 0th element of its input vector. If
9897 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009898 unsigned VWidth =
9899 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9900 APInt DemandedElts(VWidth, 1);
9901 APInt UndefElts(VWidth, 0);
9902 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009903 UndefElts)) {
9904 II->setOperand(1, V);
9905 return II;
9906 }
9907 break;
9908 }
9909
9910 case Intrinsic::ppc_altivec_vperm:
9911 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9912 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9913 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009914
Chris Lattner989ba312008-06-18 04:33:20 +00009915 // Check that all of the elements are integer constants or undefs.
9916 bool AllEltsOk = true;
9917 for (unsigned i = 0; i != 16; ++i) {
9918 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9919 !isa<UndefValue>(Mask->getOperand(i))) {
9920 AllEltsOk = false;
9921 break;
9922 }
9923 }
9924
9925 if (AllEltsOk) {
9926 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00009927 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9928 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009929 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009930
Chris Lattner989ba312008-06-18 04:33:20 +00009931 // Only extract each element once.
9932 Value *ExtractedElts[32];
9933 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9934
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009935 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009936 if (isa<UndefValue>(Mask->getOperand(i)))
9937 continue;
9938 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9939 Idx &= 31; // Match the hardware behavior.
9940
9941 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009942 ExtractedElts[Idx] =
9943 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9944 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9945 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009946 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009947
Chris Lattner989ba312008-06-18 04:33:20 +00009948 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009949 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9950 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9951 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009952 }
Chris Lattner989ba312008-06-18 04:33:20 +00009953 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009954 }
Chris Lattner989ba312008-06-18 04:33:20 +00009955 }
9956 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009957
Chris Lattner989ba312008-06-18 04:33:20 +00009958 case Intrinsic::stackrestore: {
9959 // If the save is right next to the restore, remove the restore. This can
9960 // happen when variable allocas are DCE'd.
9961 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9962 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9963 BasicBlock::iterator BI = SS;
9964 if (&*++BI == II)
9965 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009966 }
Chris Lattner989ba312008-06-18 04:33:20 +00009967 }
9968
9969 // Scan down this block to see if there is another stack restore in the
9970 // same block without an intervening call/alloca.
9971 BasicBlock::iterator BI = II;
9972 TerminatorInst *TI = II->getParent()->getTerminator();
9973 bool CannotRemove = false;
9974 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00009975 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00009976 CannotRemove = true;
9977 break;
9978 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009979 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9980 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9981 // If there is a stackrestore below this one, remove this one.
9982 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9983 return EraseInstFromFunction(CI);
9984 // Otherwise, ignore the intrinsic.
9985 } else {
9986 // If we found a non-intrinsic call, we can't remove the stack
9987 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009988 CannotRemove = true;
9989 break;
9990 }
Chris Lattner989ba312008-06-18 04:33:20 +00009991 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009992 }
Chris Lattner989ba312008-06-18 04:33:20 +00009993
9994 // If the stack restore is in a return/unwind block and if there are no
9995 // allocas or calls between the restore and the return, nuke the restore.
9996 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9997 return EraseInstFromFunction(CI);
9998 break;
9999 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010000 }
10001
10002 return visitCallSite(II);
10003}
10004
10005// InvokeInst simplification
10006//
10007Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10008 return visitCallSite(&II);
10009}
10010
Dale Johannesen96021832008-04-25 21:16:07 +000010011/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10012/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010013static bool isSafeToEliminateVarargsCast(const CallSite CS,
10014 const CastInst * const CI,
10015 const TargetData * const TD,
10016 const int ix) {
10017 if (!CI->isLosslessCast())
10018 return false;
10019
10020 // The size of ByVal arguments is derived from the type, so we
10021 // can't change to a type with a different size. If the size were
10022 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010023 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010024 return true;
10025
10026 const Type* SrcTy =
10027 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10028 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10029 if (!SrcTy->isSized() || !DstTy->isSized())
10030 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010031 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010032 return false;
10033 return true;
10034}
10035
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010036// visitCallSite - Improvements for call and invoke instructions.
10037//
10038Instruction *InstCombiner::visitCallSite(CallSite CS) {
10039 bool Changed = false;
10040
10041 // If the callee is a constexpr cast of a function, attempt to move the cast
10042 // to the arguments of the call/invoke.
10043 if (transformConstExprCastCall(CS)) return 0;
10044
10045 Value *Callee = CS.getCalledValue();
10046
10047 if (Function *CalleeF = dyn_cast<Function>(Callee))
10048 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10049 Instruction *OldCall = CS.getInstruction();
10050 // If the call and callee calling conventions don't match, this call must
10051 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010052 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010053 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010054 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010055 // If OldCall dues not return void then replaceAllUsesWith undef.
10056 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010057 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010058 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010059 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10060 return EraseInstFromFunction(*OldCall);
10061 return 0;
10062 }
10063
10064 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10065 // This instruction is not reachable, just remove it. We insert a store to
10066 // undef so that we know that this code is not reachable, despite the fact
10067 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010068 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010069 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010070 CS.getInstruction());
10071
Devang Patele3829c82009-10-13 22:56:32 +000010072 // If CS dues not return void then replaceAllUsesWith undef.
10073 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010074 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010075 CS.getInstruction()->
10076 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010077
10078 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10079 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010080 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010081 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082 }
10083 return EraseInstFromFunction(*CS.getInstruction());
10084 }
10085
Duncan Sands74833f22007-09-17 10:26:40 +000010086 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10087 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10088 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10089 return transformCallThroughTrampoline(CS);
10090
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010091 const PointerType *PTy = cast<PointerType>(Callee->getType());
10092 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10093 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010094 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010095 // See if we can optimize any arguments passed through the varargs area of
10096 // the call.
10097 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010098 E = CS.arg_end(); I != E; ++I, ++ix) {
10099 CastInst *CI = dyn_cast<CastInst>(*I);
10100 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10101 *I = CI->getOperand(0);
10102 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010103 }
Dale Johannesen35615462008-04-23 18:34:37 +000010104 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010105 }
10106
Duncan Sands2937e352007-12-19 21:13:37 +000010107 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010108 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010109 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010110 Changed = true;
10111 }
10112
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010113 return Changed ? CS.getInstruction() : 0;
10114}
10115
10116// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10117// attempt to move the cast to the arguments of the call/invoke.
10118//
10119bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10120 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10121 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10122 if (CE->getOpcode() != Instruction::BitCast ||
10123 !isa<Function>(CE->getOperand(0)))
10124 return false;
10125 Function *Callee = cast<Function>(CE->getOperand(0));
10126 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010127 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010128
10129 // Okay, this is a cast from a function to a different type. Unless doing so
10130 // would cause a type conversion of one of our arguments, change this call to
10131 // be a direct call with arguments casted to the appropriate types.
10132 //
10133 const FunctionType *FT = Callee->getFunctionType();
10134 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010135 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010136
Duncan Sands7901ce12008-06-01 07:38:42 +000010137 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010138 return false; // TODO: Handle multiple return values.
10139
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010141 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010142 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010143 // Conversion is ok if changing from one pointer type to another or from
10144 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010145 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010146 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010147 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010148 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010149 return false; // Cannot transform this return value.
10150
Duncan Sands5c489582008-01-06 10:12:28 +000010151 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010152 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010153 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010154 return false; // Cannot transform this return value.
10155
Chris Lattner1c8733e2008-03-12 17:45:29 +000010156 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010157 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010158 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010159 return false; // Attribute not compatible with transformed value.
10160 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010161
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010162 // If the callsite is an invoke instruction, and the return value is used by
10163 // a PHI node in a successor, we cannot change the return type of the call
10164 // because there is no place to put the cast instruction (without breaking
10165 // the critical edge). Bail out in this case.
10166 if (!Caller->use_empty())
10167 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10168 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10169 UI != E; ++UI)
10170 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10171 if (PN->getParent() == II->getNormalDest() ||
10172 PN->getParent() == II->getUnwindDest())
10173 return false;
10174 }
10175
10176 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10177 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10178
10179 CallSite::arg_iterator AI = CS.arg_begin();
10180 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10181 const Type *ParamTy = FT->getParamType(i);
10182 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010183
10184 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010185 return false; // Cannot transform this parameter value.
10186
Devang Patelf2a4a922008-09-26 22:53:05 +000010187 if (CallerPAL.getParamAttributes(i + 1)
10188 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010189 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010190
Duncan Sands7901ce12008-06-01 07:38:42 +000010191 // Converting from one pointer type to another or between a pointer and an
10192 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010193 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010194 (TD && ((isa<PointerType>(ParamTy) ||
10195 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10196 (isa<PointerType>(ActTy) ||
10197 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010198 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010199 }
10200
10201 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10202 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010203 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010204
Chris Lattner1c8733e2008-03-12 17:45:29 +000010205 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010207 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010208 // won't be dropping them. Check that these extra arguments have attributes
10209 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010210 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010212 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010213 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010214 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010215 return false;
10216 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010217
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010218 // Okay, we decided that this is a safe thing to do: go ahead and start
10219 // inserting cast instructions as necessary...
10220 std::vector<Value*> Args;
10221 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010222 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010223 attrVec.reserve(NumCommonArgs);
10224
10225 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010226 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010227
10228 // If the return value is not being used, the type may not be compatible
10229 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010230 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010231
10232 // Add the new return attributes.
10233 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010234 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010235
10236 AI = CS.arg_begin();
10237 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238 const Type *ParamTy = FT->getParamType(i);
10239 if ((*AI)->getType() == ParamTy) {
10240 Args.push_back(*AI);
10241 } else {
10242 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10243 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010244 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010245 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010246
10247 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010248 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010249 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010250 }
10251
10252 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010253 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010254 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010255 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010256
Chris Lattnerad7516a2009-08-30 18:50:58 +000010257 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010258 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010259 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010260 errs() << "WARNING: While resolving call to function '"
10261 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010262 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010263 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010264 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10265 const Type *PTy = getPromotedType((*AI)->getType());
10266 if (PTy != (*AI)->getType()) {
10267 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010268 Instruction::CastOps opcode =
10269 CastInst::getCastOpcode(*AI, false, PTy, false);
10270 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010271 } else {
10272 Args.push_back(*AI);
10273 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010274
Duncan Sands4ced1f82008-01-13 08:02:44 +000010275 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010276 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010277 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010278 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010279 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010280 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010281
Devang Patelf2a4a922008-09-26 22:53:05 +000010282 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10283 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10284
Devang Patele9d08b82009-10-14 17:29:00 +000010285 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010286 Caller->setName(""); // Void type should not have a name.
10287
Eric Christopher3e7381f2009-07-25 02:45:27 +000010288 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10289 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010290
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010291 Instruction *NC;
10292 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010293 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010294 Args.begin(), Args.end(),
10295 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010296 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010297 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010298 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010299 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10300 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010301 CallInst *CI = cast<CallInst>(Caller);
10302 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010303 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010304 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010305 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010306 }
10307
10308 // Insert a cast of the return type as necessary.
10309 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010310 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010311 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010312 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010313 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010314 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010315
10316 // If this is an invoke instruction, we should insert it after the first
10317 // non-phi, instruction in the normal successor block.
10318 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010319 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010320 InsertNewInstBefore(NC, *I);
10321 } else {
10322 // Otherwise, it's a call, just insert cast right after the call instr
10323 InsertNewInstBefore(NC, *Caller);
10324 }
Chris Lattner4796b622009-08-30 06:22:51 +000010325 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010326 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010327 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010328 }
10329 }
10330
Devang Pateledad36f2009-10-13 21:41:20 +000010331
Chris Lattner26b7f942009-08-31 05:17:58 +000010332 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010333 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010334
10335 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010336 return true;
10337}
10338
Duncan Sands74833f22007-09-17 10:26:40 +000010339// transformCallThroughTrampoline - Turn a call to a function created by the
10340// init_trampoline intrinsic into a direct call to the underlying function.
10341//
10342Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10343 Value *Callee = CS.getCalledValue();
10344 const PointerType *PTy = cast<PointerType>(Callee->getType());
10345 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010346 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010347
10348 // If the call already has the 'nest' attribute somewhere then give up -
10349 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010350 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010351 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010352
10353 IntrinsicInst *Tramp =
10354 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10355
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010356 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010357 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10358 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10359
Devang Pateld222f862008-09-25 21:00:45 +000010360 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010361 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010362 unsigned NestIdx = 1;
10363 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010364 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010365
10366 // Look for a parameter marked with the 'nest' attribute.
10367 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10368 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010369 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010370 // Record the parameter type and any other attributes.
10371 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010372 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010373 break;
10374 }
10375
10376 if (NestTy) {
10377 Instruction *Caller = CS.getInstruction();
10378 std::vector<Value*> NewArgs;
10379 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10380
Devang Pateld222f862008-09-25 21:00:45 +000010381 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010382 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010383
Duncan Sands74833f22007-09-17 10:26:40 +000010384 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010385 // mean appending it. Likewise for attributes.
10386
Devang Patelf2a4a922008-09-26 22:53:05 +000010387 // Add any result attributes.
10388 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010389 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010390
Duncan Sands74833f22007-09-17 10:26:40 +000010391 {
10392 unsigned Idx = 1;
10393 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10394 do {
10395 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010396 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010397 Value *NestVal = Tramp->getOperand(3);
10398 if (NestVal->getType() != NestTy)
10399 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10400 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010401 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010402 }
10403
10404 if (I == E)
10405 break;
10406
Duncan Sands48b81112008-01-14 19:52:09 +000010407 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010408 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010409 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010410 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010411 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010412
10413 ++Idx, ++I;
10414 } while (1);
10415 }
10416
Devang Patelf2a4a922008-09-26 22:53:05 +000010417 // Add any function attributes.
10418 if (Attributes Attr = Attrs.getFnAttributes())
10419 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10420
Duncan Sands74833f22007-09-17 10:26:40 +000010421 // The trampoline may have been bitcast to a bogus type (FTy).
10422 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010423 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010424
Duncan Sands74833f22007-09-17 10:26:40 +000010425 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010426 NewTypes.reserve(FTy->getNumParams()+1);
10427
Duncan Sands74833f22007-09-17 10:26:40 +000010428 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010429 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010430 {
10431 unsigned Idx = 1;
10432 FunctionType::param_iterator I = FTy->param_begin(),
10433 E = FTy->param_end();
10434
10435 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010436 if (Idx == NestIdx)
10437 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010438 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010439
10440 if (I == E)
10441 break;
10442
Duncan Sands48b81112008-01-14 19:52:09 +000010443 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010444 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010445
10446 ++Idx, ++I;
10447 } while (1);
10448 }
10449
10450 // Replace the trampoline call with a direct call. Let the generic
10451 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010452 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010453 FTy->isVarArg());
10454 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010455 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010456 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010457 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010458 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10459 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010460
10461 Instruction *NewCaller;
10462 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010463 NewCaller = InvokeInst::Create(NewCallee,
10464 II->getNormalDest(), II->getUnwindDest(),
10465 NewArgs.begin(), NewArgs.end(),
10466 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010467 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010468 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010469 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010470 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10471 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010472 if (cast<CallInst>(Caller)->isTailCall())
10473 cast<CallInst>(NewCaller)->setTailCall();
10474 cast<CallInst>(NewCaller)->
10475 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010476 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010477 }
Devang Patele9d08b82009-10-14 17:29:00 +000010478 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010479 Caller->replaceAllUsesWith(NewCaller);
10480 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010481 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010482 return 0;
10483 }
10484 }
10485
10486 // Replace the trampoline call with a direct call. Since there is no 'nest'
10487 // parameter, there is no need to adjust the argument list. Let the generic
10488 // code sort out any function type mismatches.
10489 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010490 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010491 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010492 CS.setCalledFunction(NewCallee);
10493 return CS.getInstruction();
10494}
10495
Dan Gohman09cf2b62009-09-16 16:50:24 +000010496/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10497/// 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 +000010498/// and a single binop.
10499Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10500 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010501 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010502 unsigned Opc = FirstInst->getOpcode();
10503 Value *LHSVal = FirstInst->getOperand(0);
10504 Value *RHSVal = FirstInst->getOperand(1);
10505
10506 const Type *LHSType = LHSVal->getType();
10507 const Type *RHSType = RHSVal->getType();
10508
Dan Gohman09cf2b62009-09-16 16:50:24 +000010509 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010510 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010511 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10512 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10513 // Verify type of the LHS matches so we don't fold cmp's of different
10514 // types or GEP's with different index types.
10515 I->getOperand(0)->getType() != LHSType ||
10516 I->getOperand(1)->getType() != RHSType)
10517 return 0;
10518
10519 // If they are CmpInst instructions, check their predicates
10520 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10521 if (cast<CmpInst>(I)->getPredicate() !=
10522 cast<CmpInst>(FirstInst)->getPredicate())
10523 return 0;
10524
10525 // Keep track of which operand needs a phi node.
10526 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10527 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10528 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010529
10530 // If both LHS and RHS would need a PHI, don't do this transformation,
10531 // because it would increase the number of PHIs entering the block,
10532 // which leads to higher register pressure. This is especially
10533 // bad when the PHIs are in the header of a loop.
10534 if (!LHSVal && !RHSVal)
10535 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010536
Chris Lattner30078012008-12-01 03:42:51 +000010537 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010538
10539 Value *InLHS = FirstInst->getOperand(0);
10540 Value *InRHS = FirstInst->getOperand(1);
10541 PHINode *NewLHS = 0, *NewRHS = 0;
10542 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010543 NewLHS = PHINode::Create(LHSType,
10544 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010545 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10546 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10547 InsertNewInstBefore(NewLHS, PN);
10548 LHSVal = NewLHS;
10549 }
10550
10551 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010552 NewRHS = PHINode::Create(RHSType,
10553 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010554 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10555 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10556 InsertNewInstBefore(NewRHS, PN);
10557 RHSVal = NewRHS;
10558 }
10559
10560 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010561 if (NewLHS || NewRHS) {
10562 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10563 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10564 if (NewLHS) {
10565 Value *NewInLHS = InInst->getOperand(0);
10566 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10567 }
10568 if (NewRHS) {
10569 Value *NewInRHS = InInst->getOperand(1);
10570 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10571 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010572 }
10573 }
10574
10575 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010576 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010577 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010578 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010579 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010580}
10581
Chris Lattner9e1916e2008-12-01 02:34:36 +000010582Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10583 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10584
10585 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10586 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010587 // This is true if all GEP bases are allocas and if all indices into them are
10588 // constants.
10589 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010590
10591 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010592 // more than one phi, which leads to higher register pressure. This is
10593 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010594 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010595
Dan Gohman09cf2b62009-09-16 16:50:24 +000010596 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010597 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10598 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10599 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10600 GEP->getNumOperands() != FirstInst->getNumOperands())
10601 return 0;
10602
Chris Lattneradf354b2009-02-21 00:46:50 +000010603 // Keep track of whether or not all GEPs are of alloca pointers.
10604 if (AllBasePointersAreAllocas &&
10605 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10606 !GEP->hasAllConstantIndices()))
10607 AllBasePointersAreAllocas = false;
10608
Chris Lattner9e1916e2008-12-01 02:34:36 +000010609 // Compare the operand lists.
10610 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10611 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10612 continue;
10613
10614 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10615 // if one of the PHIs has a constant for the index. The index may be
10616 // substantially cheaper to compute for the constants, so making it a
10617 // variable index could pessimize the path. This also handles the case
10618 // for struct indices, which must always be constant.
10619 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10620 isa<ConstantInt>(GEP->getOperand(op)))
10621 return 0;
10622
10623 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10624 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010625
10626 // If we already needed a PHI for an earlier operand, and another operand
10627 // also requires a PHI, we'd be introducing more PHIs than we're
10628 // eliminating, which increases register pressure on entry to the PHI's
10629 // block.
10630 if (NeededPhi)
10631 return 0;
10632
Chris Lattner9e1916e2008-12-01 02:34:36 +000010633 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010634 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010635 }
10636 }
10637
Chris Lattneradf354b2009-02-21 00:46:50 +000010638 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010639 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010640 // offset calculation, but all the predecessors will have to materialize the
10641 // stack address into a register anyway. We'd actually rather *clone* the
10642 // load up into the predecessors so that we have a load of a gep of an alloca,
10643 // which can usually all be folded into the load.
10644 if (AllBasePointersAreAllocas)
10645 return 0;
10646
Chris Lattner9e1916e2008-12-01 02:34:36 +000010647 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10648 // that is variable.
10649 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10650
10651 bool HasAnyPHIs = false;
10652 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10653 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10654 Value *FirstOp = FirstInst->getOperand(i);
10655 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10656 FirstOp->getName()+".pn");
10657 InsertNewInstBefore(NewPN, PN);
10658
10659 NewPN->reserveOperandSpace(e);
10660 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10661 OperandPhis[i] = NewPN;
10662 FixedOperands[i] = NewPN;
10663 HasAnyPHIs = true;
10664 }
10665
10666
10667 // Add all operands to the new PHIs.
10668 if (HasAnyPHIs) {
10669 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10670 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10671 BasicBlock *InBB = PN.getIncomingBlock(i);
10672
10673 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10674 if (PHINode *OpPhi = OperandPhis[op])
10675 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10676 }
10677 }
10678
10679 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010680 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10681 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10682 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010683 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10684 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010685}
10686
10687
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010688/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10689/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010690/// obvious the value of the load is not changed from the point of the load to
10691/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010692///
10693/// Finally, it is safe, but not profitable, to sink a load targetting a
10694/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10695/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010696static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010697 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10698
10699 for (++BBI; BBI != E; ++BBI)
10700 if (BBI->mayWriteToMemory())
10701 return false;
10702
10703 // Check for non-address taken alloca. If not address-taken already, it isn't
10704 // profitable to do this xform.
10705 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10706 bool isAddressTaken = false;
10707 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10708 UI != E; ++UI) {
10709 if (isa<LoadInst>(UI)) continue;
10710 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10711 // If storing TO the alloca, then the address isn't taken.
10712 if (SI->getOperand(1) == AI) continue;
10713 }
10714 isAddressTaken = true;
10715 break;
10716 }
10717
Chris Lattneradf354b2009-02-21 00:46:50 +000010718 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010719 return false;
10720 }
10721
Chris Lattneradf354b2009-02-21 00:46:50 +000010722 // If this load is a load from a GEP with a constant offset from an alloca,
10723 // then we don't want to sink it. In its present form, it will be
10724 // load [constant stack offset]. Sinking it will cause us to have to
10725 // materialize the stack addresses in each predecessor in a register only to
10726 // do a shared load from register in the successor.
10727 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10728 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10729 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10730 return false;
10731
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010732 return true;
10733}
10734
10735
10736// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10737// operator and they all are only used by the PHI, PHI together their
10738// inputs, and do the operation once, to the result of the PHI.
10739Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10740 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10741
10742 // Scan the instruction, looking for input operations that can be folded away.
10743 // If all input operands to the phi are the same instruction (e.g. a cast from
10744 // the same type or "+42") we can pull the operation through the PHI, reducing
10745 // code size and simplifying code.
10746 Constant *ConstantOp = 0;
10747 const Type *CastSrcTy = 0;
10748 bool isVolatile = false;
10749 if (isa<CastInst>(FirstInst)) {
10750 CastSrcTy = FirstInst->getOperand(0)->getType();
10751 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10752 // Can fold binop, compare or shift here if the RHS is a constant,
10753 // otherwise call FoldPHIArgBinOpIntoPHI.
10754 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10755 if (ConstantOp == 0)
10756 return FoldPHIArgBinOpIntoPHI(PN);
10757 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10758 isVolatile = LI->isVolatile();
10759 // We can't sink the load if the loaded value could be modified between the
10760 // load and the PHI.
10761 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010762 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010763 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010764
10765 // If the PHI is of volatile loads and the load block has multiple
10766 // successors, sinking it would remove a load of the volatile value from
10767 // the path through the other successor.
10768 if (isVolatile &&
10769 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10770 return 0;
10771
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010772 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010773 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010774 } else {
10775 return 0; // Cannot fold this operation.
10776 }
10777
10778 // Check to see if all arguments are the same operation.
10779 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10780 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10781 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10782 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10783 return 0;
10784 if (CastSrcTy) {
10785 if (I->getOperand(0)->getType() != CastSrcTy)
10786 return 0; // Cast operation must match.
10787 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10788 // We can't sink the load if the loaded value could be modified between
10789 // the load and the PHI.
10790 if (LI->isVolatile() != isVolatile ||
10791 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010792 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010793 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010794
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010795 // If the PHI is of volatile loads and the load block has multiple
10796 // successors, sinking it would remove a load of the volatile value from
10797 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010798 if (isVolatile &&
10799 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10800 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010801
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010802 } else if (I->getOperand(1) != ConstantOp) {
10803 return 0;
10804 }
10805 }
10806
10807 // Okay, they are all the same operation. Create a new PHI node of the
10808 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010809 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10810 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010811 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10812
10813 Value *InVal = FirstInst->getOperand(0);
10814 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10815
10816 // Add all operands to the new PHI.
10817 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10818 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10819 if (NewInVal != InVal)
10820 InVal = 0;
10821 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10822 }
10823
10824 Value *PhiVal;
10825 if (InVal) {
10826 // The new PHI unions all of the same values together. This is really
10827 // common, so we handle it intelligently here for compile-time speed.
10828 PhiVal = InVal;
10829 delete NewPN;
10830 } else {
10831 InsertNewInstBefore(NewPN, PN);
10832 PhiVal = NewPN;
10833 }
10834
10835 // Insert and return the new operation.
10836 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010837 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010838 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010839 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010840 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohmane6803b82009-08-25 23:17:54 +000010841 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010842 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010843 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10844
10845 // If this was a volatile load that we are merging, make sure to loop through
10846 // and mark all the input loads as non-volatile. If we don't do this, we will
10847 // insert a new volatile load and the old ones will not be deletable.
10848 if (isVolatile)
10849 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10850 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10851
10852 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010853}
10854
10855/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10856/// that is dead.
10857static bool DeadPHICycle(PHINode *PN,
10858 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10859 if (PN->use_empty()) return true;
10860 if (!PN->hasOneUse()) return false;
10861
10862 // Remember this node, and if we find the cycle, return.
10863 if (!PotentiallyDeadPHIs.insert(PN))
10864 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010865
10866 // Don't scan crazily complex things.
10867 if (PotentiallyDeadPHIs.size() == 16)
10868 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010869
10870 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10871 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10872
10873 return false;
10874}
10875
Chris Lattner27b695d2007-11-06 21:52:06 +000010876/// PHIsEqualValue - Return true if this phi node is always equal to
10877/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10878/// z = some value; x = phi (y, z); y = phi (x, z)
10879static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10880 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10881 // See if we already saw this PHI node.
10882 if (!ValueEqualPHIs.insert(PN))
10883 return true;
10884
10885 // Don't scan crazily complex things.
10886 if (ValueEqualPHIs.size() == 16)
10887 return false;
10888
10889 // Scan the operands to see if they are either phi nodes or are equal to
10890 // the value.
10891 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10892 Value *Op = PN->getIncomingValue(i);
10893 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10894 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10895 return false;
10896 } else if (Op != NonPhiInVal)
10897 return false;
10898 }
10899
10900 return true;
10901}
10902
10903
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010904// PHINode simplification
10905//
10906Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10907 // If LCSSA is around, don't mess with Phi nodes
10908 if (MustPreserveLCSSA) return 0;
10909
10910 if (Value *V = PN.hasConstantValue())
10911 return ReplaceInstUsesWith(PN, V);
10912
10913 // If all PHI operands are the same operation, pull them through the PHI,
10914 // reducing code size.
10915 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010916 isa<Instruction>(PN.getIncomingValue(1)) &&
10917 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10918 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10919 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10920 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010921 PN.getIncomingValue(0)->hasOneUse())
10922 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10923 return Result;
10924
10925 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10926 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10927 // PHI)... break the cycle.
10928 if (PN.hasOneUse()) {
10929 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10930 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10931 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10932 PotentiallyDeadPHIs.insert(&PN);
10933 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010934 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010935 }
10936
10937 // If this phi has a single use, and if that use just computes a value for
10938 // the next iteration of a loop, delete the phi. This occurs with unused
10939 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10940 // common case here is good because the only other things that catch this
10941 // are induction variable analysis (sometimes) and ADCE, which is only run
10942 // late.
10943 if (PHIUser->hasOneUse() &&
10944 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10945 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010946 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010947 }
10948 }
10949
Chris Lattner27b695d2007-11-06 21:52:06 +000010950 // We sometimes end up with phi cycles that non-obviously end up being the
10951 // same value, for example:
10952 // z = some value; x = phi (y, z); y = phi (x, z)
10953 // where the phi nodes don't necessarily need to be in the same block. Do a
10954 // quick check to see if the PHI node only contains a single non-phi value, if
10955 // so, scan to see if the phi cycle is actually equal to that value.
10956 {
10957 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10958 // Scan for the first non-phi operand.
10959 while (InValNo != NumOperandVals &&
10960 isa<PHINode>(PN.getIncomingValue(InValNo)))
10961 ++InValNo;
10962
10963 if (InValNo != NumOperandVals) {
10964 Value *NonPhiInVal = PN.getOperand(InValNo);
10965
10966 // Scan the rest of the operands to see if there are any conflicts, if so
10967 // there is no need to recursively scan other phis.
10968 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10969 Value *OpVal = PN.getIncomingValue(InValNo);
10970 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10971 break;
10972 }
10973
10974 // If we scanned over all operands, then we have one unique value plus
10975 // phi values. Scan PHI nodes to see if they all merge in each other or
10976 // the value.
10977 if (InValNo == NumOperandVals) {
10978 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10979 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10980 return ReplaceInstUsesWith(PN, NonPhiInVal);
10981 }
10982 }
10983 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010984 return 0;
10985}
10986
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010987Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10988 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerf3a23592009-08-30 20:36:46 +000010989 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010990 if (GEP.getNumOperands() == 1)
10991 return ReplaceInstUsesWith(GEP, PtrOp);
10992
10993 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010994 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010995
10996 bool HasZeroPointerIndex = false;
10997 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10998 HasZeroPointerIndex = C->isNullValue();
10999
11000 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11001 return ReplaceInstUsesWith(GEP, PtrOp);
11002
11003 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011004 if (TD) {
11005 bool MadeChange = false;
11006 unsigned PtrSize = TD->getPointerSizeInBits();
11007
11008 gep_type_iterator GTI = gep_type_begin(GEP);
11009 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11010 I != E; ++I, ++GTI) {
11011 if (!isa<SequentialType>(*GTI)) continue;
11012
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011013 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011014 // to what we need. If narrower, sign-extend it to what we need. This
11015 // explicit cast can make subsequent optimizations more obvious.
11016 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011017 if (OpBits == PtrSize)
11018 continue;
11019
Chris Lattnerd6164c22009-08-30 20:01:10 +000011020 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011021 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011022 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011023 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011024 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011025
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011026 // Combine Indices - If the source pointer to this getelementptr instruction
11027 // is a getelementptr instruction, combine the indices of the two
11028 // getelementptr instructions into a single instruction.
11029 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011030 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011031 // Note that if our source is a gep chain itself that we wait for that
11032 // chain to be resolved before we perform this transformation. This
11033 // avoids us creating a TON of code in some cases.
11034 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011035 if (GetElementPtrInst *SrcGEP =
11036 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11037 if (SrcGEP->getNumOperands() == 2)
11038 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011039
11040 SmallVector<Value*, 8> Indices;
11041
11042 // Find out whether the last index in the source GEP is a sequential idx.
11043 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000011044 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11045 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011046 EndsWithSequential = !isa<StructType>(*I);
11047
11048 // Can we combine the two pointer arithmetics offsets?
11049 if (EndsWithSequential) {
11050 // Replace: gep (gep %P, long B), long A, ...
11051 // With: T = long A+B; gep %P, T, ...
11052 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011053 Value *Sum;
11054 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11055 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011056 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011057 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011058 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011059 Sum = SO1;
11060 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000011061 // If they aren't the same type, then the input hasn't been processed
11062 // by the loop above yet (which canonicalizes sequential index types to
11063 // intptr_t). Just avoid transforming this until the input has been
11064 // normalized.
11065 if (SO1->getType() != GO1->getType())
11066 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000011067 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011068 }
11069
Chris Lattner1c641fc2009-08-30 05:30:55 +000011070 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011071 if (Src->getNumOperands() == 2) {
11072 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011073 GEP.setOperand(1, Sum);
11074 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011075 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011076 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011077 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011078 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011079 } else if (isa<Constant>(*GEP.idx_begin()) &&
11080 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011081 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011082 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011083 Indices.append(Src->op_begin()+1, Src->op_end());
11084 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011085 }
11086
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011087 if (!Indices.empty())
11088 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11089 Src->isInBounds()) ?
11090 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11091 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011092 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011093 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011094 }
11095
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011096 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11097 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011098 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011099
Chris Lattner83288fa2009-08-30 20:38:21 +000011100 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11101 // want to change the gep until the bitcasts are eliminated.
11102 if (getBitCastOperand(X)) {
11103 Worklist.AddValue(PtrOp);
11104 return 0;
11105 }
11106
Chris Lattnerf3a23592009-08-30 20:36:46 +000011107 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11108 // into : GEP [10 x i8]* X, i32 0, ...
11109 //
11110 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11111 // into : GEP i8* X, ...
11112 //
11113 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011114 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011115 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11116 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011117 if (const ArrayType *CATy =
11118 dyn_cast<ArrayType>(CPTy->getElementType())) {
11119 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11120 if (CATy->getElementType() == XTy->getElementType()) {
11121 // -> GEP i8* X, ...
11122 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011123 return cast<GEPOperator>(&GEP)->isInBounds() ?
11124 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11125 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011126 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11127 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011128 }
11129
11130 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011131 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011132 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011133 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011134 // At this point, we know that the cast source type is a pointer
11135 // to an array of the same type as the destination pointer
11136 // array. Because the array type is never stepped over (there
11137 // is a leading zero) we can fold the cast into this GEP.
11138 GEP.setOperand(0, X);
11139 return &GEP;
11140 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011141 }
11142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011143 } else if (GEP.getNumOperands() == 2) {
11144 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011145 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11146 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011147 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11148 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011149 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011150 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11151 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011152 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011153 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011154 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011155 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11156 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011157 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011158 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011159 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011160 }
11161
11162 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011163 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011164 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011165 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011166
Owen Anderson35b47072009-08-13 21:58:54 +000011167 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011168 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011169 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011170
11171 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11172 // allow either a mul, shift, or constant here.
11173 Value *NewIdx = 0;
11174 ConstantInt *Scale = 0;
11175 if (ArrayEltSize == 1) {
11176 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011177 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011178 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011179 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011180 Scale = CI;
11181 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11182 if (Inst->getOpcode() == Instruction::Shl &&
11183 isa<ConstantInt>(Inst->getOperand(1))) {
11184 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11185 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011186 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011187 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011188 NewIdx = Inst->getOperand(0);
11189 } else if (Inst->getOpcode() == Instruction::Mul &&
11190 isa<ConstantInt>(Inst->getOperand(1))) {
11191 Scale = cast<ConstantInt>(Inst->getOperand(1));
11192 NewIdx = Inst->getOperand(0);
11193 }
11194 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011195
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011196 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011197 // out, perform the transformation. Note, we don't know whether Scale is
11198 // signed or not. We'll use unsigned version of division/modulo
11199 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011200 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011201 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011202 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011203 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011204 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011205 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11206 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011207 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011208 }
11209
11210 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011211 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011212 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011213 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011214 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11215 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11216 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011217 // The NewGEP must be pointer typed, so must the old one -> BitCast
11218 return new BitCastInst(NewGEP, GEP.getType());
11219 }
11220 }
11221 }
11222 }
Chris Lattner111ea772009-01-09 04:53:57 +000011223
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011224 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011225 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011226 /// Y = gep X, <...constant indices...>
11227 /// into a gep of the original struct. This is important for SROA and alias
11228 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011229 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011230 if (TD &&
11231 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011232 // Determine how much the GEP moves the pointer. We are guaranteed to get
11233 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011234 ConstantInt *OffsetV =
11235 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011236 int64_t Offset = OffsetV->getSExtValue();
11237
11238 // If this GEP instruction doesn't move the pointer, just replace the GEP
11239 // with a bitcast of the real input to the dest type.
11240 if (Offset == 0) {
11241 // If the bitcast is of an allocation, and the allocation will be
11242 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000011243 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000011244 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011245 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11246 if (Instruction *I = visitBitCast(*BCI)) {
11247 if (I != BCI) {
11248 I->takeName(BCI);
11249 BCI->getParent()->getInstList().insert(BCI, I);
11250 ReplaceInstUsesWith(*BCI, I);
11251 }
11252 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011253 }
Chris Lattner111ea772009-01-09 04:53:57 +000011254 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011255 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011256 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011257
11258 // Otherwise, if the offset is non-zero, we need to find out if there is a
11259 // field at Offset in 'A's type. If so, we can pull the cast through the
11260 // GEP.
11261 SmallVector<Value*, 8> NewIndices;
11262 const Type *InTy =
11263 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011264 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011265 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11266 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11267 NewIndices.end()) :
11268 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11269 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011270
11271 if (NGEP->getType() == GEP.getType())
11272 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011273 NGEP->takeName(&GEP);
11274 return new BitCastInst(NGEP, GEP.getType());
11275 }
Chris Lattner111ea772009-01-09 04:53:57 +000011276 }
11277 }
11278
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011279 return 0;
11280}
11281
Victor Hernandezb1687302009-10-23 21:09:37 +000011282Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011283 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011284 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011285 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11286 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011287 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000011288 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000011289 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011290 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011291
11292 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011293 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011294 //
11295 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000011296 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011297
11298 // Now that I is pointing to the first non-allocation-inst in the block,
11299 // insert our getelementptr instruction...
11300 //
Owen Anderson35b47072009-08-13 21:58:54 +000011301 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011302 Value *Idx[2];
11303 Idx[0] = NullIdx;
11304 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011305 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11306 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011307
11308 // Now make everything use the getelementptr instead of the original
11309 // allocation.
11310 return ReplaceInstUsesWith(AI, V);
11311 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011312 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011313 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011314 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011315
Dan Gohmana80e2712009-07-21 23:21:54 +000011316 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011317 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011318 // Note that we only do this for alloca's, because malloc should allocate
11319 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011320 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011321 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011322
11323 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11324 if (AI.getAlignment() == 0)
11325 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11326 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011327
11328 return 0;
11329}
11330
11331Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11332 Value *Op = FI.getOperand(0);
11333
11334 // free undef -> unreachable.
11335 if (isa<UndefValue>(Op)) {
11336 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011337 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000011338 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011339 return EraseInstFromFunction(FI);
11340 }
11341
11342 // If we have 'free null' delete the instruction. This can happen in stl code
11343 // when lots of inlining happens.
11344 if (isa<ConstantPointerNull>(Op))
11345 return EraseInstFromFunction(FI);
11346
11347 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11348 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11349 FI.setOperand(0, CI->getOperand(0));
11350 return &FI;
11351 }
11352
11353 // Change free (gep X, 0,0,0,0) into free(X)
11354 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11355 if (GEPI->hasAllZeroIndices()) {
Chris Lattner3183fb62009-08-30 06:13:40 +000011356 Worklist.Add(GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011357 FI.setOperand(0, GEPI->getOperand(0));
11358 return &FI;
11359 }
11360 }
11361
Victor Hernandez48c3c542009-09-18 22:35:49 +000011362 if (isMalloc(Op)) {
11363 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11364 if (Op->hasOneUse() && CI->hasOneUse()) {
11365 EraseInstFromFunction(FI);
11366 EraseInstFromFunction(*CI);
11367 return EraseInstFromFunction(*cast<Instruction>(Op));
11368 }
11369 } else {
11370 // Op is a call to malloc
11371 if (Op->hasOneUse()) {
11372 EraseInstFromFunction(FI);
11373 return EraseInstFromFunction(*cast<Instruction>(Op));
11374 }
11375 }
11376 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011377
11378 return 0;
11379}
11380
Victor Hernandez93946082009-10-24 04:23:03 +000011381Instruction *InstCombiner::visitFree(Instruction &FI) {
11382 Value *Op = FI.getOperand(1);
11383
11384 // free undef -> unreachable.
11385 if (isa<UndefValue>(Op)) {
11386 // Insert a new store to null because we cannot modify the CFG here.
11387 new StoreInst(ConstantInt::getTrue(*Context),
11388 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11389 return EraseInstFromFunction(FI);
11390 }
11391
11392 // If we have 'free null' delete the instruction. This can happen in stl code
11393 // when lots of inlining happens.
11394 if (isa<ConstantPointerNull>(Op))
11395 return EraseInstFromFunction(FI);
11396
11397 // FIXME: Bring back free (gep X, 0,0,0,0) into free(X) transform
11398
11399 if (isMalloc(Op)) {
11400 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11401 if (Op->hasOneUse() && CI->hasOneUse()) {
11402 EraseInstFromFunction(FI);
11403 EraseInstFromFunction(*CI);
11404 return EraseInstFromFunction(*cast<Instruction>(Op));
11405 }
11406 } else {
11407 // Op is a call to malloc
11408 if (Op->hasOneUse()) {
11409 EraseInstFromFunction(FI);
11410 return EraseInstFromFunction(*cast<Instruction>(Op));
11411 }
11412 }
11413 }
11414
11415 return 0;
11416}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011417
11418/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011419static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011420 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011421 User *CI = cast<User>(LI.getOperand(0));
11422 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011423 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011424
Mon P Wangbd05ed82009-02-07 22:19:29 +000011425 const PointerType *DestTy = cast<PointerType>(CI->getType());
11426 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011427 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011428
11429 // If the address spaces don't match, don't eliminate the cast.
11430 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11431 return 0;
11432
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011433 const Type *SrcPTy = SrcTy->getElementType();
11434
11435 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11436 isa<VectorType>(DestPTy)) {
11437 // If the source is an array, the code below will not succeed. Check to
11438 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11439 // constants.
11440 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11441 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11442 if (ASrcTy->getNumElements() != 0) {
11443 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000011444 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11445 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000011446 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011447 SrcTy = cast<PointerType>(CastOp->getType());
11448 SrcPTy = SrcTy->getElementType();
11449 }
11450
Dan Gohmana80e2712009-07-21 23:21:54 +000011451 if (IC.getTargetData() &&
11452 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011453 isa<VectorType>(SrcPTy)) &&
11454 // Do not allow turning this into a load of an integer, which is then
11455 // casted to a pointer, this pessimizes pointer analysis a lot.
11456 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011457 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11458 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459
11460 // Okay, we are casting from one integer or pointer type to another of
11461 // the same size. Instead of casting the pointer before the load, cast
11462 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011463 Value *NewLoad =
11464 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011465 // Now cast the result of the load.
11466 return new BitCastInst(NewLoad, LI.getType());
11467 }
11468 }
11469 }
11470 return 0;
11471}
11472
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011473Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11474 Value *Op = LI.getOperand(0);
11475
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011476 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011477 if (TD) {
11478 unsigned KnownAlign =
11479 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11480 if (KnownAlign >
11481 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11482 LI.getAlignment()))
11483 LI.setAlignment(KnownAlign);
11484 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011485
Chris Lattnerf3a23592009-08-30 20:36:46 +000011486 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011487 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011488 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011489 return Res;
11490
11491 // None of the following transforms are legal for volatile loads.
11492 if (LI.isVolatile()) return 0;
11493
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011494 // Do really simple store-to-load forwarding and load CSE, to catch cases
11495 // where there are several consequtive memory accesses to the same location,
11496 // separated by a few arithmetic operations.
11497 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011498 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11499 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011500
Chris Lattner05274832009-10-22 06:25:11 +000011501 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000011502 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11503 const Value *GEPI0 = GEPI->getOperand(0);
11504 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011505 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011506 // Insert a new store to null instruction before the load to indicate
11507 // that this code is not reachable. We do this instead of inserting
11508 // an unreachable instruction directly because we cannot modify the
11509 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011510 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011511 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011512 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011513 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011514 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011515
Chris Lattner05274832009-10-22 06:25:11 +000011516 // load null/undef -> unreachable
11517 // TODO: Consider a target hook for valid address spaces for this xform.
11518 if (isa<UndefValue>(Op) ||
11519 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11520 // Insert a new store to null instruction before the load to indicate that
11521 // this code is not reachable. We do this instead of inserting an
11522 // unreachable instruction directly because we cannot modify the CFG.
11523 new StoreInst(UndefValue::get(LI.getType()),
11524 Constant::getNullValue(Op->getType()), &LI);
11525 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011526 }
Chris Lattner05274832009-10-22 06:25:11 +000011527
11528 // Instcombine load (constantexpr_cast global) -> cast (load global)
11529 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11530 if (CE->isCast())
11531 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11532 return Res;
11533
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011534 if (Op->hasOneUse()) {
11535 // Change select and PHI nodes to select values instead of addresses: this
11536 // helps alias analysis out a lot, allows many others simplifications, and
11537 // exposes redundancy in the code.
11538 //
11539 // Note that we cannot do the transformation unless we know that the
11540 // introduced loads cannot trap! Something like this is valid as long as
11541 // the condition is always false: load (select bool %C, int* null, int* %G),
11542 // but it would not be valid if we transformed it to load from null
11543 // unconditionally.
11544 //
11545 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11546 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11547 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11548 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011549 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11550 SI->getOperand(1)->getName()+".val");
11551 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11552 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011553 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011554 }
11555
11556 // load (select (cond, null, P)) -> load P
11557 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11558 if (C->isNullValue()) {
11559 LI.setOperand(0, SI->getOperand(2));
11560 return &LI;
11561 }
11562
11563 // load (select (cond, P, null)) -> load P
11564 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11565 if (C->isNullValue()) {
11566 LI.setOperand(0, SI->getOperand(1));
11567 return &LI;
11568 }
11569 }
11570 }
11571 return 0;
11572}
11573
11574/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011575/// when possible. This makes it generally easy to do alias analysis and/or
11576/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011577static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11578 User *CI = cast<User>(SI.getOperand(1));
11579 Value *CastOp = CI->getOperand(0);
11580
11581 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011582 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11583 if (SrcTy == 0) return 0;
11584
11585 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011586
Chris Lattnera032c0e2009-01-16 20:08:59 +000011587 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11588 return 0;
11589
Chris Lattner54dddc72009-01-24 01:00:13 +000011590 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11591 /// to its first element. This allows us to handle things like:
11592 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11593 /// on 32-bit hosts.
11594 SmallVector<Value*, 4> NewGEPIndices;
11595
Chris Lattnera032c0e2009-01-16 20:08:59 +000011596 // If the source is an array, the code below will not succeed. Check to
11597 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11598 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011599 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11600 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011601 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011602 NewGEPIndices.push_back(Zero);
11603
11604 while (1) {
11605 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011606 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011607 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011608 NewGEPIndices.push_back(Zero);
11609 SrcPTy = STy->getElementType(0);
11610 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11611 NewGEPIndices.push_back(Zero);
11612 SrcPTy = ATy->getElementType();
11613 } else {
11614 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011615 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011616 }
11617
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011618 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011619 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011620
11621 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11622 return 0;
11623
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011624 // If the pointers point into different address spaces or if they point to
11625 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011626 if (!IC.getTargetData() ||
11627 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011628 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011629 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11630 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011631 return 0;
11632
11633 // Okay, we are casting from one integer or pointer type to another of
11634 // the same size. Instead of casting the pointer before
11635 // the store, cast the value to be stored.
11636 Value *NewCast;
11637 Value *SIOp0 = SI.getOperand(0);
11638 Instruction::CastOps opcode = Instruction::BitCast;
11639 const Type* CastSrcTy = SIOp0->getType();
11640 const Type* CastDstTy = SrcPTy;
11641 if (isa<PointerType>(CastDstTy)) {
11642 if (CastSrcTy->isInteger())
11643 opcode = Instruction::IntToPtr;
11644 } else if (isa<IntegerType>(CastDstTy)) {
11645 if (isa<PointerType>(SIOp0->getType()))
11646 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011647 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011648
11649 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11650 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011651 if (!NewGEPIndices.empty())
11652 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11653 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000011654
Chris Lattnerad7516a2009-08-30 18:50:58 +000011655 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11656 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000011657 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011658}
11659
Chris Lattner6fd8c802008-11-27 08:56:30 +000011660/// equivalentAddressValues - Test if A and B will obviously have the same
11661/// value. This includes recognizing that %t0 and %t1 will have the same
11662/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011663/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011664/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011665/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011666/// %t2 = load i32* %t1
11667///
11668static bool equivalentAddressValues(Value *A, Value *B) {
11669 // Test if the values are trivially equivalent.
11670 if (A == B) return true;
11671
11672 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011673 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11674 // its only used to compare two uses within the same basic block, which
11675 // means that they'll always either have the same value or one of them
11676 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000011677 if (isa<BinaryOperator>(A) ||
11678 isa<CastInst>(A) ||
11679 isa<PHINode>(A) ||
11680 isa<GetElementPtrInst>(A))
11681 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011682 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000011683 return true;
11684
11685 // Otherwise they may not be equivalent.
11686 return false;
11687}
11688
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011689// If this instruction has two uses, one of which is a llvm.dbg.declare,
11690// return the llvm.dbg.declare.
11691DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11692 if (!V->hasNUses(2))
11693 return 0;
11694 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11695 UI != E; ++UI) {
11696 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11697 return DI;
11698 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11699 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11700 return DI;
11701 }
11702 }
11703 return 0;
11704}
11705
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011706Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11707 Value *Val = SI.getOperand(0);
11708 Value *Ptr = SI.getOperand(1);
11709
11710 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11711 EraseInstFromFunction(SI);
11712 ++NumCombined;
11713 return 0;
11714 }
11715
11716 // If the RHS is an alloca with a single use, zapify the store, making the
11717 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011718 // If the RHS is an alloca with a two uses, the other one being a
11719 // llvm.dbg.declare, zapify the store and the declare, making the
11720 // alloca dead. We must do this to prevent declare's from affecting
11721 // codegen.
11722 if (!SI.isVolatile()) {
11723 if (Ptr->hasOneUse()) {
11724 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011725 EraseInstFromFunction(SI);
11726 ++NumCombined;
11727 return 0;
11728 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011729 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11730 if (isa<AllocaInst>(GEP->getOperand(0))) {
11731 if (GEP->getOperand(0)->hasOneUse()) {
11732 EraseInstFromFunction(SI);
11733 ++NumCombined;
11734 return 0;
11735 }
11736 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11737 EraseInstFromFunction(*DI);
11738 EraseInstFromFunction(SI);
11739 ++NumCombined;
11740 return 0;
11741 }
11742 }
11743 }
11744 }
11745 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11746 EraseInstFromFunction(*DI);
11747 EraseInstFromFunction(SI);
11748 ++NumCombined;
11749 return 0;
11750 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011751 }
11752
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011753 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011754 if (TD) {
11755 unsigned KnownAlign =
11756 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11757 if (KnownAlign >
11758 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11759 SI.getAlignment()))
11760 SI.setAlignment(KnownAlign);
11761 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011762
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011763 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011764 // stores to the same location, separated by a few arithmetic operations. This
11765 // situation often occurs with bitfield accesses.
11766 BasicBlock::iterator BBI = &SI;
11767 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11768 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011769 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011770 // Don't count debug info directives, lest they affect codegen,
11771 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11772 // It is necessary for correctness to skip those that feed into a
11773 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011774 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011775 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011776 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011777 continue;
11778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011779
11780 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11781 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011782 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11783 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011784 ++NumDeadStore;
11785 ++BBI;
11786 EraseInstFromFunction(*PrevSI);
11787 continue;
11788 }
11789 break;
11790 }
11791
11792 // If this is a load, we have to stop. However, if the loaded value is from
11793 // the pointer we're loading and is producing the pointer we're storing,
11794 // then *this* store is dead (X = load P; store X -> P).
11795 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011796 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11797 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011798 EraseInstFromFunction(SI);
11799 ++NumCombined;
11800 return 0;
11801 }
11802 // Otherwise, this is a load from some other location. Stores before it
11803 // may not be dead.
11804 break;
11805 }
11806
11807 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011808 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011809 break;
11810 }
11811
11812
11813 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11814
11815 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000011816 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011817 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011818 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011819 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000011820 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011821 ++NumCombined;
11822 }
11823 return 0; // Do not modify these!
11824 }
11825
11826 // store undef, Ptr -> noop
11827 if (isa<UndefValue>(Val)) {
11828 EraseInstFromFunction(SI);
11829 ++NumCombined;
11830 return 0;
11831 }
11832
11833 // If the pointer destination is a cast, see if we can fold the cast into the
11834 // source instead.
11835 if (isa<CastInst>(Ptr))
11836 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11837 return Res;
11838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11839 if (CE->isCast())
11840 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11841 return Res;
11842
11843
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011844 // If this store is the last instruction in the basic block (possibly
11845 // excepting debug info instructions and the pointer bitcasts that feed
11846 // into them), and if the block ends with an unconditional branch, try
11847 // to move it to the successor block.
11848 BBI = &SI;
11849 do {
11850 ++BBI;
11851 } while (isa<DbgInfoIntrinsic>(BBI) ||
11852 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011853 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11854 if (BI->isUnconditional())
11855 if (SimplifyStoreAtEndOfBlock(SI))
11856 return 0; // xform done!
11857
11858 return 0;
11859}
11860
11861/// SimplifyStoreAtEndOfBlock - Turn things like:
11862/// if () { *P = v1; } else { *P = v2 }
11863/// into a phi node with a store in the successor.
11864///
11865/// Simplify things like:
11866/// *P = v1; if () { *P = v2; }
11867/// into a phi node with a store in the successor.
11868///
11869bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11870 BasicBlock *StoreBB = SI.getParent();
11871
11872 // Check to see if the successor block has exactly two incoming edges. If
11873 // so, see if the other predecessor contains a store to the same location.
11874 // if so, insert a PHI node (if needed) and move the stores down.
11875 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11876
11877 // Determine whether Dest has exactly two predecessors and, if so, compute
11878 // the other predecessor.
11879 pred_iterator PI = pred_begin(DestBB);
11880 BasicBlock *OtherBB = 0;
11881 if (*PI != StoreBB)
11882 OtherBB = *PI;
11883 ++PI;
11884 if (PI == pred_end(DestBB))
11885 return false;
11886
11887 if (*PI != StoreBB) {
11888 if (OtherBB)
11889 return false;
11890 OtherBB = *PI;
11891 }
11892 if (++PI != pred_end(DestBB))
11893 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011894
11895 // Bail out if all the relevant blocks aren't distinct (this can happen,
11896 // for example, if SI is in an infinite loop)
11897 if (StoreBB == DestBB || OtherBB == DestBB)
11898 return false;
11899
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011900 // Verify that the other block ends in a branch and is not otherwise empty.
11901 BasicBlock::iterator BBI = OtherBB->getTerminator();
11902 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11903 if (!OtherBr || BBI == OtherBB->begin())
11904 return false;
11905
11906 // If the other block ends in an unconditional branch, check for the 'if then
11907 // else' case. there is an instruction before the branch.
11908 StoreInst *OtherStore = 0;
11909 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011910 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011911 // Skip over debugging info.
11912 while (isa<DbgInfoIntrinsic>(BBI) ||
11913 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11914 if (BBI==OtherBB->begin())
11915 return false;
11916 --BBI;
11917 }
11918 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011919 OtherStore = dyn_cast<StoreInst>(BBI);
11920 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11921 return false;
11922 } else {
11923 // Otherwise, the other block ended with a conditional branch. If one of the
11924 // destinations is StoreBB, then we have the if/then case.
11925 if (OtherBr->getSuccessor(0) != StoreBB &&
11926 OtherBr->getSuccessor(1) != StoreBB)
11927 return false;
11928
11929 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11930 // if/then triangle. See if there is a store to the same ptr as SI that
11931 // lives in OtherBB.
11932 for (;; --BBI) {
11933 // Check to see if we find the matching store.
11934 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11935 if (OtherStore->getOperand(1) != SI.getOperand(1))
11936 return false;
11937 break;
11938 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011939 // If we find something that may be using or overwriting the stored
11940 // value, or if we run out of instructions, we can't do the xform.
11941 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011942 BBI == OtherBB->begin())
11943 return false;
11944 }
11945
11946 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011947 // make sure nothing reads or overwrites the stored value in
11948 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011949 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11950 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011951 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011952 return false;
11953 }
11954 }
11955
11956 // Insert a PHI node now if we need it.
11957 Value *MergedVal = OtherStore->getOperand(0);
11958 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011959 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011960 PN->reserveOperandSpace(2);
11961 PN->addIncoming(SI.getOperand(0), SI.getParent());
11962 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11963 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11964 }
11965
11966 // Advance to a place where it is safe to insert the new store and
11967 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011968 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011969 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11970 OtherStore->isVolatile()), *BBI);
11971
11972 // Nuke the old stores.
11973 EraseInstFromFunction(SI);
11974 EraseInstFromFunction(*OtherStore);
11975 ++NumCombined;
11976 return true;
11977}
11978
11979
11980Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11981 // Change br (not X), label True, label False to: br X, label False, True
11982 Value *X = 0;
11983 BasicBlock *TrueDest;
11984 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000011985 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011986 !isa<Constant>(X)) {
11987 // Swap Destinations and condition...
11988 BI.setCondition(X);
11989 BI.setSuccessor(0, FalseDest);
11990 BI.setSuccessor(1, TrueDest);
11991 return &BI;
11992 }
11993
11994 // Cannonicalize fcmp_one -> fcmp_oeq
11995 FCmpInst::Predicate FPred; Value *Y;
11996 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011997 TrueDest, FalseDest)) &&
11998 BI.getCondition()->hasOneUse())
11999 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12000 FPred == FCmpInst::FCMP_OGE) {
12001 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12002 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12003
12004 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012005 BI.setSuccessor(0, FalseDest);
12006 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012007 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012008 return &BI;
12009 }
12010
12011 // Cannonicalize icmp_ne -> icmp_eq
12012 ICmpInst::Predicate IPred;
12013 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012014 TrueDest, FalseDest)) &&
12015 BI.getCondition()->hasOneUse())
12016 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12017 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12018 IPred == ICmpInst::ICMP_SGE) {
12019 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12020 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12021 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012022 BI.setSuccessor(0, FalseDest);
12023 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012024 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012025 return &BI;
12026 }
12027
12028 return 0;
12029}
12030
12031Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12032 Value *Cond = SI.getCondition();
12033 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12034 if (I->getOpcode() == Instruction::Add)
12035 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12036 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12037 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012038 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012039 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012040 AddRHS));
12041 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012042 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012043 return &SI;
12044 }
12045 }
12046 return 0;
12047}
12048
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012049Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012050 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012051
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012052 if (!EV.hasIndices())
12053 return ReplaceInstUsesWith(EV, Agg);
12054
12055 if (Constant *C = dyn_cast<Constant>(Agg)) {
12056 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012057 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012058
12059 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012060 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012061
12062 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12063 // Extract the element indexed by the first index out of the constant
12064 Value *V = C->getOperand(*EV.idx_begin());
12065 if (EV.getNumIndices() > 1)
12066 // Extract the remaining indices out of the constant indexed by the
12067 // first index
12068 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12069 else
12070 return ReplaceInstUsesWith(EV, V);
12071 }
12072 return 0; // Can't handle other constants
12073 }
12074 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12075 // We're extracting from an insertvalue instruction, compare the indices
12076 const unsigned *exti, *exte, *insi, *inse;
12077 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12078 exte = EV.idx_end(), inse = IV->idx_end();
12079 exti != exte && insi != inse;
12080 ++exti, ++insi) {
12081 if (*insi != *exti)
12082 // The insert and extract both reference distinctly different elements.
12083 // This means the extract is not influenced by the insert, and we can
12084 // replace the aggregate operand of the extract with the aggregate
12085 // operand of the insert. i.e., replace
12086 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12087 // %E = extractvalue { i32, { i32 } } %I, 0
12088 // with
12089 // %E = extractvalue { i32, { i32 } } %A, 0
12090 return ExtractValueInst::Create(IV->getAggregateOperand(),
12091 EV.idx_begin(), EV.idx_end());
12092 }
12093 if (exti == exte && insi == inse)
12094 // Both iterators are at the end: Index lists are identical. Replace
12095 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12096 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12097 // with "i32 42"
12098 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12099 if (exti == exte) {
12100 // The extract list is a prefix of the insert list. i.e. replace
12101 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12102 // %E = extractvalue { i32, { i32 } } %I, 1
12103 // with
12104 // %X = extractvalue { i32, { i32 } } %A, 1
12105 // %E = insertvalue { i32 } %X, i32 42, 0
12106 // by switching the order of the insert and extract (though the
12107 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012108 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12109 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012110 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12111 insi, inse);
12112 }
12113 if (insi == inse)
12114 // The insert list is a prefix of the extract list
12115 // We can simply remove the common indices from the extract and make it
12116 // operate on the inserted value instead of the insertvalue result.
12117 // i.e., replace
12118 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12119 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12120 // with
12121 // %E extractvalue { i32 } { i32 42 }, 0
12122 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12123 exti, exte);
12124 }
12125 // Can't simplify extracts from other values. Note that nested extracts are
12126 // already simplified implicitely by the above (extract ( extract (insert) )
12127 // will be translated into extract ( insert ( extract ) ) first and then just
12128 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012129 return 0;
12130}
12131
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012132/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12133/// is to leave as a vector operation.
12134static bool CheapToScalarize(Value *V, bool isConstant) {
12135 if (isa<ConstantAggregateZero>(V))
12136 return true;
12137 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12138 if (isConstant) return true;
12139 // If all elts are the same, we can extract.
12140 Constant *Op0 = C->getOperand(0);
12141 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12142 if (C->getOperand(i) != Op0)
12143 return false;
12144 return true;
12145 }
12146 Instruction *I = dyn_cast<Instruction>(V);
12147 if (!I) return false;
12148
12149 // Insert element gets simplified to the inserted element or is deleted if
12150 // this is constant idx extract element and its a constant idx insertelt.
12151 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12152 isa<ConstantInt>(I->getOperand(2)))
12153 return true;
12154 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12155 return true;
12156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12157 if (BO->hasOneUse() &&
12158 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12159 CheapToScalarize(BO->getOperand(1), isConstant)))
12160 return true;
12161 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12162 if (CI->hasOneUse() &&
12163 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12164 CheapToScalarize(CI->getOperand(1), isConstant)))
12165 return true;
12166
12167 return false;
12168}
12169
12170/// Read and decode a shufflevector mask.
12171///
12172/// It turns undef elements into values that are larger than the number of
12173/// elements in the input.
12174static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12175 unsigned NElts = SVI->getType()->getNumElements();
12176 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12177 return std::vector<unsigned>(NElts, 0);
12178 if (isa<UndefValue>(SVI->getOperand(2)))
12179 return std::vector<unsigned>(NElts, 2*NElts);
12180
12181 std::vector<unsigned> Result;
12182 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012183 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12184 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012185 Result.push_back(NElts*2); // undef -> 8
12186 else
Gabor Greif17396002008-06-12 21:37:33 +000012187 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012188 return Result;
12189}
12190
12191/// FindScalarElement - Given a vector and an element number, see if the scalar
12192/// value is already around as a register, for example if it were inserted then
12193/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012194static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012195 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012196 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12197 const VectorType *PTy = cast<VectorType>(V->getType());
12198 unsigned Width = PTy->getNumElements();
12199 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012200 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012201
12202 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012203 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012204 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012205 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012206 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12207 return CP->getOperand(EltNo);
12208 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12209 // If this is an insert to a variable element, we don't know what it is.
12210 if (!isa<ConstantInt>(III->getOperand(2)))
12211 return 0;
12212 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12213
12214 // If this is an insert to the element we are looking for, return the
12215 // inserted value.
12216 if (EltNo == IIElt)
12217 return III->getOperand(1);
12218
12219 // Otherwise, the insertelement doesn't modify the value, recurse on its
12220 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012221 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012222 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012223 unsigned LHSWidth =
12224 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012225 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012226 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012227 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012228 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012229 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012230 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012231 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012232 }
12233
12234 // Otherwise, we don't know.
12235 return 0;
12236}
12237
12238Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012239 // If vector val is undef, replace extract with scalar undef.
12240 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012241 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012242
12243 // If vector val is constant 0, replace extract with scalar 0.
12244 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012245 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012246
12247 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012248 // If vector val is constant with all elements the same, replace EI with
12249 // that element. When the elements are not identical, we cannot replace yet
12250 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012251 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012252 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012253 if (C->getOperand(i) != op0) {
12254 op0 = 0;
12255 break;
12256 }
12257 if (op0)
12258 return ReplaceInstUsesWith(EI, op0);
12259 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012260
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012261 // If extracting a specified index from the vector, see if we can recursively
12262 // find a previously computed scalar that was inserted into the vector.
12263 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12264 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012265 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012266
12267 // If this is extracting an invalid index, turn this into undef, to avoid
12268 // crashing the code below.
12269 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012270 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012271
12272 // This instruction only demands the single element from the input vector.
12273 // If the input vector has a single use, simplify it based on this use
12274 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012275 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012276 APInt UndefElts(VectorWidth, 0);
12277 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012278 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012279 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012280 EI.setOperand(0, V);
12281 return &EI;
12282 }
12283 }
12284
Owen Anderson24be4c12009-07-03 00:17:18 +000012285 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012286 return ReplaceInstUsesWith(EI, Elt);
12287
12288 // If the this extractelement is directly using a bitcast from a vector of
12289 // the same number of elements, see if we can find the source element from
12290 // it. In this case, we will end up needing to bitcast the scalars.
12291 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12292 if (const VectorType *VT =
12293 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12294 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012295 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12296 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012297 return new BitCastInst(Elt, EI.getType());
12298 }
12299 }
12300
12301 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012302 // Push extractelement into predecessor operation if legal and
12303 // profitable to do so
12304 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12305 if (I->hasOneUse() &&
12306 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12307 Value *newEI0 =
12308 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12309 EI.getName()+".lhs");
12310 Value *newEI1 =
12311 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12312 EI.getName()+".rhs");
12313 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012314 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012315 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012316 // Extracting the inserted element?
12317 if (IE->getOperand(2) == EI.getOperand(1))
12318 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12319 // If the inserted and extracted elements are constants, they must not
12320 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012321 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012322 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012323 EI.setOperand(0, IE->getOperand(0));
12324 return &EI;
12325 }
12326 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12327 // If this is extracting an element from a shufflevector, figure out where
12328 // it came from and extract from the appropriate input element instead.
12329 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12330 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12331 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012332 unsigned LHSWidth =
12333 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12334
12335 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012336 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012337 else if (SrcIdx < LHSWidth*2) {
12338 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012339 Src = SVI->getOperand(1);
12340 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012341 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012342 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012343 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012344 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12345 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012346 }
12347 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012348 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012349 }
12350 return 0;
12351}
12352
12353/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12354/// elements from either LHS or RHS, return the shuffle mask and true.
12355/// Otherwise, return false.
12356static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012357 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012358 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012359 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12360 "Invalid CollectSingleShuffleElements");
12361 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12362
12363 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012364 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012365 return true;
12366 } else if (V == LHS) {
12367 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012368 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012369 return true;
12370 } else if (V == RHS) {
12371 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012372 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012373 return true;
12374 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12375 // If this is an insert of an extract from some other vector, include it.
12376 Value *VecOp = IEI->getOperand(0);
12377 Value *ScalarOp = IEI->getOperand(1);
12378 Value *IdxOp = IEI->getOperand(2);
12379
12380 if (!isa<ConstantInt>(IdxOp))
12381 return false;
12382 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12383
12384 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12385 // Okay, we can handle this if the vector we are insertinting into is
12386 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012387 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012388 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012389 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012390 return true;
12391 }
12392 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12393 if (isa<ConstantInt>(EI->getOperand(1)) &&
12394 EI->getOperand(0)->getType() == V->getType()) {
12395 unsigned ExtractedIdx =
12396 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12397
12398 // This must be extracting from either LHS or RHS.
12399 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12400 // Okay, we can handle this if the vector we are insertinting into is
12401 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012402 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012403 // If so, update the mask to reflect the inserted value.
12404 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012405 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012406 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012407 } else {
12408 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012409 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012410 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012411
12412 }
12413 return true;
12414 }
12415 }
12416 }
12417 }
12418 }
12419 // TODO: Handle shufflevector here!
12420
12421 return false;
12422}
12423
12424/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12425/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12426/// that computes V and the LHS value of the shuffle.
12427static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012428 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012429 assert(isa<VectorType>(V->getType()) &&
12430 (RHS == 0 || V->getType() == RHS->getType()) &&
12431 "Invalid shuffle!");
12432 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12433
12434 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012435 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012436 return V;
12437 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012438 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012439 return V;
12440 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12441 // If this is an insert of an extract from some other vector, include it.
12442 Value *VecOp = IEI->getOperand(0);
12443 Value *ScalarOp = IEI->getOperand(1);
12444 Value *IdxOp = IEI->getOperand(2);
12445
12446 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12447 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12448 EI->getOperand(0)->getType() == V->getType()) {
12449 unsigned ExtractedIdx =
12450 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12451 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12452
12453 // Either the extracted from or inserted into vector must be RHSVec,
12454 // otherwise we'd end up with a shuffle of three inputs.
12455 if (EI->getOperand(0) == RHS || RHS == 0) {
12456 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012457 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012458 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012459 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012460 return V;
12461 }
12462
12463 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012464 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12465 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012466 // Everything but the extracted element is replaced with the RHS.
12467 for (unsigned i = 0; i != NumElts; ++i) {
12468 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012469 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012470 }
12471 return V;
12472 }
12473
12474 // If this insertelement is a chain that comes from exactly these two
12475 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012476 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12477 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012478 return EI->getOperand(0);
12479
12480 }
12481 }
12482 }
12483 // TODO: Handle shufflevector here!
12484
12485 // Otherwise, can't do anything fancy. Return an identity vector.
12486 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012487 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012488 return V;
12489}
12490
12491Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12492 Value *VecOp = IE.getOperand(0);
12493 Value *ScalarOp = IE.getOperand(1);
12494 Value *IdxOp = IE.getOperand(2);
12495
12496 // Inserting an undef or into an undefined place, remove this.
12497 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12498 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012499
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012500 // If the inserted element was extracted from some other vector, and if the
12501 // indexes are constant, try to turn this into a shufflevector operation.
12502 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12503 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12504 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012505 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012506 unsigned ExtractedIdx =
12507 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12508 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12509
12510 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12511 return ReplaceInstUsesWith(IE, VecOp);
12512
12513 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012514 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012515
12516 // If we are extracting a value from a vector, then inserting it right
12517 // back into the same place, just use the input vector.
12518 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12519 return ReplaceInstUsesWith(IE, VecOp);
12520
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012521 // If this insertelement isn't used by some other insertelement, turn it
12522 // (and any insertelements it points to), into one big shuffle.
12523 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12524 std::vector<Constant*> Mask;
12525 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012526 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012527 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012528 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012529 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012530 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012531 }
12532 }
12533 }
12534
Eli Friedmanbefee262009-06-06 20:08:03 +000012535 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12536 APInt UndefElts(VWidth, 0);
12537 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12538 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12539 return &IE;
12540
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012541 return 0;
12542}
12543
12544
12545Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12546 Value *LHS = SVI.getOperand(0);
12547 Value *RHS = SVI.getOperand(1);
12548 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12549
12550 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012551
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012552 // Undefined shuffle mask -> undefined value.
12553 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012554 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012555
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012556 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012557
12558 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12559 return 0;
12560
Evan Cheng63295ab2009-02-03 10:05:09 +000012561 APInt UndefElts(VWidth, 0);
12562 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12563 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012564 LHS = SVI.getOperand(0);
12565 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012566 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012567 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012568
12569 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12570 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12571 if (LHS == RHS || isa<UndefValue>(LHS)) {
12572 if (isa<UndefValue>(LHS) && LHS == RHS) {
12573 // shuffle(undef,undef,mask) -> undef.
12574 return ReplaceInstUsesWith(SVI, LHS);
12575 }
12576
12577 // Remap any references to RHS to use LHS.
12578 std::vector<Constant*> Elts;
12579 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12580 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012581 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012582 else {
12583 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012584 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012585 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012586 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012587 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012588 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012589 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012590 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012591 }
12592 }
12593 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012594 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012595 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012596 LHS = SVI.getOperand(0);
12597 RHS = SVI.getOperand(1);
12598 MadeChange = true;
12599 }
12600
12601 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12602 bool isLHSID = true, isRHSID = true;
12603
12604 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12605 if (Mask[i] >= e*2) continue; // Ignore undef values.
12606 // Is this an identity shuffle of the LHS value?
12607 isLHSID &= (Mask[i] == i);
12608
12609 // Is this an identity shuffle of the RHS value?
12610 isRHSID &= (Mask[i]-e == i);
12611 }
12612
12613 // Eliminate identity shuffles.
12614 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12615 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12616
12617 // If the LHS is a shufflevector itself, see if we can combine it with this
12618 // one without producing an unusual shuffle. Here we are really conservative:
12619 // we are absolutely afraid of producing a shuffle mask not in the input
12620 // program, because the code gen may not be smart enough to turn a merged
12621 // shuffle into two specific shuffles: it may produce worse code. As such,
12622 // we only merge two shuffles if the result is one of the two input shuffle
12623 // masks. In this case, merging the shuffles just removes one instruction,
12624 // which we know is safe. This is good for things like turning:
12625 // (splat(splat)) -> splat.
12626 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12627 if (isa<UndefValue>(RHS)) {
12628 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12629
12630 std::vector<unsigned> NewMask;
12631 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12632 if (Mask[i] >= 2*e)
12633 NewMask.push_back(2*e);
12634 else
12635 NewMask.push_back(LHSMask[Mask[i]]);
12636
12637 // If the result mask is equal to the src shuffle or this shuffle mask, do
12638 // the replacement.
12639 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012640 unsigned LHSInNElts =
12641 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012642 std::vector<Constant*> Elts;
12643 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012644 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000012645 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012646 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000012647 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012648 }
12649 }
12650 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12651 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012652 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012653 }
12654 }
12655 }
12656
12657 return MadeChange ? &SVI : 0;
12658}
12659
12660
12661
12662
12663/// TryToSinkInstruction - Try to move the specified instruction from its
12664/// current block into the beginning of DestBlock, which can only happen if it's
12665/// safe to move the instruction past all of the instructions between it and the
12666/// end of its block.
12667static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12668 assert(I->hasOneUse() && "Invariants didn't hold!");
12669
12670 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012671 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012672 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012673
12674 // Do not sink alloca instructions out of the entry block.
12675 if (isa<AllocaInst>(I) && I->getParent() ==
12676 &DestBlock->getParent()->getEntryBlock())
12677 return false;
12678
12679 // We can only sink load instructions if there is nothing between the load and
12680 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012681 if (I->mayReadFromMemory()) {
12682 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012683 Scan != E; ++Scan)
12684 if (Scan->mayWriteToMemory())
12685 return false;
12686 }
12687
Dan Gohman514277c2008-05-23 21:05:58 +000012688 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012689
Dale Johannesen24339f12009-03-03 01:09:07 +000012690 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012691 I->moveBefore(InsertPos);
12692 ++NumSunkInst;
12693 return true;
12694}
12695
12696
12697/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12698/// all reachable code to the worklist.
12699///
12700/// This has a couple of tricks to make the code faster and more powerful. In
12701/// particular, we constant fold and DCE instructions as we go, to avoid adding
12702/// them to the worklist (this significantly speeds up instcombine on code where
12703/// many instructions are dead or constant). Additionally, if we find a branch
12704/// whose condition is a known constant, we only visit the reachable successors.
12705///
Chris Lattnerc4269e52009-10-15 04:59:28 +000012706static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012707 SmallPtrSet<BasicBlock*, 64> &Visited,
12708 InstCombiner &IC,
12709 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000012710 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000012711 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012712 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000012713
12714 std::vector<Instruction*> InstrsForInstCombineWorklist;
12715 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012716
Chris Lattnerc4269e52009-10-15 04:59:28 +000012717 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12718
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012719 while (!Worklist.empty()) {
12720 BB = Worklist.back();
12721 Worklist.pop_back();
12722
12723 // We have now visited this block! If we've already been here, ignore it.
12724 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012725
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012726 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12727 Instruction *Inst = BBI++;
12728
12729 // DCE instruction if trivially dead.
12730 if (isInstructionTriviallyDead(Inst)) {
12731 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000012732 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012733 Inst->eraseFromParent();
12734 continue;
12735 }
12736
12737 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000012738 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12739 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12740 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12741 << *Inst << '\n');
12742 Inst->replaceAllUsesWith(C);
12743 ++NumConstProp;
12744 Inst->eraseFromParent();
12745 continue;
12746 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000012747
12748
12749
12750 if (TD) {
12751 // See if we can constant fold its operands.
12752 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12753 i != e; ++i) {
12754 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12755 if (CE == 0) continue;
12756
12757 // If we already folded this constant, don't try again.
12758 if (!FoldedConstants.insert(CE))
12759 continue;
12760
12761 Constant *NewC =
12762 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12763 if (NewC && NewC != CE) {
12764 *i = NewC;
12765 MadeIRChange = true;
12766 }
12767 }
12768 }
12769
Devang Patel794140c2008-11-19 18:56:50 +000012770
Chris Lattnerb5663c72009-10-12 03:58:40 +000012771 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012772 }
12773
12774 // Recursively visit successors. If this is a branch or switch on a
12775 // constant, only visit the reachable successor.
12776 TerminatorInst *TI = BB->getTerminator();
12777 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12778 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12779 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012780 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012781 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012782 continue;
12783 }
12784 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12785 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12786 // See if this is an explicit destination.
12787 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12788 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012789 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012790 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012791 continue;
12792 }
12793
12794 // Otherwise it is the default destination.
12795 Worklist.push_back(SI->getSuccessor(0));
12796 continue;
12797 }
12798 }
12799
12800 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12801 Worklist.push_back(TI->getSuccessor(i));
12802 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000012803
12804 // Once we've found all of the instructions to add to instcombine's worklist,
12805 // add them in reverse order. This way instcombine will visit from the top
12806 // of the function down. This jives well with the way that it adds all uses
12807 // of instructions to the worklist after doing a transformation, thus avoiding
12808 // some N^2 behavior in pathological cases.
12809 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12810 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000012811
12812 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012813}
12814
12815bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000012816 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012817
Daniel Dunbar005975c2009-07-25 00:23:56 +000012818 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12819 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012820
12821 {
12822 // Do a depth-first traversal of the function, populate the worklist with
12823 // the reachable instructions. Ignore blocks that are not reachable. Keep
12824 // track of which blocks we visit.
12825 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000012826 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012827
12828 // Do a quick scan over the function. If we find any blocks that are
12829 // unreachable, remove any instructions inside of them. This prevents
12830 // the instcombine code from having to deal with some bad special cases.
12831 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12832 if (!Visited.count(BB)) {
12833 Instruction *Term = BB->getTerminator();
12834 while (Term != BB->begin()) { // Remove instrs bottom-up
12835 BasicBlock::iterator I = Term; --I;
12836
Chris Lattner8a6411c2009-08-23 04:37:46 +000012837 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000012838 // A debug intrinsic shouldn't force another iteration if we weren't
12839 // going to do one without it.
12840 if (!isa<DbgInfoIntrinsic>(I)) {
12841 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012842 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000012843 }
Devang Patele3829c82009-10-13 22:56:32 +000012844
Devang Patele3829c82009-10-13 22:56:32 +000012845 // If I is not void type then replaceAllUsesWith undef.
12846 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000012847 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000012848 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012849 I->eraseFromParent();
12850 }
12851 }
12852 }
12853
Chris Lattner5119c702009-08-30 05:55:36 +000012854 while (!Worklist.isEmpty()) {
12855 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012856 if (I == 0) continue; // skip null values.
12857
12858 // Check to see if we can DCE the instruction.
12859 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012860 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000012861 EraseInstFromFunction(*I);
12862 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012863 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012864 continue;
12865 }
12866
12867 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000012868 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12869 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12870 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012871
Chris Lattneree5839b2009-10-15 04:13:44 +000012872 // Add operands to the worklist.
12873 ReplaceInstUsesWith(*I, C);
12874 ++NumConstProp;
12875 EraseInstFromFunction(*I);
12876 MadeIRChange = true;
12877 continue;
12878 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012879
12880 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012881 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012882 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000012883 Instruction *UserInst = cast<Instruction>(I->use_back());
12884 BasicBlock *UserParent;
12885
12886 // Get the block the use occurs in.
12887 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12888 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12889 else
12890 UserParent = UserInst->getParent();
12891
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012892 if (UserParent != BB) {
12893 bool UserIsSuccessor = false;
12894 // See if the user is one of our successors.
12895 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12896 if (*SI == UserParent) {
12897 UserIsSuccessor = true;
12898 break;
12899 }
12900
12901 // If the user is one of our immediate successors, and if that successor
12902 // only has us as a predecessors (we'd have to split the critical edge
12903 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000012904 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012905 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000012906 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012907 }
12908 }
12909
Chris Lattnerc7694852009-08-30 07:44:24 +000012910 // Now that we have an instruction, try combining it to simplify it.
12911 Builder->SetInsertPoint(I->getParent(), I);
12912
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012913#ifndef NDEBUG
12914 std::string OrigI;
12915#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000012916 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000012917 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12918
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012919 if (Instruction *Result = visit(*I)) {
12920 ++NumCombined;
12921 // Should we replace the old instruction with a new one?
12922 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012923 DEBUG(errs() << "IC: Old = " << *I << '\n'
12924 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012925
12926 // Everything uses the new instruction now.
12927 I->replaceAllUsesWith(Result);
12928
12929 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000012930 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000012931 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012932
12933 // Move the name to the new instruction first.
12934 Result->takeName(I);
12935
12936 // Insert the new instruction into the basic block...
12937 BasicBlock *InstParent = I->getParent();
12938 BasicBlock::iterator InsertPos = I;
12939
12940 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12941 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12942 ++InsertPos;
12943
12944 InstParent->getInstList().insert(InsertPos, Result);
12945
Chris Lattner3183fb62009-08-30 06:13:40 +000012946 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012947 } else {
12948#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000012949 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12950 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012951#endif
12952
12953 // If the instruction was modified, it's possible that it is now dead.
12954 // if so, remove it.
12955 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012956 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012957 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000012958 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000012959 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012960 }
12961 }
Chris Lattner21d79e22009-08-31 06:57:37 +000012962 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012963 }
12964 }
12965
Chris Lattner5119c702009-08-30 05:55:36 +000012966 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000012967 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012968}
12969
12970
12971bool InstCombiner::runOnFunction(Function &F) {
12972 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000012973 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000012974 TD = getAnalysisIfAvailable<TargetData>();
12975
Chris Lattnerc7694852009-08-30 07:44:24 +000012976
12977 /// Builder - This is an IRBuilder that automatically inserts new
12978 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000012979 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12980 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattnerc7694852009-08-30 07:44:24 +000012981 InstCombineIRInserter(Worklist));
12982 Builder = &TheBuilder;
12983
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012984 bool EverMadeChange = false;
12985
12986 // Iterate while there is work to do.
12987 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012988 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012989 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000012990
12991 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012992 return EverMadeChange;
12993}
12994
12995FunctionPass *llvm::createInstructionCombiningPass() {
12996 return new InstCombiner();
12997}