blob: 07f7b2617c84b0d574e6e3e0467863c64deb0a77 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera9333562009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
51#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
56#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058#include "llvm/Support/MathExtras.h"
59#include "llvm/Support/PatternMatch.h"
Chris Lattneree5839b2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include "llvm/ADT/DenseMap.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/STLExtras.h"
67#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000068#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069using namespace llvm;
70using namespace llvm::PatternMatch;
71
72STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
77
78namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000079 /// InstCombineWorklist - This is the worklist management logic for
80 /// InstCombine.
81 class InstCombineWorklist {
82 SmallVector<Instruction*, 256> Worklist;
83 DenseMap<Instruction*, unsigned> WorklistMap;
84
85 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
86 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87 public:
88 InstCombineWorklist() {}
89
90 bool isEmpty() const { return Worklist.empty(); }
91
92 /// Add - Add the specified instruction to the worklist if it isn't already
93 /// in it.
94 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +000097 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000098 }
Chris Lattner5119c702009-08-30 05:55:36 +000099 }
100
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
103 Add(I);
104 }
105
Chris Lattnerb5663c72009-10-12 03:58:40 +0000106 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107 /// which should only be done when the worklist is empty and when the group
108 /// has no duplicates.
109 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110 assert(Worklist.empty() && "Worklist must be empty to add initial group");
111 Worklist.reserve(NumEntries+16);
112 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113 for (; NumEntries; --NumEntries) {
114 Instruction *I = List[NumEntries-1];
115 WorklistMap.insert(std::make_pair(I, Worklist.size()));
116 Worklist.push_back(I);
117 }
118 }
119
Chris Lattner3183fb62009-08-30 06:13:40 +0000120 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000121 void Remove(Instruction *I) {
122 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123 if (It == WorklistMap.end()) return; // Not in worklist.
124
125 // Don't bother moving everything down, just null out the slot.
126 Worklist[It->second] = 0;
127
128 WorklistMap.erase(It);
129 }
130
131 Instruction *RemoveOne() {
132 Instruction *I = Worklist.back();
133 Worklist.pop_back();
134 WorklistMap.erase(I);
135 return I;
136 }
137
Chris Lattner4796b622009-08-30 06:22:51 +0000138 /// AddUsersToWorkList - When an instruction is simplified, add all users of
139 /// the instruction to the work lists because they might get more simplified
140 /// now.
141 ///
142 void AddUsersToWorkList(Instruction &I) {
143 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144 UI != UE; ++UI)
145 Add(cast<Instruction>(*UI));
146 }
147
Chris Lattner5119c702009-08-30 05:55:36 +0000148
149 /// Zap - check that the worklist is empty and nuke the backing store for
150 /// the map if it is large.
151 void Zap() {
152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
153
154 // Do an explicit clear, this shrinks the map if needed.
155 WorklistMap.clear();
156 }
157 };
158} // end anonymous namespace.
159
160
161namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000162 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163 /// just like the normal insertion helper, but also adds any new instructions
164 /// to the instcombine worklist.
165 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166 InstCombineWorklist &Worklist;
167 public:
168 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169
170 void InsertHelper(Instruction *I, const Twine &Name,
171 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173 Worklist.Add(I);
174 }
175 };
176} // end anonymous namespace
177
178
179namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 TargetData *TD;
183 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000184 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000186 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000187 InstCombineWorklist Worklist;
188
Chris Lattnerc7694852009-08-30 07:44:24 +0000189 /// Builder - This is an IRBuilder that automatically inserts new
190 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +0000191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000192 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000193
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196
Owen Anderson175b6542009-07-22 00:24:57 +0000197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 public:
201 virtual bool runOnFunction(Function &F);
202
203 bool DoOneIteration(Function &F, unsigned ItNum);
204
205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 AU.addPreservedID(LCSSAID);
207 AU.setPreservesCFG();
208 }
209
Dan Gohmana80e2712009-07-21 23:21:54 +0000210 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211
212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
214 // Return Value:
215 // null - No change was made
216 // I - Change was made, I is still valid, I may be dead though
217 // otherwise - Change was made, replace I with returned instruction
218 //
219 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000220 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner93e6ff92009-11-04 08:05:20 +0000221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000223 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000225 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
232 Instruction *commonDivTransforms(BinaryOperator &I);
233 Instruction *commonIDivTransforms(BinaryOperator &I);
234 Instruction *visitUDiv(BinaryOperator &I);
235 Instruction *visitSDiv(BinaryOperator &I);
236 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000243 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *LHS,
257 ConstantInt *RHS);
258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
Chris Lattner258a2ffb2009-12-21 03:19:28 +0000260 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
261 ICmpInst::Predicate Pred);
Dan Gohman17f46f72009-07-28 01:40:03 +0000262 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 ICmpInst::Predicate Cond, Instruction &I);
264 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
265 BinaryOperator &I);
266 Instruction *commonCastTransforms(CastInst &CI);
267 Instruction *commonIntCastTransforms(CastInst &CI);
268 Instruction *commonPointerCastTransforms(CastInst &CI);
269 Instruction *visitTrunc(TruncInst &CI);
270 Instruction *visitZExt(ZExtInst &CI);
271 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000272 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000274 Instruction *visitFPToUI(FPToUIInst &FI);
275 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 Instruction *visitUIToFP(CastInst &CI);
277 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000278 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000279 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 Instruction *visitBitCast(BitCastInst &CI);
281 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
282 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000283 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000284 Instruction *visitSelectInst(SelectInst &SI);
285 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 Instruction *visitCallInst(CallInst &CI);
287 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner1cd526b2009-11-08 19:23:30 +0000288
289 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 Instruction *visitPHINode(PHINode &PN);
291 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandezb1687302009-10-23 21:09:37 +0000292 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez93946082009-10-24 04:23:03 +0000293 Instruction *visitFree(Instruction &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 Instruction *visitLoadInst(LoadInst &LI);
295 Instruction *visitStoreInst(StoreInst &SI);
296 Instruction *visitBranchInst(BranchInst &BI);
297 Instruction *visitSwitchInst(SwitchInst &SI);
298 Instruction *visitInsertElementInst(InsertElementInst &IE);
299 Instruction *visitExtractElementInst(ExtractElementInst &EI);
300 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000301 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302
303 // visitInstruction - Specify what to return for unhandled instructions...
304 Instruction *visitInstruction(Instruction &I) { return 0; }
305
306 private:
307 Instruction *visitCallSite(CallSite CS);
308 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000309 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000310 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
311 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000312 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000313 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
314
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315
316 public:
317 // InsertNewInstBefore - insert an instruction New before instruction Old
318 // in the program. Add the new instruction to the worklist.
319 //
320 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
321 assert(New && New->getParent() == 0 &&
322 "New instruction already inserted into a basic block!");
323 BasicBlock *BB = Old.getParent();
324 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000325 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 return New;
327 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000328
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 // ReplaceInstUsesWith - This method is to be used when an instruction is
330 // found to be dead, replacable with another preexisting expression. Here
331 // we add all uses of I to the worklist, replace all uses of I with the new
332 // value, then return I, so that the inst combiner will know that I was
333 // modified.
334 //
335 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000336 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000337
338 // If we are replacing the instruction with itself, this must be in a
339 // segment of unreachable code, so just clobber the instruction.
340 if (&I == V)
341 V = UndefValue::get(I.getType());
342
343 I.replaceAllUsesWith(V);
344 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 }
346
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 // EraseInstFromFunction - When dealing with an instruction that has side
348 // effects or produces a void value, we can't rely on DCE to delete the
349 // instruction. Instead, visit methods should return the value returned by
350 // this function.
351 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000352 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000353
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000355 // Make sure that we reprocess all operands now that we reduced their
356 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000357 if (I.getNumOperands() < 8) {
358 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
359 if (Instruction *Op = dyn_cast<Instruction>(*i))
360 Worklist.Add(Op);
361 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000362 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000364 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 return 0; // Don't do anything with FI
366 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000367
368 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
369 APInt &KnownOne, unsigned Depth = 0) const {
370 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
371 }
372
373 bool MaskedValueIsZero(Value *V, const APInt &Mask,
374 unsigned Depth = 0) const {
375 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
376 }
377 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
378 return llvm::ComputeNumSignBits(Op, TD, Depth);
379 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380
381 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382
383 /// SimplifyCommutative - This performs a few simplifications for
384 /// commutative operators.
385 bool SimplifyCommutative(BinaryOperator &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);
Chris Lattner38751f82009-11-01 20:04:24 +0000420 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000421
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422
423 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
424 ConstantInt *AndRHS, BinaryOperator &TheAnd);
425
426 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
427 bool isSub, Instruction &I);
428 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
429 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandezb1687302009-10-23 21:09:37 +0000430 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 Instruction *MatchBSwap(BinaryOperator &I);
432 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000433 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000434 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000435
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436
437 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000438
Dan Gohman8fd520a2009-06-15 22:12:54 +0000439 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000440 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000441 unsigned GetOrEnforceKnownAlignment(Value *V,
442 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000443
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 };
Chris Lattner5119c702009-08-30 05:55:36 +0000445} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446
Dan Gohman089efff2008-05-13 00:00:25 +0000447char InstCombiner::ID = 0;
448static RegisterPass<InstCombiner>
449X("instcombine", "Combine redundant instructions");
450
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451// getComplexity: Assign a complexity or rank value to LLVM Values...
452// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000453static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000455 if (BinaryOperator::isNeg(V) ||
456 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000457 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 return 3;
459 return 4;
460 }
461 if (isa<Argument>(V)) return 3;
462 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
463}
464
465// isOnlyUse - Return true if this instruction will be deleted if we stop using
466// it.
467static bool isOnlyUse(Value *V) {
468 return V->hasOneUse() || isa<Constant>(V);
469}
470
471// getPromotedType - Return the specified type promoted as it would be to pass
472// though a va_arg area...
473static const Type *getPromotedType(const Type *Ty) {
474 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
475 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000476 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 }
478 return Ty;
479}
480
Chris Lattnerd0011092009-11-10 07:23:37 +0000481/// ShouldChangeType - Return true if it is desirable to convert a computation
482/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
483/// type for example, or from a smaller to a larger illegal type.
484static bool ShouldChangeType(const Type *From, const Type *To,
485 const TargetData *TD) {
486 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
487
488 // If we don't have TD, we don't know if the source/dest are legal.
489 if (!TD) return false;
490
491 unsigned FromWidth = From->getPrimitiveSizeInBits();
492 unsigned ToWidth = To->getPrimitiveSizeInBits();
493 bool FromLegal = TD->isLegalInteger(FromWidth);
494 bool ToLegal = TD->isLegalInteger(ToWidth);
495
496 // If this is a legal integer from type, and the result would be an illegal
497 // type, don't do the transformation.
498 if (FromLegal && !ToLegal)
499 return false;
500
501 // Otherwise, if both are illegal, do not increase the size of the result. We
502 // do allow things like i160 -> i64, but not i64 -> i160.
503 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
504 return false;
505
506 return true;
507}
508
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000509/// getBitCastOperand - If the specified operand is a CastInst, a constant
510/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
511/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000513 if (Operator *O = dyn_cast<Operator>(V)) {
514 if (O->getOpcode() == Instruction::BitCast)
515 return O->getOperand(0);
516 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
517 if (GEP->hasAllZeroIndices())
518 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 return 0;
521}
522
523/// This function is a wrapper around CastInst::isEliminableCastPair. It
524/// simply extracts arguments and returns what that function returns.
525static Instruction::CastOps
526isEliminableCastPair(
527 const CastInst *CI, ///< The first cast instruction
528 unsigned opcode, ///< The opcode of the second cast instruction
529 const Type *DstTy, ///< The target type for the second cast instruction
530 TargetData *TD ///< The target data for pointer size
531) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000532
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
534 const Type *MidTy = CI->getType(); // B from above
535
536 // Get the opcodes of the two Cast instructions
537 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
538 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
539
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000540 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000541 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000542 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000543
544 // We don't want to form an inttoptr or ptrtoint that converts to an integer
545 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000546 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000547 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000548 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000549 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000550 Res = 0;
551
552 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553}
554
555/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
556/// in any code being generated. It does not require codegen if V is simple
557/// enough or if the cast can be folded into other casts.
558static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
559 const Type *Ty, TargetData *TD) {
560 if (V->getType() == Ty || isa<Constant>(V)) return false;
561
562 // If this is another cast that can be eliminated, it isn't codegen either.
563 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000564 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 return false;
566 return true;
567}
568
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569// SimplifyCommutative - This performs a few simplifications for commutative
570// operators:
571//
572// 1. Order operands such that they are listed from right (least complex) to
573// left (most complex). This puts constants before unary operators before
574// binary operators.
575//
576// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
577// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
578//
579bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
580 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000581 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 Changed = !I.swapOperands();
583
584 if (!I.isAssociative()) return Changed;
585 Instruction::BinaryOps Opcode = I.getOpcode();
586 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
587 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
588 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000589 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 cast<Constant>(I.getOperand(1)),
591 cast<Constant>(Op->getOperand(1)));
592 I.setOperand(0, Op->getOperand(0));
593 I.setOperand(1, Folded);
594 return true;
595 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
596 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
597 isOnlyUse(Op) && isOnlyUse(Op1)) {
598 Constant *C1 = cast<Constant>(Op->getOperand(1));
599 Constant *C2 = cast<Constant>(Op1->getOperand(1));
600
601 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000602 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000603 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 Op1->getOperand(0),
605 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000606 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 I.setOperand(0, New);
608 I.setOperand(1, Folded);
609 return true;
610 }
611 }
612 return Changed;
613}
614
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
616// if the LHS is a constant zero (which is the 'negate' form).
617//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000618static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000619 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620 return BinaryOperator::getNegArgument(V);
621
622 // Constants can be considered to be negated values if they can be folded.
623 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000624 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000625
626 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000628 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000629
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 return 0;
631}
632
Dan Gohman7ce405e2009-06-04 22:49:04 +0000633// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
634// instruction if the LHS is a constant negative zero (which is the 'negate'
635// form).
636//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000637static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000638 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000639 return BinaryOperator::getFNegArgument(V);
640
641 // Constants can be considered to be negated values if they can be folded.
642 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000643 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000644
645 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
646 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000647 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000648
649 return 0;
650}
651
Chris Lattner6e060db2009-10-26 15:40:07 +0000652/// isFreeToInvert - Return true if the specified value is free to invert (apply
653/// ~ to). This happens in cases where the ~ can be eliminated.
654static inline bool isFreeToInvert(Value *V) {
655 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000656 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000657 return true;
658
659 // Constants can be considered to be not'ed values.
660 if (isa<ConstantInt>(V))
661 return true;
662
663 // Compares can be inverted if they have a single use.
664 if (CmpInst *CI = dyn_cast<CmpInst>(V))
665 return CI->hasOneUse();
666
667 return false;
668}
669
670static inline Value *dyn_castNotVal(Value *V) {
671 // If this is not(not(x)) don't return that this is a not: we want the two
672 // not's to be folded first.
673 if (BinaryOperator::isNot(V)) {
674 Value *Operand = BinaryOperator::getNotArgument(V);
675 if (!isFreeToInvert(Operand))
676 return Operand;
677 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678
679 // Constants can be considered to be not'ed values...
680 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000681 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 return 0;
683}
684
Chris Lattner6e060db2009-10-26 15:40:07 +0000685
686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687// dyn_castFoldableMul - If this value is a multiply that can be folded into
688// other computations (because it has a constant operand), return the
689// non-constant operand of the multiply, and set CST to point to the multiplier.
690// Otherwise, return null.
691//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000692static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693 if (V->hasOneUse() && V->getType()->isInteger())
694 if (Instruction *I = dyn_cast<Instruction>(V)) {
695 if (I->getOpcode() == Instruction::Mul)
696 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
697 return I->getOperand(0);
698 if (I->getOpcode() == Instruction::Shl)
699 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
700 // The multiplier is really 1 << CST.
701 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
702 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000703 CST = ConstantInt::get(V->getType()->getContext(),
704 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 return I->getOperand(0);
706 }
707 }
708 return 0;
709}
710
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000712static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000713 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000714 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715}
716/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000717static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000718 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000719 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000721/// MultiplyOverflows - True if the multiply can not be expressed in an int
722/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000723static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000724 uint32_t W = C1->getBitWidth();
725 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
726 if (sign) {
727 LHSExt.sext(W * 2);
728 RHSExt.sext(W * 2);
729 } else {
730 LHSExt.zext(W * 2);
731 RHSExt.zext(W * 2);
732 }
733
734 APInt MulExt = LHSExt * RHSExt;
735
736 if (sign) {
737 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
738 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
739 return MulExt.slt(Min) || MulExt.sgt(Max);
740 } else
741 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
742}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744
745/// ShrinkDemandedConstant - Check to see if the specified operand of the
746/// specified instruction is a constant integer. If so, check to see if there
747/// are any bits set in the constant that are not demanded. If so, shrink the
748/// constant and return true.
749static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000750 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 assert(I && "No instruction?");
752 assert(OpNo < I->getNumOperands() && "Operand index too large");
753
754 // If the operand is not a constant integer, nothing to do.
755 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
756 if (!OpC) return false;
757
758 // If there are no bits set that aren't demanded, nothing to do.
759 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
760 if ((~Demanded & OpC->getValue()) == 0)
761 return false;
762
763 // This instruction is producing bits that are not demanded. Shrink the RHS.
764 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000765 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 return true;
767}
768
769// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
770// set of known zero and one bits, compute the maximum and minimum values that
771// could have the specified known zero and known one bits, returning them in
772// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000773static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774 const APInt& KnownOne,
775 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000776 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
777 KnownZero.getBitWidth() == Min.getBitWidth() &&
778 KnownZero.getBitWidth() == Max.getBitWidth() &&
779 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 APInt UnknownBits = ~(KnownZero|KnownOne);
781
782 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783 // bit if it is unknown.
784 Min = KnownOne;
785 Max = KnownOne|UnknownBits;
786
Dan Gohman7934d592009-04-25 17:12:48 +0000787 if (UnknownBits.isNegative()) { // Sign bit is unknown
788 Min.set(Min.getBitWidth()-1);
789 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790 }
791}
792
793// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
794// a set of known zero and one bits, compute the maximum and minimum values that
795// could have the specified known zero and known one bits, returning them in
796// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000797static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000798 const APInt &KnownOne,
799 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000800 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
801 KnownZero.getBitWidth() == Min.getBitWidth() &&
802 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
804 APInt UnknownBits = ~(KnownZero|KnownOne);
805
806 // The minimum value is when the unknown bits are all zeros.
807 Min = KnownOne;
808 // The maximum value is when the unknown bits are all ones.
809 Max = KnownOne|UnknownBits;
810}
811
Chris Lattner676c78e2009-01-31 08:15:18 +0000812/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
813/// SimplifyDemandedBits knows about. See if the instruction has any
814/// properties that allow us to simplify its operands.
815bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000816 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000817 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
818 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
819
820 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
821 KnownZero, KnownOne, 0);
822 if (V == 0) return false;
823 if (V == &Inst) return true;
824 ReplaceInstUsesWith(Inst, V);
825 return true;
826}
827
828/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
829/// specified instruction operand if possible, updating it in place. It returns
830/// true if it made any change and false otherwise.
831bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
832 APInt &KnownZero, APInt &KnownOne,
833 unsigned Depth) {
834 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
835 KnownZero, KnownOne, Depth);
836 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000837 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000838 return true;
839}
840
841
842/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
843/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844/// that only the bits set in DemandedMask of the result of V are ever used
845/// downstream. Consequently, depending on the mask and V, it may be possible
846/// to replace V with a constant or one of its operands. In such cases, this
847/// function does the replacement and returns true. In all other cases, it
848/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000849/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850/// to be zero in the expression. These are provided to potentially allow the
851/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
852/// the expression. KnownOne and KnownZero always follow the invariant that
853/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
854/// the bits in KnownOne and KnownZero may only be accurate for those bits set
855/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
856/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000857///
858/// This returns null if it did not change anything and it permits no
859/// simplification. This returns V itself if it did some simplification of V's
860/// operands based on the information about what bits are demanded. This returns
861/// some other non-null value if it found out that V is equal to another value
862/// in the context where the specified bits are demanded, but not for all users.
863Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
864 APInt &KnownZero, APInt &KnownOne,
865 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 assert(V != 0 && "Null pointer of Value???");
867 assert(Depth <= 6 && "Limit Search Depth");
868 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000869 const Type *VTy = V->getType();
870 assert((TD || !isa<PointerType>(VTy)) &&
871 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000872 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
873 (!VTy->isIntOrIntVector() ||
874 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000875 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000877 "Value *V, DemandedMask, KnownZero and KnownOne "
878 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
880 // We know all of the bits for a constant!
881 KnownOne = CI->getValue() & DemandedMask;
882 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000883 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 }
Dan Gohman7934d592009-04-25 17:12:48 +0000885 if (isa<ConstantPointerNull>(V)) {
886 // We know all of the bits for a constant!
887 KnownOne.clear();
888 KnownZero = DemandedMask;
889 return 0;
890 }
891
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000892 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000894 if (DemandedMask == 0) { // Not demanding any bits from V.
895 if (isa<UndefValue>(V))
896 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000897 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898 }
899
Chris Lattner08817332009-01-31 08:24:16 +0000900 if (Depth == 6) // Limit search depth.
901 return 0;
902
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000903 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
904 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
905
Dan Gohman7934d592009-04-25 17:12:48 +0000906 Instruction *I = dyn_cast<Instruction>(V);
907 if (!I) {
908 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
909 return 0; // Only analyze instructions.
910 }
911
Chris Lattner08817332009-01-31 08:24:16 +0000912 // If there are multiple uses of this value and we aren't at the root, then
913 // we can't do any simplifications of the operands, because DemandedMask
914 // only reflects the bits demanded by *one* of the users.
915 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000916 // Despite the fact that we can't simplify this instruction in all User's
917 // context, we can at least compute the knownzero/knownone bits, and we can
918 // do simplifications that apply to *just* the one user if we know that
919 // this instruction has a simpler value in that context.
920 if (I->getOpcode() == Instruction::And) {
921 // If either the LHS or the RHS are Zero, the result is zero.
922 ComputeMaskedBits(I->getOperand(1), DemandedMask,
923 RHSKnownZero, RHSKnownOne, Depth+1);
924 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
925 LHSKnownZero, LHSKnownOne, Depth+1);
926
927 // If all of the demanded bits are known 1 on one side, return the other.
928 // These bits cannot contribute to the result of the 'and' in this
929 // context.
930 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
931 (DemandedMask & ~LHSKnownZero))
932 return I->getOperand(0);
933 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
934 (DemandedMask & ~RHSKnownZero))
935 return I->getOperand(1);
936
937 // If all of the demanded bits in the inputs are known zeros, return zero.
938 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000939 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000940
941 } else if (I->getOpcode() == Instruction::Or) {
942 // We can simplify (X|Y) -> X or Y in the user's context if we know that
943 // only bits from X or Y are demanded.
944
945 // If either the LHS or the RHS are One, the result is One.
946 ComputeMaskedBits(I->getOperand(1), DemandedMask,
947 RHSKnownZero, RHSKnownOne, Depth+1);
948 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
949 LHSKnownZero, LHSKnownOne, Depth+1);
950
951 // If all of the demanded bits are known zero on one side, return the
952 // other. These bits cannot contribute to the result of the 'or' in this
953 // context.
954 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
955 (DemandedMask & ~LHSKnownOne))
956 return I->getOperand(0);
957 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
958 (DemandedMask & ~RHSKnownOne))
959 return I->getOperand(1);
960
961 // If all of the potentially set bits on one side are known to be set on
962 // the other side, just use the 'other' side.
963 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
964 (DemandedMask & (~RHSKnownZero)))
965 return I->getOperand(0);
966 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
967 (DemandedMask & (~LHSKnownZero)))
968 return I->getOperand(1);
969 }
970
Chris Lattner08817332009-01-31 08:24:16 +0000971 // Compute the KnownZero/KnownOne bits to simplify things downstream.
972 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
973 return 0;
974 }
975
976 // If this is the root being simplified, allow it to have multiple uses,
977 // just set the DemandedMask to all bits so that we can try to simplify the
978 // operands. This allows visitTruncInst (for example) to simplify the
979 // operand of a trunc without duplicating all the logic below.
980 if (Depth == 0 && !V->hasOneUse())
981 DemandedMask = APInt::getAllOnesValue(BitWidth);
982
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000984 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000985 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000986 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 case Instruction::And:
988 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000989 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
990 RHSKnownZero, RHSKnownOne, Depth+1) ||
991 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000993 return I;
994 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
995 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996
997 // If all of the demanded bits are known 1 on one side, return the other.
998 // These bits cannot contribute to the result of the 'and'.
999 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1000 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001001 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1003 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001004 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005
1006 // If all of the demanded bits in the inputs are known zeros, return zero.
1007 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +00001008 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009
1010 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001011 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001012 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013
1014 // Output known-1 bits are only known if set in both the LHS & RHS.
1015 RHSKnownOne &= LHSKnownOne;
1016 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1017 RHSKnownZero |= LHSKnownZero;
1018 break;
1019 case Instruction::Or:
1020 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +00001021 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1022 RHSKnownZero, RHSKnownOne, Depth+1) ||
1023 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001025 return I;
1026 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1027 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 // If all of the demanded bits are known zero on one side, return the other.
1030 // These bits cannot contribute to the result of the 'or'.
1031 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1032 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001033 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1035 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001036 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037
1038 // If all of the potentially set bits on one side are known to be set on
1039 // the other side, just use the 'other' side.
1040 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1041 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001042 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1044 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001045 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001049 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 // Output known-0 bits are only known if clear in both the LHS & RHS.
1052 RHSKnownZero &= LHSKnownZero;
1053 // Output known-1 are known to be set if set in either the LHS | RHS.
1054 RHSKnownOne |= LHSKnownOne;
1055 break;
1056 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001057 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1058 RHSKnownZero, RHSKnownOne, Depth+1) ||
1059 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001061 return I;
1062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1063 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064
1065 // If all of the demanded bits are known zero on one side, return the other.
1066 // These bits cannot contribute to the result of the 'xor'.
1067 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001068 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001070 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071
1072 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1073 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1074 (RHSKnownOne & LHSKnownOne);
1075 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1076 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1077 (RHSKnownOne & LHSKnownZero);
1078
1079 // If all of the demanded bits are known to be zero on one side or the
1080 // other, turn this into an *inclusive* or.
1081 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001082 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1083 Instruction *Or =
1084 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1085 I->getName());
1086 return InsertNewInstBefore(Or, *I);
1087 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001088
1089 // If all of the demanded bits on one side are known, and all of the set
1090 // bits on that side are also known to be set on the other side, turn this
1091 // into an AND, as we know the bits will be cleared.
1092 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1093 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1094 // all known
1095 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001096 Constant *AndC = Constant::getIntegerValue(VTy,
1097 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001099 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001100 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 }
1102 }
1103
1104 // If the RHS is a constant, see if we can simplify it.
1105 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001106 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001107 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108
Chris Lattnereefa89c2009-10-11 22:22:13 +00001109 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1110 // are flipping are known to be set, then the xor is just resetting those
1111 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1112 // simplifying both of them.
1113 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1114 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1115 isa<ConstantInt>(I->getOperand(1)) &&
1116 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1117 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1118 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1119 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1120 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1121
1122 Constant *AndC =
1123 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1124 Instruction *NewAnd =
1125 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1126 InsertNewInstBefore(NewAnd, *I);
1127
1128 Constant *XorC =
1129 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1130 Instruction *NewXor =
1131 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1132 return InsertNewInstBefore(NewXor, *I);
1133 }
1134
1135
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 RHSKnownZero = KnownZeroOut;
1137 RHSKnownOne = KnownOneOut;
1138 break;
1139 }
1140 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001141 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1) ||
1143 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001145 return I;
1146 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1147 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148
1149 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001150 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1151 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001152 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153
1154 // Only known if known in both the LHS and RHS.
1155 RHSKnownOne &= LHSKnownOne;
1156 RHSKnownZero &= LHSKnownZero;
1157 break;
1158 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001159 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 DemandedMask.zext(truncBf);
1161 RHSKnownZero.zext(truncBf);
1162 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001163 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001165 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166 DemandedMask.trunc(BitWidth);
1167 RHSKnownZero.trunc(BitWidth);
1168 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001169 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 break;
1171 }
1172 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001173 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001174 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001175
1176 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1177 if (const VectorType *SrcVTy =
1178 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1179 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1180 // Don't touch a bitcast between vectors of different element counts.
1181 return false;
1182 } else
1183 // Don't touch a scalar-to-vector bitcast.
1184 return false;
1185 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1186 // Don't touch a vector-to-scalar bitcast.
1187 return false;
1188
Chris Lattner676c78e2009-01-31 08:15:18 +00001189 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001191 return I;
1192 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 break;
1194 case Instruction::ZExt: {
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 DemandedMask.trunc(SrcBitWidth);
1199 RHSKnownZero.trunc(SrcBitWidth);
1200 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001201 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001203 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 DemandedMask.zext(BitWidth);
1205 RHSKnownZero.zext(BitWidth);
1206 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001207 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 // The top bits are known to be zero.
1209 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1210 break;
1211 }
1212 case Instruction::SExt: {
1213 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001214 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215
1216 APInt InputDemandedBits = DemandedMask &
1217 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1218
1219 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1220 // If any of the sign extended bits are demanded, we know that the sign
1221 // bit is demanded.
1222 if ((NewBits & DemandedMask) != 0)
1223 InputDemandedBits.set(SrcBitWidth-1);
1224
1225 InputDemandedBits.trunc(SrcBitWidth);
1226 RHSKnownZero.trunc(SrcBitWidth);
1227 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001230 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 InputDemandedBits.zext(BitWidth);
1232 RHSKnownZero.zext(BitWidth);
1233 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001234 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235
1236 // If the sign bit of the input is known set or clear, then we know the
1237 // top bits of the result.
1238
1239 // If the input sign bit is known zero, or if the NewBits are not demanded
1240 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001241 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001243 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1244 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1246 RHSKnownOne |= NewBits;
1247 }
1248 break;
1249 }
1250 case Instruction::Add: {
1251 // Figure out what the input bits are. If the top bits of the and result
1252 // are not demanded, then the add doesn't demand them from its input
1253 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001254 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255
1256 // If there is a constant on the RHS, there are a variety of xformations
1257 // we can do.
1258 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259 // If null, this should be simplified elsewhere. Some of the xforms here
1260 // won't work if the RHS is zero.
1261 if (RHS->isZero())
1262 break;
1263
1264 // If the top bit of the output is demanded, demand everything from the
1265 // input. Otherwise, we demand all the input bits except NLZ top bits.
1266 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1267
1268 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001271 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272
1273 // If the RHS of the add has bits set that can't affect the input, reduce
1274 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001275 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001276 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277
1278 // Avoid excess work.
1279 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1280 break;
1281
1282 // Turn it into OR if input bits are zero.
1283 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1284 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001285 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001287 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 }
1289
1290 // We can say something about the output known-zero and known-one bits,
1291 // depending on potential carries from the input constant and the
1292 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1293 // bits set and the RHS constant is 0x01001, then we know we have a known
1294 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1295
1296 // To compute this, we first compute the potential carry bits. These are
1297 // the bits which may be modified. I'm not aware of a better way to do
1298 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001299 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1301
1302 // Now that we know which bits have carries, compute the known-1/0 sets.
1303
1304 // Bits are known one if they are known zero in one operand and one in the
1305 // other, and there is no input carry.
1306 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1307 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1308
1309 // Bits are known zero if they are known zero in both operands and there
1310 // is no input carry.
1311 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1312 } else {
1313 // If the high-bits of this ADD are not demanded, then it does not demand
1314 // the high bits of its LHS or RHS.
1315 if (DemandedMask[BitWidth-1] == 0) {
1316 // Right fill the mask of bits for this ADD to demand the most
1317 // significant bit and all those below it.
1318 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001319 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1320 LHSKnownZero, LHSKnownOne, Depth+1) ||
1321 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001323 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 }
1325 }
1326 break;
1327 }
1328 case Instruction::Sub:
1329 // If the high-bits of this SUB are not demanded, then it does not demand
1330 // the high bits of its LHS or RHS.
1331 if (DemandedMask[BitWidth-1] == 0) {
1332 // Right fill the mask of bits for this SUB to demand the most
1333 // significant bit and all those below it.
1334 uint32_t NLZ = DemandedMask.countLeadingZeros();
1335 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1337 LHSKnownZero, LHSKnownOne, Depth+1) ||
1338 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001340 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001342 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1343 // the known zeros and ones.
1344 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 break;
1346 case Instruction::Shl:
1347 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1348 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1349 APInt DemandedMaskIn(DemandedMask.lshr(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 <<= ShiftAmt;
1355 RHSKnownOne <<= ShiftAmt;
1356 // low bits known zero.
1357 if (ShiftAmt)
1358 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1359 }
1360 break;
1361 case Instruction::LShr:
1362 // For a logical shift right
1363 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1364 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1365
1366 // Unsigned shift right.
1367 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001368 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001370 return I;
1371 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1373 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1374 if (ShiftAmt) {
1375 // Compute the new bits that are at the top now.
1376 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1377 RHSKnownZero |= HighBits; // high bits known zero.
1378 }
1379 }
1380 break;
1381 case Instruction::AShr:
1382 // If this is an arithmetic shift right and only the low-bit is set, we can
1383 // always convert this into a logical shr, even if the shift amount is
1384 // variable. The low bit of the shift cannot be an input sign bit unless
1385 // the shift amount is >= the size of the datatype, which is undefined.
1386 if (DemandedMask == 1) {
1387 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001388 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001390 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 }
1392
1393 // If the sign bit is the only bit demanded by this ashr, then there is no
1394 // need to do it, the shift doesn't change the high bit.
1395 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001396 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397
1398 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1399 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1400
1401 // Signed shift right.
1402 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1403 // If any of the "high bits" are demanded, we should set the sign bit as
1404 // demanded.
1405 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1406 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001407 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001409 return I;
1410 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 // Compute the new bits that are at the top now.
1412 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1413 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1414 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1415
1416 // Handle the sign bits.
1417 APInt SignBit(APInt::getSignBit(BitWidth));
1418 // Adjust to where it is now in the mask.
1419 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1420
1421 // If the input sign bit is known to be zero, or if none of the top bits
1422 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001423 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 (HighBits & ~DemandedMask) == HighBits) {
1425 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001426 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001428 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1430 RHSKnownOne |= HighBits;
1431 }
1432 }
1433 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001434 case Instruction::SRem:
1435 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001436 APInt RA = Rem->getValue().abs();
1437 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001438 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001439 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001440
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001441 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001442 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001443 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001444 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001445 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001446
1447 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1448 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001449
1450 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001451
Chris Lattner676c78e2009-01-31 08:15:18 +00001452 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001453 }
1454 }
1455 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001456 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001457 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1458 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001459 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1460 KnownZero2, KnownOne2, Depth+1) ||
1461 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001462 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001463 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001464
Chris Lattneree5417c2009-01-21 18:09:24 +00001465 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001466 Leaders = std::max(Leaders,
1467 KnownZero2.countLeadingOnes());
1468 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001469 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 }
Chris Lattner989ba312008-06-18 04:33:20 +00001471 case Instruction::Call:
1472 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1473 switch (II->getIntrinsicID()) {
1474 default: break;
1475 case Intrinsic::bswap: {
1476 // If the only bits demanded come from one byte of the bswap result,
1477 // just shift the input byte into position to eliminate the bswap.
1478 unsigned NLZ = DemandedMask.countLeadingZeros();
1479 unsigned NTZ = DemandedMask.countTrailingZeros();
1480
1481 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1482 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1483 // have 14 leading zeros, round to 8.
1484 NLZ &= ~7;
1485 NTZ &= ~7;
1486 // If we need exactly one byte, we can do this transformation.
1487 if (BitWidth-NLZ-NTZ == 8) {
1488 unsigned ResultBit = NTZ;
1489 unsigned InputBit = BitWidth-NTZ-8;
1490
1491 // Replace this with either a left or right shift to get the byte into
1492 // the right place.
1493 Instruction *NewVal;
1494 if (InputBit > ResultBit)
1495 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001496 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001497 else
1498 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001499 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001500 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001501 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001502 }
1503
1504 // TODO: Could compute known zero/one bits based on the input.
1505 break;
1506 }
1507 }
1508 }
Chris Lattner4946e222008-06-18 18:11:55 +00001509 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001510 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001511 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
1513 // If the client is only demanding bits that we know, return the known
1514 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001515 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1516 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 return false;
1518}
1519
1520
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001521/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001522/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523/// actually used by the caller. This method analyzes which elements of the
1524/// operand are undef and returns that information in UndefElts.
1525///
1526/// If the information about demanded elements can be used to simplify the
1527/// operation, the operation is simplified, then the resultant value is
1528/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001529Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1530 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 unsigned Depth) {
1532 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001533 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001534 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535
1536 if (isa<UndefValue>(V)) {
1537 // If the entire vector is undefined, just return this info.
1538 UndefElts = EltMask;
1539 return 0;
1540 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1541 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001542 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001544
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 UndefElts = 0;
1546 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1547 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001548 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549
1550 std::vector<Constant*> Elts;
1551 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001552 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001553 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001554 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1556 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001557 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558 } else { // Otherwise, defined.
1559 Elts.push_back(CP->getOperand(i));
1560 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001561
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001563 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001564 return NewCP != CP ? NewCP : 0;
1565 } else if (isa<ConstantAggregateZero>(V)) {
1566 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1567 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001568
1569 // Check if this is identity. If so, return 0 since we are not simplifying
1570 // anything.
1571 if (DemandedElts == ((1ULL << VWidth) -1))
1572 return 0;
1573
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001574 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001575 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001576 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001578 for (unsigned i = 0; i != VWidth; ++i) {
1579 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1580 Elts.push_back(Elt);
1581 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001582 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001583 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584 }
1585
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001586 // Limit search depth.
1587 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001588 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001589
1590 // If multiple users are using the root value, procede with
1591 // simplification conservatively assuming that all elements
1592 // are needed.
1593 if (!V->hasOneUse()) {
1594 // Quit if we find multiple users of a non-root value though.
1595 // They'll be handled when it's their turn to be visited by
1596 // the main instcombine process.
1597 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001599 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001600
1601 // Conservatively assume that all elements are needed.
1602 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001603 }
1604
1605 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001606 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607
1608 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001609 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610 Value *TmpV;
1611 switch (I->getOpcode()) {
1612 default: break;
1613
1614 case Instruction::InsertElement: {
1615 // If this is a variable index, we don't know which element it overwrites.
1616 // demand exactly the same input as we produce.
1617 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1618 if (Idx == 0) {
1619 // Note that we can't propagate undef elt info, because we don't know
1620 // which elt is getting updated.
1621 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1622 UndefElts2, Depth+1);
1623 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1624 break;
1625 }
1626
1627 // If this is inserting an element that isn't demanded, remove this
1628 // insertelement.
1629 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001630 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1631 Worklist.Add(I);
1632 return I->getOperand(0);
1633 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634
1635 // Otherwise, the element inserted overwrites whatever was there, so the
1636 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001637 APInt DemandedElts2 = DemandedElts;
1638 DemandedElts2.clear(IdxNo);
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640 UndefElts, Depth+1);
1641 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1642
1643 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001644 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001645 break;
1646 }
1647 case Instruction::ShuffleVector: {
1648 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001649 uint64_t LHSVWidth =
1650 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001651 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001652 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001653 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001654 unsigned MaskVal = Shuffle->getMaskValue(i);
1655 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001656 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001657 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001658 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001659 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001660 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001661 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001662 }
1663 }
1664 }
1665
Nate Begemanb4d176f2009-02-11 22:36:25 +00001666 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001667 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001668 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001669 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670
Nate Begemanb4d176f2009-02-11 22:36:25 +00001671 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001672 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1673 UndefElts3, Depth+1);
1674 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1675
1676 bool NewUndefElts = false;
1677 for (unsigned i = 0; i < VWidth; i++) {
1678 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001679 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001680 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001681 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001682 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001683 NewUndefElts = true;
1684 UndefElts.set(i);
1685 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001686 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001687 if (UndefElts3[MaskVal - LHSVWidth]) {
1688 NewUndefElts = true;
1689 UndefElts.set(i);
1690 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001691 }
1692 }
1693
1694 if (NewUndefElts) {
1695 // Add additional discovered undefs.
1696 std::vector<Constant*> Elts;
1697 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001698 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001699 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001700 else
Owen Anderson35b47072009-08-13 21:58:54 +00001701 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001702 Shuffle->getMaskValue(i)));
1703 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001704 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001705 MadeChange = true;
1706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001707 break;
1708 }
1709 case Instruction::BitCast: {
1710 // Vector->vector casts only.
1711 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1712 if (!VTy) break;
1713 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001714 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001715 unsigned Ratio;
1716
1717 if (VWidth == InVWidth) {
1718 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1719 // elements as are demanded of us.
1720 Ratio = 1;
1721 InputDemandedElts = DemandedElts;
1722 } else if (VWidth > InVWidth) {
1723 // Untested so far.
1724 break;
1725
1726 // If there are more elements in the result than there are in the source,
1727 // then an input element is live if any of the corresponding output
1728 // elements are live.
1729 Ratio = VWidth/InVWidth;
1730 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001731 if (DemandedElts[OutIdx])
1732 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 }
1734 } else {
1735 // Untested so far.
1736 break;
1737
1738 // If there are more elements in the source than there are in the result,
1739 // then an input element is live if the corresponding output element is
1740 // live.
1741 Ratio = InVWidth/VWidth;
1742 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001743 if (DemandedElts[InIdx/Ratio])
1744 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745 }
1746
1747 // div/rem demand all inputs, because they don't want divide by zero.
1748 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1749 UndefElts2, Depth+1);
1750 if (TmpV) {
1751 I->setOperand(0, TmpV);
1752 MadeChange = true;
1753 }
1754
1755 UndefElts = UndefElts2;
1756 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001757 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758 // If there are more elements in the result than there are in the source,
1759 // then an output element is undef if the corresponding input element is
1760 // undef.
1761 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001762 if (UndefElts2[OutIdx/Ratio])
1763 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001765 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001766 // If there are more elements in the source than there are in the result,
1767 // then a result element is undef if all of the corresponding input
1768 // elements are undef.
1769 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1770 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001771 if (!UndefElts2[InIdx]) // Not undef?
1772 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 }
1774 break;
1775 }
1776 case Instruction::And:
1777 case Instruction::Or:
1778 case Instruction::Xor:
1779 case Instruction::Add:
1780 case Instruction::Sub:
1781 case Instruction::Mul:
1782 // div/rem demand all inputs, because they don't want divide by zero.
1783 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1784 UndefElts, Depth+1);
1785 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1786 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1787 UndefElts2, Depth+1);
1788 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1789
1790 // Output elements are undefined if both are undefined. Consider things
1791 // like undef&0. The result is known zero, not undef.
1792 UndefElts &= UndefElts2;
1793 break;
1794
1795 case Instruction::Call: {
1796 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1797 if (!II) break;
1798 switch (II->getIntrinsicID()) {
1799 default: break;
1800
1801 // Binary vector operations that work column-wise. A dest element is a
1802 // function of the corresponding input elements from the two inputs.
1803 case Intrinsic::x86_sse_sub_ss:
1804 case Intrinsic::x86_sse_mul_ss:
1805 case Intrinsic::x86_sse_min_ss:
1806 case Intrinsic::x86_sse_max_ss:
1807 case Intrinsic::x86_sse2_sub_sd:
1808 case Intrinsic::x86_sse2_mul_sd:
1809 case Intrinsic::x86_sse2_min_sd:
1810 case Intrinsic::x86_sse2_max_sd:
1811 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1812 UndefElts, Depth+1);
1813 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1814 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1815 UndefElts2, Depth+1);
1816 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1817
1818 // If only the low elt is demanded and this is a scalarizable intrinsic,
1819 // scalarize it now.
1820 if (DemandedElts == 1) {
1821 switch (II->getIntrinsicID()) {
1822 default: break;
1823 case Intrinsic::x86_sse_sub_ss:
1824 case Intrinsic::x86_sse_mul_ss:
1825 case Intrinsic::x86_sse2_sub_sd:
1826 case Intrinsic::x86_sse2_mul_sd:
1827 // TODO: Lower MIN/MAX/ABS/etc
1828 Value *LHS = II->getOperand(1);
1829 Value *RHS = II->getOperand(2);
1830 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001831 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001832 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001833 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001834 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835
1836 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001837 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838 case Intrinsic::x86_sse_sub_ss:
1839 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001840 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001841 II->getName()), *II);
1842 break;
1843 case Intrinsic::x86_sse_mul_ss:
1844 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001845 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846 II->getName()), *II);
1847 break;
1848 }
1849
1850 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001851 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001852 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001853 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001855 return New;
1856 }
1857 }
1858
1859 // Output elements are undefined if both are undefined. Consider things
1860 // like undef&0. The result is known zero, not undef.
1861 UndefElts &= UndefElts2;
1862 break;
1863 }
1864 break;
1865 }
1866 }
1867 return MadeChange ? I : 0;
1868}
1869
Dan Gohman5d56fd42008-05-19 22:14:15 +00001870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871/// AssociativeOpt - Perform an optimization on an associative operator. This
1872/// function is designed to check a chain of associative operators for a
1873/// potential to apply a certain optimization. Since the optimization may be
1874/// applicable if the expression was reassociated, this checks the chain, then
1875/// reassociates the expression as necessary to expose the optimization
1876/// opportunity. This makes use of a special Functor, which must define
1877/// 'shouldApply' and 'apply' methods.
1878///
1879template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001880static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001881 unsigned Opcode = Root.getOpcode();
1882 Value *LHS = Root.getOperand(0);
1883
1884 // Quick check, see if the immediate LHS matches...
1885 if (F.shouldApply(LHS))
1886 return F.apply(Root);
1887
1888 // Otherwise, if the LHS is not of the same opcode as the root, return.
1889 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1890 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1891 // Should we apply this transform to the RHS?
1892 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1893
1894 // If not to the RHS, check to see if we should apply to the LHS...
1895 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1896 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1897 ShouldApply = true;
1898 }
1899
1900 // If the functor wants to apply the optimization to the RHS of LHSI,
1901 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1902 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 // Now all of the instructions are in the current basic block, go ahead
1904 // and perform the reassociation.
1905 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1906
1907 // First move the selected RHS to the LHS of the root...
1908 Root.setOperand(0, LHSI->getOperand(1));
1909
1910 // Make what used to be the LHS of the root be the user of the root...
1911 Value *ExtraOperand = TmpLHSI->getOperand(1);
1912 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001913 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001914 return 0;
1915 }
1916 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1917 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001918 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001919 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920 ARI = Root;
1921
1922 // Now propagate the ExtraOperand down the chain of instructions until we
1923 // get to LHSI.
1924 while (TmpLHSI != LHSI) {
1925 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1926 // Move the instruction to immediately before the chain we are
1927 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001928 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001929 ARI = NextLHSI;
1930
1931 Value *NextOp = NextLHSI->getOperand(1);
1932 NextLHSI->setOperand(1, ExtraOperand);
1933 TmpLHSI = NextLHSI;
1934 ExtraOperand = NextOp;
1935 }
1936
1937 // Now that the instructions are reassociated, have the functor perform
1938 // the transformation...
1939 return F.apply(Root);
1940 }
1941
1942 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1943 }
1944 return 0;
1945}
1946
Dan Gohman089efff2008-05-13 00:00:25 +00001947namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001948
Nick Lewycky27f6c132008-05-23 04:34:58 +00001949// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001950struct AddRHS {
1951 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001952 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1954 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001955 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001956 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001957 }
1958};
1959
1960// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1961// iff C1&C2 == 0
1962struct AddMaskingAnd {
1963 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001964 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965 bool shouldApply(Value *LHS) const {
1966 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001967 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001968 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969 }
1970 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001971 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001972 }
1973};
1974
Dan Gohman089efff2008-05-13 00:00:25 +00001975}
1976
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1978 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001979 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001980 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001981
1982 // Figure out if the constant is the left or the right argument.
1983 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1984 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1985
1986 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1987 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001988 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1989 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001990 }
1991
1992 Value *Op0 = SO, *Op1 = ConstOperand;
1993 if (!ConstIsRHS)
1994 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001995
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001997 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1998 SO->getName()+".op");
1999 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2000 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2001 SO->getName()+".cmp");
2002 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2003 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2004 SO->getName()+".cmp");
2005 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002006}
2007
2008// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2009// constant as the other operand, try to fold the binary operator into the
2010// select arguments. This also works for Cast instructions, which obviously do
2011// not have a second operand.
2012static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2013 InstCombiner *IC) {
2014 // Don't modify shared select instructions
2015 if (!SI->hasOneUse()) return 0;
2016 Value *TV = SI->getOperand(1);
2017 Value *FV = SI->getOperand(2);
2018
2019 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2020 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00002021 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022
2023 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2024 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2025
Gabor Greifd6da1d02008-04-06 20:25:17 +00002026 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2027 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028 }
2029 return 0;
2030}
2031
2032
Chris Lattnerf7843b72009-09-27 19:57:57 +00002033/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2034/// has a PHI node as operand #0, see if we can fold the instruction into the
2035/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00002036///
2037/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2038/// that would normally be unprofitable because they strongly encourage jump
2039/// threading.
2040Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2041 bool AllowAggressive) {
2042 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 PHINode *PN = cast<PHINode>(I.getOperand(0));
2044 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002045 if (NumPHIValues == 0 ||
2046 // We normally only transform phis with a single use, unless we're trying
2047 // hard to make jump threading happen.
2048 (!PN->hasOneUse() && !AllowAggressive))
2049 return 0;
2050
2051
Chris Lattnerf7843b72009-09-27 19:57:57 +00002052 // Check to see if all of the operands of the PHI are simple constants
2053 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002054 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2055 // bail out. We don't do arbitrary constant expressions here because moving
2056 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 BasicBlock *NonConstBB = 0;
2058 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002059 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2060 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061 if (NonConstBB) return 0; // More than one non-const value.
2062 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2063 NonConstBB = PN->getIncomingBlock(i);
2064
2065 // If the incoming non-constant value is in I's block, we have an infinite
2066 // loop.
2067 if (NonConstBB == I.getParent())
2068 return 0;
2069 }
2070
2071 // If there is exactly one non-constant value, we can insert a copy of the
2072 // operation in that block. However, if this is a critical edge, we would be
2073 // inserting the computation one some other paths (e.g. inside a loop). Only
2074 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002075 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2077 if (!BI || !BI->isUnconditional()) return 0;
2078 }
2079
2080 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002081 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002083 InsertNewInstBefore(NewPN, *PN);
2084 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085
2086 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002087 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2088 // We only currently try to fold the condition of a select when it is a phi,
2089 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002090 Value *TrueV = SI->getTrueValue();
2091 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002092 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002093 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002094 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002095 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2096 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002097 Value *InV = 0;
2098 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002099 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002100 } else {
2101 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002102 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2103 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002104 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002105 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002106 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002107 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002108 }
2109 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002110 Constant *C = cast<Constant>(I.getOperand(1));
2111 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002112 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002113 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2114 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002115 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002116 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002117 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 } else {
2119 assert(PN->getIncomingBlock(i) == NonConstBB);
2120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002121 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 PN->getIncomingValue(i), C, "phitmp",
2123 NonConstBB->getTerminator());
2124 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002125 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002126 CI->getPredicate(),
2127 PN->getIncomingValue(i), C, "phitmp",
2128 NonConstBB->getTerminator());
2129 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002130 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002131
2132 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002133 }
2134 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2135 }
2136 } else {
2137 CastInst *CI = cast<CastInst>(&I);
2138 const Type *RetTy = CI->getType();
2139 for (unsigned i = 0; i != NumPHIValues; ++i) {
2140 Value *InV;
2141 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002142 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143 } else {
2144 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002145 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002146 I.getType(), "phitmp",
2147 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002148 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002149 }
2150 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2151 }
2152 }
2153 return ReplaceInstUsesWith(I, NewPN);
2154}
2155
Chris Lattner55476162008-01-29 06:52:45 +00002156
Chris Lattner3554f972008-05-20 05:46:13 +00002157/// WillNotOverflowSignedAdd - Return true if we can prove that:
2158/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2159/// This basically requires proving that the add in the original type would not
2160/// overflow to change the sign bit or have a carry out.
2161bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2162 // There are different heuristics we can use for this. Here are some simple
2163 // ones.
2164
2165 // Add has the property that adding any two 2's complement numbers can only
2166 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner96076f72009-11-27 17:42:22 +00002167 // have at least two sign bits, we know that the addition of the two values
2168 // will sign extend fine.
Chris Lattner3554f972008-05-20 05:46:13 +00002169 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2170 return true;
2171
2172
2173 // If one of the operands only has one non-zero bit, and if the other operand
2174 // has a known-zero bit in a more significant place than it (not including the
2175 // sign bit) the ripple may go up to and fill the zero, but won't change the
2176 // sign. For example, (X & ~4) + 1.
2177
2178 // TODO: Implement.
2179
2180 return false;
2181}
2182
Chris Lattner55476162008-01-29 06:52:45 +00002183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002184Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2185 bool Changed = SimplifyCommutative(I);
2186 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2187
Chris Lattner96076f72009-11-27 17:42:22 +00002188 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2189 I.hasNoUnsignedWrap(), TD))
2190 return ReplaceInstUsesWith(I, V);
2191
2192
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2195 // X + (signbit) --> X ^ signbit
2196 const APInt& Val = CI->getValue();
2197 uint32_t BitWidth = Val.getBitWidth();
2198 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002199 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200
2201 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2202 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002203 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002204 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002205
Eli Friedmana21526d2009-07-13 22:27:52 +00002206 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002207 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002208 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002209 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 }
2211
2212 if (isa<PHINode>(LHS))
2213 if (Instruction *NV = FoldOpIntoPhi(I))
2214 return NV;
2215
2216 ConstantInt *XorRHS = 0;
2217 Value *XorLHS = 0;
2218 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002219 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002220 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2222
2223 uint32_t Size = TySizeBits / 2;
2224 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2225 APInt CFF80Val(-C0080Val);
2226 do {
2227 if (TySizeBits > Size) {
2228 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2229 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2230 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2231 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2232 // This is a sign extend if the top bits are known zero.
2233 if (!MaskedValueIsZero(XorLHS,
2234 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2235 Size = 0; // Not a sign ext, but can't be any others either.
2236 break;
2237 }
2238 }
2239 Size >>= 1;
2240 C0080Val = APIntOps::lshr(C0080Val, Size);
2241 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2242 } while (Size >= 1);
2243
2244 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002245 // with funny bit widths then this switch statement should be removed. It
2246 // is just here to get the size of the "middle" type back up to something
2247 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002248 const Type *MiddleType = 0;
2249 switch (Size) {
2250 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002251 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2252 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2253 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254 }
2255 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002256 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257 return new SExtInst(NewTrunc, I.getType(), I.getName());
2258 }
2259 }
2260 }
2261
Owen Anderson35b47072009-08-13 21:58:54 +00002262 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002263 return BinaryOperator::CreateXor(LHS, RHS);
2264
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002265 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002266 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002267 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002268 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269
2270 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2271 if (RHSI->getOpcode() == Instruction::Sub)
2272 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2273 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2274 }
2275 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2276 if (LHSI->getOpcode() == Instruction::Sub)
2277 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2278 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2279 }
2280 }
2281
2282 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002283 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002284 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002285 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002286 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002287 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002288 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002289 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002290 }
2291
Gabor Greifa645dd32008-05-16 19:29:10 +00002292 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002293 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294
2295 // A + -B --> A - B
2296 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002297 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002298 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299
2300
2301 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002302 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002304 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305
2306 // X*C1 + X*C2 --> X * (C1+C2)
2307 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002308 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002309 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 }
2311
2312 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002313 if (dyn_castFoldableMul(RHS, C2) == LHS)
2314 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315
2316 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002317 if (dyn_castNotVal(LHS) == RHS ||
2318 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002319 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320
2321
2322 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002323 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2324 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002326
2327 // A+B --> A|B iff A and B have no bits set in common.
2328 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2329 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2330 APInt LHSKnownOne(IT->getBitWidth(), 0);
2331 APInt LHSKnownZero(IT->getBitWidth(), 0);
2332 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2333 if (LHSKnownZero != 0) {
2334 APInt RHSKnownOne(IT->getBitWidth(), 0);
2335 APInt RHSKnownZero(IT->getBitWidth(), 0);
2336 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2337
2338 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002339 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002340 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002341 }
2342 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343
Nick Lewycky83598a72008-02-03 07:42:09 +00002344 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002345 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002346 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002347 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2348 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002349 if (W != Y) {
2350 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002351 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002352 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002353 std::swap(W, X);
2354 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002355 std::swap(Y, Z);
2356 std::swap(W, X);
2357 }
2358 }
2359
2360 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002361 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002362 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002363 }
2364 }
2365 }
2366
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2368 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002369 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002370 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002371
2372 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002373 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002374 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002375 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002376 if (Anded == CRHS) {
2377 // See if all bits from the first bit set in the Add RHS up are included
2378 // in the mask. First, get the rightmost bit.
2379 const APInt& AddRHSV = CRHS->getValue();
2380
2381 // Form a mask of all bits from the lowest bit added through the top.
2382 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2383
2384 // See if the and mask includes all of these bits.
2385 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2386
2387 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2388 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002389 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391 }
2392 }
2393 }
2394
2395 // Try to fold constant add into select arguments.
2396 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2397 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2398 return R;
2399 }
2400
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002401 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002402 {
2403 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002404 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002405 if (!SI) {
2406 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002407 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002408 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002409 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002410 Value *TV = SI->getTrueValue();
2411 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002412 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002413
2414 // Can we fold the add into the argument of the select?
2415 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002416 if (match(FV, m_Zero()) &&
2417 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002418 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002419 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002420 if (match(TV, m_Zero()) &&
2421 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002422 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002423 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002424 }
2425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426
Chris Lattner3554f972008-05-20 05:46:13 +00002427 // Check for (add (sext x), y), see if we can merge this into an
2428 // integer add followed by a sext.
2429 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2430 // (add (sext x), cst) --> (sext (add x, cst'))
2431 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2432 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002433 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002434 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002435 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002436 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002438 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2439 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002440 return new SExtInst(NewAdd, I.getType());
2441 }
2442 }
2443
2444 // (add (sext x), (sext y)) --> (sext (add int x, y))
2445 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2446 // Only do this if x/y have the same type, if at last one of them has a
2447 // single use (so we don't increase the number of sexts), and if the
2448 // integer add will not overflow.
2449 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2450 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2451 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2452 RHSConv->getOperand(0))) {
2453 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002454 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2455 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002456 return new SExtInst(NewAdd, I.getType());
2457 }
2458 }
2459 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002460
2461 return Changed ? &I : 0;
2462}
2463
2464Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2465 bool Changed = SimplifyCommutative(I);
2466 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2467
2468 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2469 // X + 0 --> X
2470 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002471 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002472 (I.getType())->getValueAPF()))
2473 return ReplaceInstUsesWith(I, LHS);
2474 }
2475
2476 if (isa<PHINode>(LHS))
2477 if (Instruction *NV = FoldOpIntoPhi(I))
2478 return NV;
2479 }
2480
2481 // -A + B --> B - A
2482 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002483 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002484 return BinaryOperator::CreateFSub(RHS, LHSV);
2485
2486 // A + -B --> A - B
2487 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002488 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002489 return BinaryOperator::CreateFSub(LHS, V);
2490
2491 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2492 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2493 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2494 return ReplaceInstUsesWith(I, LHS);
2495
Chris Lattner3554f972008-05-20 05:46:13 +00002496 // Check for (add double (sitofp x), y), see if we can merge this into an
2497 // integer add followed by a promotion.
2498 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2499 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2500 // ... if the constant fits in the integer value. This is useful for things
2501 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2502 // requires a constant pool load, and generally allows the add to be better
2503 // instcombined.
2504 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2505 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002506 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002507 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002508 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002509 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2510 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002511 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2512 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002513 return new SIToFPInst(NewAdd, I.getType());
2514 }
2515 }
2516
2517 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2518 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2519 // Only do this if x/y have the same type, if at last one of them has a
2520 // single use (so we don't increase the number of int->fp conversions),
2521 // and if the integer add will not overflow.
2522 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2523 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2524 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2525 RHSConv->getOperand(0))) {
2526 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002527 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +00002528 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002529 return new SIToFPInst(NewAdd, I.getType());
2530 }
2531 }
2532 }
2533
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002534 return Changed ? &I : 0;
2535}
2536
Chris Lattner93e6ff92009-11-04 08:05:20 +00002537
2538/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2539/// code necessary to compute the offset from the base pointer (without adding
2540/// in the base pointer). Return the result as a signed integer of intptr size.
2541static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2542 TargetData &TD = *IC.getTargetData();
2543 gep_type_iterator GTI = gep_type_begin(GEP);
2544 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2545 Value *Result = Constant::getNullValue(IntPtrTy);
2546
2547 // Build a mask for high order bits.
2548 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2549 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2550
2551 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2552 ++i, ++GTI) {
2553 Value *Op = *i;
2554 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2555 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2556 if (OpC->isZero()) continue;
2557
2558 // Handle a struct index, which adds its field offset to the pointer.
2559 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2560 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2561
2562 Result = IC.Builder->CreateAdd(Result,
2563 ConstantInt::get(IntPtrTy, Size),
2564 GEP->getName()+".offs");
2565 continue;
2566 }
2567
2568 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2569 Constant *OC =
2570 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2571 Scale = ConstantExpr::getMul(OC, Scale);
2572 // Emit an add instruction.
2573 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2574 continue;
2575 }
2576 // Convert to correct type.
2577 if (Op->getType() != IntPtrTy)
2578 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2579 if (Size != 1) {
2580 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2581 // We'll let instcombine(mul) convert this to a shl if possible.
2582 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2583 }
2584
2585 // Emit an add instruction.
2586 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2587 }
2588 return Result;
2589}
2590
2591
2592/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2593/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2594/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2595/// be complex, and scales are involved. The above expression would also be
2596/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2597/// This later form is less amenable to optimization though, and we are allowed
2598/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2599///
2600/// If we can't emit an optimized form for this expression, this returns null.
2601///
2602static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2603 InstCombiner &IC) {
2604 TargetData &TD = *IC.getTargetData();
2605 gep_type_iterator GTI = gep_type_begin(GEP);
2606
2607 // Check to see if this gep only has a single variable index. If so, and if
2608 // any constant indices are a multiple of its scale, then we can compute this
2609 // in terms of the scale of the variable index. For example, if the GEP
2610 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2611 // because the expression will cross zero at the same point.
2612 unsigned i, e = GEP->getNumOperands();
2613 int64_t Offset = 0;
2614 for (i = 1; i != e; ++i, ++GTI) {
2615 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2616 // Compute the aggregate offset of constant indices.
2617 if (CI->isZero()) continue;
2618
2619 // Handle a struct index, which adds its field offset to the pointer.
2620 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2621 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2622 } else {
2623 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2624 Offset += Size*CI->getSExtValue();
2625 }
2626 } else {
2627 // Found our variable index.
2628 break;
2629 }
2630 }
2631
2632 // If there are no variable indices, we must have a constant offset, just
2633 // evaluate it the general way.
2634 if (i == e) return 0;
2635
2636 Value *VariableIdx = GEP->getOperand(i);
2637 // Determine the scale factor of the variable element. For example, this is
2638 // 4 if the variable index is into an array of i32.
2639 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2640
2641 // Verify that there are no other variable indices. If so, emit the hard way.
2642 for (++i, ++GTI; i != e; ++i, ++GTI) {
2643 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2644 if (!CI) return 0;
2645
2646 // Compute the aggregate offset of constant indices.
2647 if (CI->isZero()) continue;
2648
2649 // Handle a struct index, which adds its field offset to the pointer.
2650 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2651 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2652 } else {
2653 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2654 Offset += Size*CI->getSExtValue();
2655 }
2656 }
2657
2658 // Okay, we know we have a single variable index, which must be a
2659 // pointer/array/vector index. If there is no offset, life is simple, return
2660 // the index.
2661 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2662 if (Offset == 0) {
2663 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2664 // we don't need to bother extending: the extension won't affect where the
2665 // computation crosses zero.
2666 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2667 VariableIdx = new TruncInst(VariableIdx,
2668 TD.getIntPtrType(VariableIdx->getContext()),
2669 VariableIdx->getName(), &I);
2670 return VariableIdx;
2671 }
2672
2673 // Otherwise, there is an index. The computation we will do will be modulo
2674 // the pointer size, so get it.
2675 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2676
2677 Offset &= PtrSizeMask;
2678 VariableScale &= PtrSizeMask;
2679
2680 // To do this transformation, any constant index must be a multiple of the
2681 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2682 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2683 // multiple of the variable scale.
2684 int64_t NewOffs = Offset / (int64_t)VariableScale;
2685 if (Offset != NewOffs*(int64_t)VariableScale)
2686 return 0;
2687
2688 // Okay, we can do this evaluation. Start by converting the index to intptr.
2689 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2690 if (VariableIdx->getType() != IntPtrTy)
2691 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2692 true /*SExt*/,
2693 VariableIdx->getName(), &I);
2694 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2695 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2696}
2697
2698
2699/// Optimize pointer differences into the same array into a size. Consider:
2700/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2701/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2702///
2703Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2704 const Type *Ty) {
2705 assert(TD && "Must have target data info for this");
2706
2707 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2708 // this.
2709 bool Swapped;
2710 GetElementPtrInst *GEP;
2711
2712 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2713 GEP->getOperand(0) == RHS)
2714 Swapped = false;
2715 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2716 GEP->getOperand(0) == LHS)
2717 Swapped = true;
2718 else
2719 return 0;
2720
2721 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2722
2723 // Emit the offset of the GEP and an intptr_t.
2724 Value *Result = EmitGEPOffset(GEP, *this);
2725
2726 // If we have p - gep(p, ...) then we have to negate the result.
2727 if (Swapped)
2728 Result = Builder->CreateNeg(Result, "diff.neg");
2729
2730 return Builder->CreateIntCast(Result, Ty, true);
2731}
2732
2733
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2736
Dan Gohman7ce405e2009-06-04 22:49:04 +00002737 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002738 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739
Chris Lattner93e6ff92009-11-04 08:05:20 +00002740 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002741 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002743
2744 if (isa<UndefValue>(Op0))
2745 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2746 if (isa<UndefValue>(Op1))
2747 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner93e6ff92009-11-04 08:05:20 +00002748 if (I.getType() == Type::getInt1Ty(*Context))
2749 return BinaryOperator::CreateXor(Op0, Op1);
2750
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002751 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00002752 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002754 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755
2756 // C - ~X == X + (1+C)
2757 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002758 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002759 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002760
2761 // -(X >>u 31) -> (X >>s 31)
2762 // -(X >>s 31) -> (X >>u 31)
2763 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002764 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 if (SI->getOpcode() == Instruction::LShr) {
2766 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2767 // Check to see if we are shifting out everything but the sign bit.
2768 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2769 SI->getType()->getPrimitiveSizeInBits()-1) {
2770 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002771 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002772 SI->getOperand(0), CU, SI->getName());
2773 }
2774 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002775 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2777 // Check to see if we are shifting out everything but the sign bit.
2778 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2779 SI->getType()->getPrimitiveSizeInBits()-1) {
2780 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002781 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 SI->getOperand(0), CU, SI->getName());
2783 }
2784 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002785 }
2786 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787 }
2788
2789 // Try to fold constant sub into select arguments.
2790 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2791 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2792 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002793
2794 // C - zext(bool) -> bool ? C - 1 : C
2795 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002796 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002797 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 }
2799
2800 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002801 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002803 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002804 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002806 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002807 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002808 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2809 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2810 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002811 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002812 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 }
2814 }
2815
2816 if (Op1I->hasOneUse()) {
2817 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2818 // is not used by anyone else...
2819 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002820 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002821 // Swap the two operands of the subexpr...
2822 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2823 Op1I->setOperand(0, IIOp1);
2824 Op1I->setOperand(1, IIOp0);
2825
2826 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002827 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828 }
2829
2830 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2831 //
2832 if (Op1I->getOpcode() == Instruction::And &&
2833 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2834 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2835
Chris Lattnerc7694852009-08-30 07:44:24 +00002836 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002837 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002838 }
2839
2840 // 0 - (X sdiv C) -> (X sdiv -C)
2841 if (Op1I->getOpcode() == Instruction::SDiv)
2842 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2843 if (CSI->isZero())
2844 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002845 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002846 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002847
2848 // X - X*C --> X * (1-C)
2849 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002850 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002851 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002852 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002853 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002854 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 }
2856 }
2857 }
2858
Dan Gohman7ce405e2009-06-04 22:49:04 +00002859 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2860 if (Op0I->getOpcode() == Instruction::Add) {
2861 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2862 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2863 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2864 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2865 } else if (Op0I->getOpcode() == Instruction::Sub) {
2866 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002867 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002868 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002869 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871
2872 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002873 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002874 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002875 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002876
2877 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002878 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002879 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002880 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002881
2882 // Optimize pointer differences into the same array into a size. Consider:
2883 // &A[10] - &A[0]: we should compile this to "10".
2884 if (TD) {
2885 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2886 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2887 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2888 RHS->getOperand(0),
2889 I.getType()))
2890 return ReplaceInstUsesWith(I, Res);
2891
2892 // trunc(p)-trunc(q) -> trunc(p-q)
2893 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2894 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2895 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2896 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2897 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2898 RHS->getOperand(0),
2899 I.getType()))
2900 return ReplaceInstUsesWith(I, Res);
2901 }
2902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 return 0;
2904}
2905
Dan Gohman7ce405e2009-06-04 22:49:04 +00002906Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908
2909 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002910 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002911 return BinaryOperator::CreateFAdd(Op0, V);
2912
2913 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2914 if (Op1I->getOpcode() == Instruction::FAdd) {
2915 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002916 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002917 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002918 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002919 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002920 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002921 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002922 }
2923
2924 return 0;
2925}
2926
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002927/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2928/// comparison only checks the sign bit. If it only checks the sign bit, set
2929/// TrueIfSigned if the result of the comparison is true when the input value is
2930/// signed.
2931static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2932 bool &TrueIfSigned) {
2933 switch (pred) {
2934 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2935 TrueIfSigned = true;
2936 return RHS->isZero();
2937 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2938 TrueIfSigned = true;
2939 return RHS->isAllOnesValue();
2940 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2941 TrueIfSigned = false;
2942 return RHS->isAllOnesValue();
2943 case ICmpInst::ICMP_UGT:
2944 // True if LHS u> RHS and RHS == high-bit-mask - 1
2945 TrueIfSigned = true;
2946 return RHS->getValue() ==
2947 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2948 case ICmpInst::ICMP_UGE:
2949 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2950 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002951 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952 default:
2953 return false;
2954 }
2955}
2956
2957Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2958 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960
Chris Lattner3508c5c2009-10-11 21:36:10 +00002961 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002963
Chris Lattner6438c582009-10-11 07:53:15 +00002964 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002965 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2966 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967
2968 // ((X << C1)*C2) == (X * (C2 << C1))
2969 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2970 if (SI->getOpcode() == Instruction::Shl)
2971 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002972 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002973 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974
2975 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00002976 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977 if (CI->equalsInt(1)) // X * 1 == X
2978 return ReplaceInstUsesWith(I, Op0);
2979 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002980 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981
2982 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2983 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002984 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002985 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002987 } else if (isa<VectorType>(Op1C->getType())) {
2988 if (Op1C->isNullValue())
2989 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00002990
Chris Lattner3508c5c2009-10-11 21:36:10 +00002991 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00002992 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002993 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002994
2995 // As above, vector X*splat(1.0) -> X in all defined cases.
2996 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002997 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2998 if (CI->equalsInt(1))
2999 return ReplaceInstUsesWith(I, Op0);
3000 }
3001 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003002 }
3003
3004 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3005 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003006 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003008 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3009 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011
3012 }
3013
3014 // Try to fold constant mul into select arguments.
3015 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3016 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3017 return R;
3018
3019 if (isa<PHINode>(Op0))
3020 if (Instruction *NV = FoldOpIntoPhi(I))
3021 return NV;
3022 }
3023
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003024 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003025 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00003026 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027
Nick Lewycky1c246402008-11-21 07:33:58 +00003028 // (X / Y) * Y = X - (X % Y)
3029 // (X / Y) * -Y = (X % Y) - X
3030 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003031 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00003032 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3033 if (!BO ||
3034 (BO->getOpcode() != Instruction::UDiv &&
3035 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003036 Op1C = Op0;
3037 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00003038 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003039 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00003040 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003041 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00003042 (BO->getOpcode() == Instruction::UDiv ||
3043 BO->getOpcode() == Instruction::SDiv)) {
3044 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3045
Dan Gohman07878902009-08-12 16:33:09 +00003046 // If the division is exact, X % Y is zero.
3047 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3048 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003049 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00003050 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003051 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00003052 }
3053
Chris Lattnerc7694852009-08-30 07:44:24 +00003054 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00003055 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00003056 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003057 else
Chris Lattnerc7694852009-08-30 07:44:24 +00003058 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003059 Rem->takeName(BO);
3060
Chris Lattner3508c5c2009-10-11 21:36:10 +00003061 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00003062 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00003063 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003064 }
3065 }
3066
Chris Lattner6438c582009-10-11 07:53:15 +00003067 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00003068 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003069 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003070
Chris Lattner6438c582009-10-11 07:53:15 +00003071 // X*(1 << Y) --> X << Y
3072 // (1 << Y)*X --> X << Y
3073 {
3074 Value *Y;
3075 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003076 return BinaryOperator::CreateShl(Op1, Y);
3077 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00003078 return BinaryOperator::CreateShl(Op0, Y);
3079 }
3080
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081 // If one of the operands of the multiply is a cast from a boolean value, then
3082 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00003083 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3084 if (!isa<VectorType>(I.getType())) {
3085 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00003086 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00003087
Chris Lattner4ca76f72009-10-11 21:29:45 +00003088 Value *BoolCast = 0, *OtherOp = 0;
3089 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003090 BoolCast = Op0, OtherOp = Op1;
3091 else if (MaskedValueIsZero(Op1, Negative2))
3092 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00003093
Chris Lattner291872e2009-10-11 21:22:21 +00003094 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00003095 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3096 BoolCast, "tmp");
3097 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098 }
3099 }
3100
3101 return Changed ? &I : 0;
3102}
3103
Dan Gohman7ce405e2009-06-04 22:49:04 +00003104Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3105 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003106 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00003107
3108 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00003109 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3110 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003111 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3112 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3113 if (Op1F->isExactlyValue(1.0))
3114 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00003115 } else if (isa<VectorType>(Op1C->getType())) {
3116 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003117 // As above, vector X*splat(1.0) -> X in all defined cases.
3118 if (Constant *Splat = Op1V->getSplatValue()) {
3119 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3120 if (F->isExactlyValue(1.0))
3121 return ReplaceInstUsesWith(I, Op0);
3122 }
3123 }
3124 }
3125
3126 // Try to fold constant mul into select arguments.
3127 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3128 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3129 return R;
3130
3131 if (isa<PHINode>(Op0))
3132 if (Instruction *NV = FoldOpIntoPhi(I))
3133 return NV;
3134 }
3135
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003136 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003137 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003138 return BinaryOperator::CreateFMul(Op0v, Op1v);
3139
3140 return Changed ? &I : 0;
3141}
3142
Chris Lattner76972db2008-07-14 00:15:52 +00003143/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3144/// instruction.
3145bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3146 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3147
3148 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3149 int NonNullOperand = -1;
3150 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3151 if (ST->isNullValue())
3152 NonNullOperand = 2;
3153 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3154 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3155 if (ST->isNullValue())
3156 NonNullOperand = 1;
3157
3158 if (NonNullOperand == -1)
3159 return false;
3160
3161 Value *SelectCond = SI->getOperand(0);
3162
3163 // Change the div/rem to use 'Y' instead of the select.
3164 I.setOperand(1, SI->getOperand(NonNullOperand));
3165
3166 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3167 // problem. However, the select, or the condition of the select may have
3168 // multiple uses. Based on our knowledge that the operand must be non-zero,
3169 // propagate the known value for the select into other uses of it, and
3170 // propagate a known value of the condition into its other users.
3171
3172 // If the select and condition only have a single use, don't bother with this,
3173 // early exit.
3174 if (SI->use_empty() && SelectCond->hasOneUse())
3175 return true;
3176
3177 // Scan the current block backward, looking for other uses of SI.
3178 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3179
3180 while (BBI != BBFront) {
3181 --BBI;
3182 // If we found a call to a function, we can't assume it will return, so
3183 // information from below it cannot be propagated above it.
3184 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3185 break;
3186
3187 // Replace uses of the select or its condition with the known values.
3188 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3189 I != E; ++I) {
3190 if (*I == SI) {
3191 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00003192 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003193 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00003194 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3195 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00003196 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003197 }
3198 }
3199
3200 // If we past the instruction, quit looking for it.
3201 if (&*BBI == SI)
3202 SI = 0;
3203 if (&*BBI == SelectCond)
3204 SelectCond = 0;
3205
3206 // If we ran out of things to eliminate, break out of the loop.
3207 if (SelectCond == 0 && SI == 0)
3208 break;
3209
3210 }
3211 return true;
3212}
3213
3214
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215/// This function implements the transforms on div instructions that work
3216/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3217/// used by the visitors to those instructions.
3218/// @brief Transforms common to all three div instructions
3219Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
Chris Lattner653ef3c2008-02-19 06:12:18 +00003222 // undef / X -> 0 for integer.
3223 // undef / X -> undef for FP (the undef could be a snan).
3224 if (isa<UndefValue>(Op0)) {
3225 if (Op0->getType()->isFPOrFPVector())
3226 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00003227 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003228 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229
3230 // X / undef -> undef
3231 if (isa<UndefValue>(Op1))
3232 return ReplaceInstUsesWith(I, Op1);
3233
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003234 return 0;
3235}
3236
3237/// This function implements the transforms common to both integer division
3238/// instructions (udiv and sdiv). It is called by the visitors to those integer
3239/// division instructions.
3240/// @brief Common integer divide transforms
3241Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3243
Chris Lattnercefb36c2008-05-16 02:59:42 +00003244 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003245 if (Op0 == Op1) {
3246 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003247 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003248 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003249 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003250 }
3251
Owen Andersoneacb44d2009-07-24 23:12:02 +00003252 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003253 return ReplaceInstUsesWith(I, CI);
3254 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003255
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 if (Instruction *Common = commonDivTransforms(I))
3257 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003258
3259 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3260 // This does not apply for fdiv.
3261 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3262 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003263
3264 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3265 // div X, 1 == X
3266 if (RHS->equalsInt(1))
3267 return ReplaceInstUsesWith(I, Op0);
3268
3269 // (X / C1) / C2 -> X / (C1*C2)
3270 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3271 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3272 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003273 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003274 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003275 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003276 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003277 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003278 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003279 }
3280
3281 if (!RHS->isZero()) { // avoid X udiv 0
3282 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3283 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3284 return R;
3285 if (isa<PHINode>(Op0))
3286 if (Instruction *NV = FoldOpIntoPhi(I))
3287 return NV;
3288 }
3289 }
3290
3291 // 0 / X == 0, we don't need to preserve faults!
3292 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3293 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003296 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003297 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003298 return ReplaceInstUsesWith(I, Op0);
3299
Nick Lewycky94418732008-11-27 20:21:08 +00003300 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3301 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3302 // div X, 1 == X
3303 if (X->isOne())
3304 return ReplaceInstUsesWith(I, Op0);
3305 }
3306
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307 return 0;
3308}
3309
3310Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3312
3313 // Handle the integer div common cases
3314 if (Instruction *Common = commonIDivTransforms(I))
3315 return Common;
3316
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003317 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003318 // X udiv C^2 -> X >> C
3319 // Check to see if this is an unsigned division with an exact power of 2,
3320 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003321 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003322 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003323 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003324
3325 // X udiv C, where C >= signbit
3326 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003327 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003328 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003329 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003330 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331 }
3332
3333 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3334 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3335 if (RHSI->getOpcode() == Instruction::Shl &&
3336 isa<ConstantInt>(RHSI->getOperand(0))) {
3337 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3338 if (C1.isPowerOf2()) {
3339 Value *N = RHSI->getOperand(1);
3340 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003341 if (uint32_t C2 = C1.logBase2())
3342 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003343 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344 }
3345 }
3346 }
3347
3348 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3349 // where C1&C2 are powers of two.
3350 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3351 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3352 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3353 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3354 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3355 // Compute the shift amounts
3356 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3357 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003358 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003359 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003360
3361 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003362 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003363 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003364
3365 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003366 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003367 }
3368 }
3369 return 0;
3370}
3371
3372Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3374
3375 // Handle the integer div common cases
3376 if (Instruction *Common = commonIDivTransforms(I))
3377 return Common;
3378
3379 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3380 // sdiv X, -1 == -X
3381 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003382 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003383
Dan Gohman07878902009-08-12 16:33:09 +00003384 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003385 if (cast<SDivOperator>(&I)->isExact() &&
3386 RHS->getValue().isNonNegative() &&
3387 RHS->getValue().isPowerOf2()) {
3388 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3389 RHS->getValue().exactLogBase2());
3390 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3391 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003392
3393 // -X/C --> X/-C provided the negation doesn't overflow.
3394 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3395 if (isa<Constant>(Sub->getOperand(0)) &&
3396 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003397 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003398 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3399 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 }
3401
3402 // If the sign bits of both operands are zero (i.e. we can prove they are
3403 // unsigned inputs), turn this into a udiv.
3404 if (I.getType()->isInteger()) {
3405 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003406 if (MaskedValueIsZero(Op0, Mask)) {
3407 if (MaskedValueIsZero(Op1, Mask)) {
3408 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3409 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3410 }
3411 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003412 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003413 ShiftedInt->getValue().isPowerOf2()) {
3414 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3415 // Safe because the only negative value (1 << Y) can take on is
3416 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3417 // the sign bit set.
3418 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3419 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003421 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422
3423 return 0;
3424}
3425
3426Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3427 return commonDivTransforms(I);
3428}
3429
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003430/// This function implements the transforms on rem instructions that work
3431/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3432/// is used by the visitors to those instructions.
3433/// @brief Transforms common to all three rem instructions
3434Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3436
Chris Lattner653ef3c2008-02-19 06:12:18 +00003437 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3438 if (I.getType()->isFPOrFPVector())
3439 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003441 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 if (isa<UndefValue>(Op1))
3443 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3444
3445 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003446 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3447 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003448
3449 return 0;
3450}
3451
3452/// This function implements the transforms common to both integer remainder
3453/// instructions (urem and srem). It is called by the visitors to those integer
3454/// remainder instructions.
3455/// @brief Common integer remainder transforms
3456Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3457 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3458
3459 if (Instruction *common = commonRemTransforms(I))
3460 return common;
3461
Dale Johannesena51f7372009-01-21 00:35:19 +00003462 // 0 % X == 0 for integer, we don't need to preserve faults!
3463 if (Constant *LHS = dyn_cast<Constant>(Op0))
3464 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3468 // X % 0 == undef, we don't need to preserve faults!
3469 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003470 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003471
3472 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003473 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003474
3475 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3476 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3477 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3478 return R;
3479 } else if (isa<PHINode>(Op0I)) {
3480 if (Instruction *NV = FoldOpIntoPhi(I))
3481 return NV;
3482 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003483
3484 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003485 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003486 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 }
3488 }
3489
3490 return 0;
3491}
3492
3493Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3495
3496 if (Instruction *common = commonIRemTransforms(I))
3497 return common;
3498
3499 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3500 // X urem C^2 -> X and C
3501 // Check to see if this is an unsigned remainder with an exact power of 2,
3502 // if so, convert to a bitwise and.
3503 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3504 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003505 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 }
3507
3508 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3509 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3510 if (RHSI->getOpcode() == Instruction::Shl &&
3511 isa<ConstantInt>(RHSI->getOperand(0))) {
3512 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003513 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003514 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003515 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 }
3517 }
3518 }
3519
3520 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3521 // where C1&C2 are powers of two.
3522 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3523 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3524 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3525 // STO == 0 and SFO == 0 handled above.
3526 if ((STO->getValue().isPowerOf2()) &&
3527 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003528 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3529 SI->getName()+".t");
3530 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3531 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003532 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 }
3534 }
3535 }
3536
3537 return 0;
3538}
3539
3540Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3541 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3542
Dan Gohmandb3dd962007-11-05 23:16:33 +00003543 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003544 if (Instruction *Common = commonIRemTransforms(I))
3545 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003547 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003548 if (!isa<Constant>(RHSNeg) ||
3549 (isa<ConstantInt>(RHSNeg) &&
3550 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003551 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003552 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003553 I.setOperand(1, RHSNeg);
3554 return &I;
3555 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003556
Dan Gohmandb3dd962007-11-05 23:16:33 +00003557 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003559 if (I.getType()->isInteger()) {
3560 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3561 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3562 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003563 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003564 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565 }
3566
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003567 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003568 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3569 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003570
Nick Lewyckyfd746832008-12-20 16:48:00 +00003571 bool hasNegative = false;
3572 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3574 if (RHS->getValue().isNegative())
3575 hasNegative = true;
3576
3577 if (hasNegative) {
3578 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003579 for (unsigned i = 0; i != VWidth; ++i) {
3580 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3581 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003582 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003583 else
3584 Elts[i] = RHS;
3585 }
3586 }
3587
Owen Anderson2f422e02009-07-28 21:19:26 +00003588 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003589 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003590 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003591 I.setOperand(1, NewRHSV);
3592 return &I;
3593 }
3594 }
3595 }
3596
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003597 return 0;
3598}
3599
3600Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3601 return commonRemTransforms(I);
3602}
3603
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604// isOneBitSet - Return true if there is exactly one bit set in the specified
3605// constant.
3606static bool isOneBitSet(const ConstantInt *CI) {
3607 return CI->getValue().isPowerOf2();
3608}
3609
3610// isHighOnes - Return true if the constant is of the form 1+0+.
3611// This is the same as lowones(~X).
3612static bool isHighOnes(const ConstantInt *CI) {
3613 return (~CI->getValue() + 1).isPowerOf2();
3614}
3615
3616/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3617/// are carefully arranged to allow folding of expressions such as:
3618///
3619/// (A < B) | (A > B) --> (A != B)
3620///
3621/// Note that this is only valid if the first and second predicates have the
3622/// same sign. Is illegal to do: (A u< B) | (A s> B)
3623///
3624/// Three bits are used to represent the condition, as follows:
3625/// 0 A > B
3626/// 1 A == B
3627/// 2 A < B
3628///
3629/// <=> Value Definition
3630/// 000 0 Always false
3631/// 001 1 A > B
3632/// 010 2 A == B
3633/// 011 3 A >= B
3634/// 100 4 A < B
3635/// 101 5 A != B
3636/// 110 6 A <= B
3637/// 111 7 Always true
3638///
3639static unsigned getICmpCode(const ICmpInst *ICI) {
3640 switch (ICI->getPredicate()) {
3641 // False -> 0
3642 case ICmpInst::ICMP_UGT: return 1; // 001
3643 case ICmpInst::ICMP_SGT: return 1; // 001
3644 case ICmpInst::ICMP_EQ: return 2; // 010
3645 case ICmpInst::ICMP_UGE: return 3; // 011
3646 case ICmpInst::ICMP_SGE: return 3; // 011
3647 case ICmpInst::ICMP_ULT: return 4; // 100
3648 case ICmpInst::ICMP_SLT: return 4; // 100
3649 case ICmpInst::ICMP_NE: return 5; // 101
3650 case ICmpInst::ICMP_ULE: return 6; // 110
3651 case ICmpInst::ICMP_SLE: return 6; // 110
3652 // True -> 7
3653 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003654 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 return 0;
3656 }
3657}
3658
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003659/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3660/// predicate into a three bit mask. It also returns whether it is an ordered
3661/// predicate by reference.
3662static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3663 isOrdered = false;
3664 switch (CC) {
3665 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3666 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003667 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3668 case FCmpInst::FCMP_UGT: return 1; // 001
3669 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3670 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003671 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3672 case FCmpInst::FCMP_UGE: return 3; // 011
3673 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3674 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003675 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3676 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003677 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3678 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003679 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003680 default:
3681 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003682 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003683 return 0;
3684 }
3685}
3686
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003687/// getICmpValue - This is the complement of getICmpCode, which turns an
3688/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003689/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003690/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003691static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003692 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003694 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003695 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 case 1:
3697 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003698 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003700 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3701 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702 case 3:
3703 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003704 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003705 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003706 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 case 4:
3708 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003709 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003710 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003711 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3712 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 case 6:
3714 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003715 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003716 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003717 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003718 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003719 }
3720}
3721
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003722/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3723/// opcode and two operands into either a FCmp instruction. isordered is passed
3724/// in to determine which kind of predicate to use in the new fcmp instruction.
3725static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003726 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003727 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003728 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003729 case 0:
3730 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003731 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003732 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003733 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003734 case 1:
3735 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003736 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003737 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003738 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003739 case 2:
3740 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003741 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003742 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003743 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003744 case 3:
3745 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003746 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003747 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003748 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003749 case 4:
3750 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003751 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003752 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003753 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003754 case 5:
3755 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003756 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003757 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003758 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003759 case 6:
3760 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003761 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003762 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003763 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003764 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003765 }
3766}
3767
Chris Lattner2972b822008-11-16 04:55:20 +00003768/// PredicatesFoldable - Return true if both predicates match sign or if at
3769/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003770static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003771 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3772 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3773 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003774}
3775
3776namespace {
3777// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3778struct FoldICmpLogical {
3779 InstCombiner &IC;
3780 Value *LHS, *RHS;
3781 ICmpInst::Predicate pred;
3782 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3783 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3784 pred(ICI->getPredicate()) {}
3785 bool shouldApply(Value *V) const {
3786 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3787 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003788 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3789 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 return false;
3791 }
3792 Instruction *apply(Instruction &Log) const {
3793 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3794 if (ICI->getOperand(0) != LHS) {
3795 assert(ICI->getOperand(1) == LHS);
3796 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3797 }
3798
3799 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3800 unsigned LHSCode = getICmpCode(ICI);
3801 unsigned RHSCode = getICmpCode(RHSICI);
3802 unsigned Code;
3803 switch (Log.getOpcode()) {
3804 case Instruction::And: Code = LHSCode & RHSCode; break;
3805 case Instruction::Or: Code = LHSCode | RHSCode; break;
3806 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003807 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003808 }
3809
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003810 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003811 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003812 if (Instruction *I = dyn_cast<Instruction>(RV))
3813 return I;
3814 // Otherwise, it's a constant boolean value...
3815 return IC.ReplaceInstUsesWith(Log, RV);
3816 }
3817};
3818} // end anonymous namespace
3819
3820// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3821// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3822// guaranteed to be a binary operator.
3823Instruction *InstCombiner::OptAndOp(Instruction *Op,
3824 ConstantInt *OpRHS,
3825 ConstantInt *AndRHS,
3826 BinaryOperator &TheAnd) {
3827 Value *X = Op->getOperand(0);
3828 Constant *Together = 0;
3829 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003830 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831
3832 switch (Op->getOpcode()) {
3833 case Instruction::Xor:
3834 if (Op->hasOneUse()) {
3835 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003836 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003837 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003838 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003839 }
3840 break;
3841 case Instruction::Or:
3842 if (Together == AndRHS) // (X | C) & C --> C
3843 return ReplaceInstUsesWith(TheAnd, AndRHS);
3844
3845 if (Op->hasOneUse() && Together != OpRHS) {
3846 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003847 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003848 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003849 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003850 }
3851 break;
3852 case Instruction::Add:
3853 if (Op->hasOneUse()) {
3854 // Adding a one to a single bit bit-field should be turned into an XOR
3855 // of the bit. First thing to check is to see if this AND is with a
3856 // single bit constant.
3857 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3858
3859 // If there is only one bit set...
3860 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3861 // Ok, at this point, we know that we are masking the result of the
3862 // ADD down to exactly one bit. If the constant we are adding has
3863 // no bits set below this bit, then we can eliminate the ADD.
3864 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3865
3866 // Check to see if any bits below the one bit set in AndRHSV are set.
3867 if ((AddRHS & (AndRHSV-1)) == 0) {
3868 // If not, the only thing that can effect the output of the AND is
3869 // the bit specified by AndRHSV. If that bit is set, the effect of
3870 // the XOR is to toggle the bit. If it is clear, then the ADD has
3871 // no effect.
3872 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3873 TheAnd.setOperand(0, X);
3874 return &TheAnd;
3875 } else {
3876 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003877 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003878 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003879 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003880 }
3881 }
3882 }
3883 }
3884 break;
3885
3886 case Instruction::Shl: {
3887 // We know that the AND will not produce any of the bits shifted in, so if
3888 // the anded constant includes them, clear them now!
3889 //
3890 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3891 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3892 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003893 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894
3895 if (CI->getValue() == ShlMask) {
3896 // Masking out bits that the shift already masks
3897 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3898 } else if (CI != AndRHS) { // Reducing bits set in and.
3899 TheAnd.setOperand(1, CI);
3900 return &TheAnd;
3901 }
3902 break;
3903 }
3904 case Instruction::LShr:
3905 {
3906 // We know that the AND will not produce any of the bits shifted in, so if
3907 // the anded constant includes them, clear them now! This only applies to
3908 // unsigned shifts, because a signed shr may bring in set bits!
3909 //
3910 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3911 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3912 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003913 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003914
3915 if (CI->getValue() == ShrMask) {
3916 // Masking out bits that the shift already masks.
3917 return ReplaceInstUsesWith(TheAnd, Op);
3918 } else if (CI != AndRHS) {
3919 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3920 return &TheAnd;
3921 }
3922 break;
3923 }
3924 case Instruction::AShr:
3925 // Signed shr.
3926 // See if this is shifting in some sign extension, then masking it out
3927 // with an and.
3928 if (Op->hasOneUse()) {
3929 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3930 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3931 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003932 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003933 if (C == AndRHS) { // Masking out bits shifted in.
3934 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3935 // Make the argument unsigned.
3936 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003937 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003938 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003939 }
3940 }
3941 break;
3942 }
3943 return 0;
3944}
3945
3946
3947/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3948/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3949/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3950/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3951/// insert new instructions.
3952Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3953 bool isSigned, bool Inside,
3954 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003955 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003956 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3957 "Lo is not <= Hi in range emission code!");
3958
3959 if (Inside) {
3960 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003961 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962
3963 // V >= Min && V < Hi --> V < Hi
3964 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3965 ICmpInst::Predicate pred = (isSigned ?
3966 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003967 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003968 }
3969
3970 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003971 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003972 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003973 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003974 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003975 }
3976
3977 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003978 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003979
3980 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003981 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003982 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3983 ICmpInst::Predicate pred = (isSigned ?
3984 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003985 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003986 }
3987
3988 // Emit V-Lo >u Hi-1-Lo
3989 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003990 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003991 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003992 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003993 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994}
3995
3996// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3997// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3998// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3999// not, since all 1s are not contiguous.
4000static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4001 const APInt& V = Val->getValue();
4002 uint32_t BitWidth = Val->getType()->getBitWidth();
4003 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4004
4005 // look for the first zero bit after the run of ones
4006 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4007 // look for the first non-zero bit
4008 ME = V.getActiveBits();
4009 return true;
4010}
4011
4012/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4013/// where isSub determines whether the operator is a sub. If we can fold one of
4014/// the following xforms:
4015///
4016/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4017/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4018/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4019///
4020/// return (A +/- B).
4021///
4022Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4023 ConstantInt *Mask, bool isSub,
4024 Instruction &I) {
4025 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4026 if (!LHSI || LHSI->getNumOperands() != 2 ||
4027 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4028
4029 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4030
4031 switch (LHSI->getOpcode()) {
4032 default: return 0;
4033 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00004034 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004035 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4036 if ((Mask->getValue().countLeadingZeros() +
4037 Mask->getValue().countPopulation()) ==
4038 Mask->getValue().getBitWidth())
4039 break;
4040
4041 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4042 // part, we don't need any explicit masks to take them out of A. If that
4043 // is all N is, ignore it.
4044 uint32_t MB = 0, ME = 0;
4045 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4046 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4047 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4048 if (MaskedValueIsZero(RHS, Mask))
4049 break;
4050 }
4051 }
4052 return 0;
4053 case Instruction::Or:
4054 case Instruction::Xor:
4055 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4056 if ((Mask->getValue().countLeadingZeros() +
4057 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00004058 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004059 break;
4060 return 0;
4061 }
4062
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004063 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00004064 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4065 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004066}
4067
Chris Lattner0631ea72008-11-16 05:06:21 +00004068/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4069Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4070 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner163e6ab2009-11-29 00:51:17 +00004071 // (icmp eq A, null) & (icmp eq B, null) -->
4072 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4073 if (TD &&
4074 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4075 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4076 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4077 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4078 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4079 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4080 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4081 Value *NewOr = Builder->CreateOr(A, B);
4082 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4083 Constant::getNullValue(IntPtrTy));
4084 }
4085
Chris Lattnerf3803482008-11-16 05:10:52 +00004086 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00004087 ConstantInt *LHSCst, *RHSCst;
4088 ICmpInst::Predicate LHSCC, RHSCC;
4089
Chris Lattnerf3803482008-11-16 05:10:52 +00004090 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004091 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004092 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004093 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004094 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00004095 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00004096
Chris Lattner163e6ab2009-11-29 00:51:17 +00004097 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4098 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4099 // where C is a power of 2
4100 if (LHSCC == ICmpInst::ICMP_ULT &&
4101 LHSCst->getValue().isPowerOf2()) {
4102 Value *NewOr = Builder->CreateOr(Val, Val2);
4103 return new ICmpInst(LHSCC, NewOr, LHSCst);
4104 }
4105
4106 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4107 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4108 Value *NewOr = Builder->CreateOr(Val, Val2);
4109 return new ICmpInst(LHSCC, NewOr, LHSCst);
4110 }
Chris Lattnerf3803482008-11-16 05:10:52 +00004111 }
4112
4113 // From here on, we only handle:
4114 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4115 if (Val != Val2) return 0;
4116
Chris Lattner0631ea72008-11-16 05:06:21 +00004117 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4118 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4119 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4120 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4121 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4122 return 0;
4123
4124 // We can't fold (ugt x, C) & (sgt x, C2).
4125 if (!PredicatesFoldable(LHSCC, RHSCC))
4126 return 0;
4127
4128 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00004129 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004130 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00004131 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004132 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00004133 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00004134 else
Chris Lattner665298f2008-11-16 05:14:43 +00004135 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4136
4137 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00004138 std::swap(LHS, RHS);
4139 std::swap(LHSCst, RHSCst);
4140 std::swap(LHSCC, RHSCC);
4141 }
4142
4143 // At this point, we know we have have two icmp instructions
4144 // comparing a value against two constants and and'ing the result
4145 // together. Because of the above check, we know that we only have
4146 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4147 // (from the FoldICmpLogical check above), that the two constants
4148 // are not equal and that the larger constant is on the RHS
4149 assert(LHSCst != RHSCst && "Compares not folded above?");
4150
4151 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004152 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004153 case ICmpInst::ICMP_EQ:
4154 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004155 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004156 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4157 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4158 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004159 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004160 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4161 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4162 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4163 return ReplaceInstUsesWith(I, LHS);
4164 }
4165 case ICmpInst::ICMP_NE:
4166 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004167 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004168 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004169 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004170 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004171 break; // (X != 13 & X u< 15) -> no change
4172 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004173 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004174 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004175 break; // (X != 13 & X s< 15) -> no change
4176 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4177 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4178 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4179 return ReplaceInstUsesWith(I, RHS);
4180 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004181 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00004182 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004183 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00004184 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004185 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00004186 }
4187 break; // (X != 13 & X != 15) -> no change
4188 }
4189 break;
4190 case ICmpInst::ICMP_ULT:
4191 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004192 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004193 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4194 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004195 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004196 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4197 break;
4198 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4199 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4200 return ReplaceInstUsesWith(I, LHS);
4201 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4202 break;
4203 }
4204 break;
4205 case ICmpInst::ICMP_SLT:
4206 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004207 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004208 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4209 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004210 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004211 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4212 break;
4213 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4214 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4215 return ReplaceInstUsesWith(I, LHS);
4216 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4217 break;
4218 }
4219 break;
4220 case ICmpInst::ICMP_UGT:
4221 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004222 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004223 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4224 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4225 return ReplaceInstUsesWith(I, RHS);
4226 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4227 break;
4228 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004229 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004230 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004231 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004232 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004233 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004234 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004235 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4236 break;
4237 }
4238 break;
4239 case ICmpInst::ICMP_SGT:
4240 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004241 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004242 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4243 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4244 return ReplaceInstUsesWith(I, RHS);
4245 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4246 break;
4247 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004248 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004249 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004250 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004251 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004252 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004253 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004254 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4255 break;
4256 }
4257 break;
4258 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004259
4260 return 0;
4261}
4262
Chris Lattner93a359a2009-07-23 05:14:02 +00004263Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4264 FCmpInst *RHS) {
4265
4266 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4267 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4268 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4269 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4270 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4271 // If either of the constants are nans, then the whole thing returns
4272 // false.
4273 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004274 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004275 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004276 LHS->getOperand(0), RHS->getOperand(0));
4277 }
Chris Lattnercf373552009-07-23 05:32:17 +00004278
4279 // Handle vector zeros. This occurs because the canonical form of
4280 // "fcmp ord x,x" is "fcmp ord x, 0".
4281 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4282 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004283 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004284 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004285 return 0;
4286 }
4287
4288 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4289 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4290 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4291
4292
4293 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4294 // Swap RHS operands to match LHS.
4295 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4296 std::swap(Op1LHS, Op1RHS);
4297 }
4298
4299 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4300 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4301 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004302 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004303
4304 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004305 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004306 if (Op0CC == FCmpInst::FCMP_TRUE)
4307 return ReplaceInstUsesWith(I, RHS);
4308 if (Op1CC == FCmpInst::FCMP_TRUE)
4309 return ReplaceInstUsesWith(I, LHS);
4310
4311 bool Op0Ordered;
4312 bool Op1Ordered;
4313 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4314 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4315 if (Op1Pred == 0) {
4316 std::swap(LHS, RHS);
4317 std::swap(Op0Pred, Op1Pred);
4318 std::swap(Op0Ordered, Op1Ordered);
4319 }
4320 if (Op0Pred == 0) {
4321 // uno && ueq -> uno && (uno || eq) -> ueq
4322 // ord && olt -> ord && (ord && lt) -> olt
4323 if (Op0Ordered == Op1Ordered)
4324 return ReplaceInstUsesWith(I, RHS);
4325
4326 // uno && oeq -> uno && (ord && eq) -> false
4327 // uno && ord -> false
4328 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004329 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004330 // ord && ueq -> ord && (uno || eq) -> oeq
4331 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4332 Op0LHS, Op0RHS, Context));
4333 }
4334 }
4335
4336 return 0;
4337}
4338
Chris Lattner0631ea72008-11-16 05:06:21 +00004339
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004340Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4341 bool Changed = SimplifyCommutative(I);
4342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4343
Chris Lattnera3e46f62009-11-10 00:55:12 +00004344 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4345 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004346
4347 // See if we can simplify any instructions used by the instruction whose sole
4348 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004349 if (SimplifyDemandedInstructionBits(I))
4350 return &I;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004351
Dan Gohman8fd520a2009-06-15 22:12:54 +00004352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004353 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004354 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004355 APInt NotAndRHS(~AndRHSMask);
4356
4357 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004358 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359 Value *Op0LHS = Op0I->getOperand(0);
4360 Value *Op0RHS = Op0I->getOperand(1);
4361 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004362 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363 case Instruction::Xor:
4364 case Instruction::Or:
4365 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004366 if (!Op0I->hasOneUse()) break;
4367
4368 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4369 // Not masking anything out for the LHS, move to RHS.
4370 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4371 Op0RHS->getName()+".masked");
4372 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4373 }
4374 if (!isa<Constant>(Op0RHS) &&
4375 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4376 // Not masking anything out for the RHS, move to LHS.
4377 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4378 Op0LHS->getName()+".masked");
4379 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004380 }
4381
4382 break;
4383 case Instruction::Add:
4384 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4385 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4386 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4387 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004388 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004389 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004390 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004391 break;
4392
4393 case Instruction::Sub:
4394 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4395 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4396 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4397 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004398 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004399
Nick Lewyckya349ba42008-07-10 05:51:40 +00004400 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4401 // has 1's for all bits that the subtraction with A might affect.
4402 if (Op0I->hasOneUse()) {
4403 uint32_t BitWidth = AndRHSMask.getBitWidth();
4404 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4405 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4406
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004407 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004408 if (!(A && A->isZero()) && // avoid infinite recursion.
4409 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004410 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004411 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4412 }
4413 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004414 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004415
4416 case Instruction::Shl:
4417 case Instruction::LShr:
4418 // (1 << x) & 1 --> zext(x == 0)
4419 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004420 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004421 Value *NewICmp =
4422 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004423 return new ZExtInst(NewICmp, I.getType());
4424 }
4425 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 }
4427
4428 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4429 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4430 return Res;
4431 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4432 // If this is an integer truncation or change from signed-to-unsigned, and
4433 // if the source is an and/or with immediate, transform it. This
4434 // frequently occurs for bitfield accesses.
4435 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4436 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4437 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00004438 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004439 if (CastOp->getOpcode() == Instruction::And) {
4440 // Change: and (cast (and X, C1) to T), C2
4441 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4442 // This will fold the two constants together, which may allow
4443 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004444 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004445 CastOp->getOperand(0), I.getType(),
4446 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004448 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004449 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004450 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004451 } else if (CastOp->getOpcode() == Instruction::Or) {
4452 // Change: and (cast (or X, C1) to T), C2
4453 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004454 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004455 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004456 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004457 return ReplaceInstUsesWith(I, AndRHS);
4458 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004460 }
4461 }
4462
4463 // Try to fold constant and into select arguments.
4464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4465 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4466 return R;
4467 if (isa<PHINode>(Op0))
4468 if (Instruction *NV = FoldOpIntoPhi(I))
4469 return NV;
4470 }
4471
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472
4473 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00004474 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4475 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4476 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4477 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4478 I.getName()+".demorgan");
4479 return BinaryOperator::CreateNot(Or);
4480 }
4481
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004482 {
4483 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004484 // (A|B) & ~(A&B) -> A^B
4485 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4486 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4487 ((A == C && B == D) || (A == D && B == C)))
4488 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004489
Chris Lattnera3e46f62009-11-10 00:55:12 +00004490 // ~(A&B) & (A|B) -> A^B
4491 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4492 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4493 ((A == C && B == D) || (A == D && B == C)))
4494 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004495
4496 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004497 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004498 if (A == Op1) { // (A^B)&A -> A&(A^B)
4499 I.swapOperands(); // Simplify below
4500 std::swap(Op0, Op1);
4501 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4502 cast<BinaryOperator>(Op0)->swapOperands();
4503 I.swapOperands(); // Simplify below
4504 std::swap(Op0, Op1);
4505 }
4506 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004507
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004508 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004509 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004510 if (B == Op0) { // B&(A^B) -> B&(B^A)
4511 cast<BinaryOperator>(Op1)->swapOperands();
4512 std::swap(A, B);
4513 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004514 if (A == Op0) // A&(A^B) -> A & ~B
4515 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004516 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004517
4518 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004519 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4520 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004521 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004522 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4523 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004524 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004525 }
4526
4527 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4528 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004529 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004530 return R;
4531
Chris Lattner0631ea72008-11-16 05:06:21 +00004532 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4533 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4534 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004535 }
4536
4537 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4538 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4539 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4540 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4541 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004542 if (SrcTy == Op1C->getOperand(0)->getType() &&
4543 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004544 // Only do this if the casts both really cause code to be generated.
4545 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4546 I.getType(), TD) &&
4547 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4548 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004549 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4550 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004551 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004552 }
4553 }
4554
4555 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4556 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4557 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4558 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4559 SI0->getOperand(1) == SI1->getOperand(1) &&
4560 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004561 Value *NewOp =
4562 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4563 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004564 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004565 SI1->getOperand(1));
4566 }
4567 }
4568
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004569 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004570 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004571 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4572 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4573 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004574 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004575
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004576 return Changed ? &I : 0;
4577}
4578
Chris Lattner567f5112008-10-05 02:13:19 +00004579/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4580/// capable of providing pieces of a bswap. The subexpression provides pieces
4581/// of a bswap if it is proven that each of the non-zero bytes in the output of
4582/// the expression came from the corresponding "byte swapped" byte in some other
4583/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4584/// we know that the expression deposits the low byte of %X into the high byte
4585/// of the bswap result and that all other bytes are zero. This expression is
4586/// accepted, the high byte of ByteValues is set to X to indicate a correct
4587/// match.
4588///
4589/// This function returns true if the match was unsuccessful and false if so.
4590/// On entry to the function the "OverallLeftShift" is a signed integer value
4591/// indicating the number of bytes that the subexpression is later shifted. For
4592/// example, if the expression is later right shifted by 16 bits, the
4593/// OverallLeftShift value would be -2 on entry. This is used to specify which
4594/// byte of ByteValues is actually being set.
4595///
4596/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4597/// byte is masked to zero by a user. For example, in (X & 255), X will be
4598/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4599/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4600/// always in the local (OverallLeftShift) coordinate space.
4601///
4602static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4603 SmallVector<Value*, 8> &ByteValues) {
4604 if (Instruction *I = dyn_cast<Instruction>(V)) {
4605 // If this is an or instruction, it may be an inner node of the bswap.
4606 if (I->getOpcode() == Instruction::Or) {
4607 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4608 ByteValues) ||
4609 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4610 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004611 }
Chris Lattner567f5112008-10-05 02:13:19 +00004612
4613 // If this is a logical shift by a constant multiple of 8, recurse with
4614 // OverallLeftShift and ByteMask adjusted.
4615 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4616 unsigned ShAmt =
4617 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4618 // Ensure the shift amount is defined and of a byte value.
4619 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4620 return true;
4621
4622 unsigned ByteShift = ShAmt >> 3;
4623 if (I->getOpcode() == Instruction::Shl) {
4624 // X << 2 -> collect(X, +2)
4625 OverallLeftShift += ByteShift;
4626 ByteMask >>= ByteShift;
4627 } else {
4628 // X >>u 2 -> collect(X, -2)
4629 OverallLeftShift -= ByteShift;
4630 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004631 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004632 }
4633
4634 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4635 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4636
4637 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4638 ByteValues);
4639 }
4640
4641 // If this is a logical 'and' with a mask that clears bytes, clear the
4642 // corresponding bytes in ByteMask.
4643 if (I->getOpcode() == Instruction::And &&
4644 isa<ConstantInt>(I->getOperand(1))) {
4645 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4646 unsigned NumBytes = ByteValues.size();
4647 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4648 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4649
4650 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4651 // If this byte is masked out by a later operation, we don't care what
4652 // the and mask is.
4653 if ((ByteMask & (1 << i)) == 0)
4654 continue;
4655
4656 // If the AndMask is all zeros for this byte, clear the bit.
4657 APInt MaskB = AndMask & Byte;
4658 if (MaskB == 0) {
4659 ByteMask &= ~(1U << i);
4660 continue;
4661 }
4662
4663 // If the AndMask is not all ones for this byte, it's not a bytezap.
4664 if (MaskB != Byte)
4665 return true;
4666
4667 // Otherwise, this byte is kept.
4668 }
4669
4670 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4671 ByteValues);
4672 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004673 }
4674
Chris Lattner567f5112008-10-05 02:13:19 +00004675 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4676 // the input value to the bswap. Some observations: 1) if more than one byte
4677 // is demanded from this input, then it could not be successfully assembled
4678 // into a byteswap. At least one of the two bytes would not be aligned with
4679 // their ultimate destination.
4680 if (!isPowerOf2_32(ByteMask)) return true;
4681 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004682
Chris Lattner567f5112008-10-05 02:13:19 +00004683 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4684 // is demanded, it needs to go into byte 0 of the result. This means that the
4685 // byte needs to be shifted until it lands in the right byte bucket. The
4686 // shift amount depends on the position: if the byte is coming from the high
4687 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4688 // low part, it must be shifted left.
4689 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4690 if (InputByteNo < ByteValues.size()/2) {
4691 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4692 return true;
4693 } else {
4694 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4695 return true;
4696 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004697
4698 // If the destination byte value is already defined, the values are or'd
4699 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004700 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004701 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004702 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004703 return false;
4704}
4705
4706/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4707/// If so, insert the new bswap intrinsic and return it.
4708Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4709 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004710 if (!ITy || ITy->getBitWidth() % 16 ||
4711 // ByteMask only allows up to 32-byte values.
4712 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4714
4715 /// ByteValues - For each byte of the result, we keep track of which value
4716 /// defines each byte.
4717 SmallVector<Value*, 8> ByteValues;
4718 ByteValues.resize(ITy->getBitWidth()/8);
4719
4720 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004721 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4722 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004723 return 0;
4724
4725 // Check to see if all of the bytes come from the same value.
4726 Value *V = ByteValues[0];
4727 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4728
4729 // Check to make sure that all of the bytes come from the same value.
4730 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4731 if (ByteValues[i] != V)
4732 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004733 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004734 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004735 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004736 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004737}
4738
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004739/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4740/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4741/// we can simplify this expression to "cond ? C : D or B".
4742static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004743 Value *C, Value *D,
4744 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004745 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004746 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004747 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004748 return 0;
4749
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004750 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004751 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004752 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004753 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004754 return SelectInst::Create(Cond, C, B);
4755 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004756 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004757 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004758 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004759 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004760 return 0;
4761}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004762
Chris Lattner0c678e52008-11-16 05:20:07 +00004763/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4764Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4765 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner163e6ab2009-11-29 00:51:17 +00004766 // (icmp ne A, null) | (icmp ne B, null) -->
4767 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4768 if (TD &&
4769 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4770 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4771 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4772 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4773 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4774 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4775 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4776 Value *NewOr = Builder->CreateOr(A, B);
4777 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4778 Constant::getNullValue(IntPtrTy));
4779 }
4780
Chris Lattner0c678e52008-11-16 05:20:07 +00004781 Value *Val, *Val2;
4782 ConstantInt *LHSCst, *RHSCst;
4783 ICmpInst::Predicate LHSCC, RHSCC;
4784
4785 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner163e6ab2009-11-29 00:51:17 +00004786 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4787 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004788 return 0;
Chris Lattner163e6ab2009-11-29 00:51:17 +00004789
4790
4791 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4792 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4793 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4794 Value *NewOr = Builder->CreateOr(Val, Val2);
4795 return new ICmpInst(LHSCC, NewOr, LHSCst);
4796 }
Chris Lattner0c678e52008-11-16 05:20:07 +00004797
4798 // From here on, we only handle:
4799 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4800 if (Val != Val2) return 0;
4801
4802 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4803 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4804 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4805 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4806 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4807 return 0;
4808
4809 // We can't fold (ugt x, C) | (sgt x, C2).
4810 if (!PredicatesFoldable(LHSCC, RHSCC))
4811 return 0;
4812
4813 // Ensure that the larger constant is on the RHS.
4814 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004815 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004816 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004817 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004818 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4819 else
4820 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4821
4822 if (ShouldSwap) {
4823 std::swap(LHS, RHS);
4824 std::swap(LHSCst, RHSCst);
4825 std::swap(LHSCC, RHSCC);
4826 }
4827
4828 // At this point, we know we have have two icmp instructions
4829 // comparing a value against two constants and or'ing the result
4830 // together. Because of the above check, we know that we only have
4831 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4832 // FoldICmpLogical check above), that the two constants are not
4833 // equal.
4834 assert(LHSCst != RHSCst && "Compares not folded above?");
4835
4836 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004837 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004838 case ICmpInst::ICMP_EQ:
4839 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004840 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004841 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004842 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004843 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004844 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004845 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004846 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004847 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004848 }
4849 break; // (X == 13 | X == 15) -> no change
4850 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4851 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4852 break;
4853 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4854 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4855 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4856 return ReplaceInstUsesWith(I, RHS);
4857 }
4858 break;
4859 case ICmpInst::ICMP_NE:
4860 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004861 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004862 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4863 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4864 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4865 return ReplaceInstUsesWith(I, LHS);
4866 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4867 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4868 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004869 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004870 }
4871 break;
4872 case ICmpInst::ICMP_ULT:
4873 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004874 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004875 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4876 break;
4877 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4878 // If RHSCst is [us]MAXINT, it is always false. Not handling
4879 // this can cause overflow.
4880 if (RHSCst->isMaxValue(false))
4881 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004882 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004883 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004884 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4885 break;
4886 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4887 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4888 return ReplaceInstUsesWith(I, RHS);
4889 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4890 break;
4891 }
4892 break;
4893 case ICmpInst::ICMP_SLT:
4894 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004895 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004896 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4897 break;
4898 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4899 // If RHSCst is [us]MAXINT, it is always false. Not handling
4900 // this can cause overflow.
4901 if (RHSCst->isMaxValue(true))
4902 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004903 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004904 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004905 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4906 break;
4907 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4908 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4909 return ReplaceInstUsesWith(I, RHS);
4910 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4911 break;
4912 }
4913 break;
4914 case ICmpInst::ICMP_UGT:
4915 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004916 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004917 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4918 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4919 return ReplaceInstUsesWith(I, LHS);
4920 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4921 break;
4922 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4923 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004925 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4926 break;
4927 }
4928 break;
4929 case ICmpInst::ICMP_SGT:
4930 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004931 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004932 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4933 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4934 return ReplaceInstUsesWith(I, LHS);
4935 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4936 break;
4937 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4938 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004939 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004940 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4941 break;
4942 }
4943 break;
4944 }
4945 return 0;
4946}
4947
Chris Lattner57e66fa2009-07-23 05:46:22 +00004948Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4949 FCmpInst *RHS) {
4950 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4951 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4952 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4953 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4954 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4955 // If either of the constants are nans, then the whole thing returns
4956 // true.
4957 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004958 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004959
4960 // Otherwise, no need to compare the two constants, compare the
4961 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004962 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004963 LHS->getOperand(0), RHS->getOperand(0));
4964 }
4965
4966 // Handle vector zeros. This occurs because the canonical form of
4967 // "fcmp uno x,x" is "fcmp uno x, 0".
4968 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4969 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004970 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004971 LHS->getOperand(0), RHS->getOperand(0));
4972
4973 return 0;
4974 }
4975
4976 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4977 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4978 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4979
4980 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4981 // Swap RHS operands to match LHS.
4982 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4983 std::swap(Op1LHS, Op1RHS);
4984 }
4985 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4986 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4987 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004988 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004989 Op0LHS, Op0RHS);
4990 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004991 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004992 if (Op0CC == FCmpInst::FCMP_FALSE)
4993 return ReplaceInstUsesWith(I, RHS);
4994 if (Op1CC == FCmpInst::FCMP_FALSE)
4995 return ReplaceInstUsesWith(I, LHS);
4996 bool Op0Ordered;
4997 bool Op1Ordered;
4998 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4999 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5000 if (Op0Ordered == Op1Ordered) {
5001 // If both are ordered or unordered, return a new fcmp with
5002 // or'ed predicates.
5003 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5004 Op0LHS, Op0RHS, Context);
5005 if (Instruction *I = dyn_cast<Instruction>(RV))
5006 return I;
5007 // Otherwise, it's a constant boolean value...
5008 return ReplaceInstUsesWith(I, RV);
5009 }
5010 }
5011 return 0;
5012}
5013
Bill Wendlingdae376a2008-12-01 08:23:25 +00005014/// FoldOrWithConstants - This helper function folds:
5015///
Bill Wendling236a1192008-12-02 05:09:00 +00005016/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00005017///
5018/// into:
5019///
Bill Wendling236a1192008-12-02 05:09:00 +00005020/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00005021///
Bill Wendling236a1192008-12-02 05:09:00 +00005022/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00005023Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00005024 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00005025 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5026 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005027
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005028 Value *V1 = 0;
5029 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005030 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005031
Bill Wendling86ee3162008-12-02 06:18:11 +00005032 APInt Xor = CI1->getValue() ^ CI2->getValue();
5033 if (!Xor.isAllOnesValue()) return 0;
5034
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005035 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005036 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00005037 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005038 }
5039
5040 return 0;
5041}
5042
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5044 bool Changed = SimplifyCommutative(I);
5045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5046
Chris Lattnera3e46f62009-11-10 00:55:12 +00005047 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5048 return ReplaceInstUsesWith(I, V);
5049
5050
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005051 // See if we can simplify any instructions used by the instruction whose sole
5052 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005053 if (SimplifyDemandedInstructionBits(I))
5054 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005055
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005056 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5057 ConstantInt *C1 = 0; Value *X = 0;
5058 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005059 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005060 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005061 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005062 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005063 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005064 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065 }
5066
5067 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005068 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005069 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005070 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005071 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005072 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005073 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005074 }
5075
5076 // Try to fold constant and into select arguments.
5077 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5078 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5079 return R;
5080 if (isa<PHINode>(Op0))
5081 if (Instruction *NV = FoldOpIntoPhi(I))
5082 return NV;
5083 }
5084
5085 Value *A = 0, *B = 0;
5086 ConstantInt *C1 = 0, *C2 = 0;
5087
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005088 // (A | B) | C and A | (B | C) -> bswap if possible.
5089 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00005090 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5091 match(Op1, m_Or(m_Value(), m_Value())) ||
5092 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5093 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005094 if (Instruction *BSwap = MatchBSwap(I))
5095 return BSwap;
5096 }
5097
5098 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005099 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005100 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005101 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005102 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005103 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005105 }
5106
5107 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005108 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005109 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005110 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005111 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005112 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005113 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005114 }
5115
5116 // (A & C)|(B & D)
5117 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005118 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5119 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120 Value *V1 = 0, *V2 = 0, *V3 = 0;
5121 C1 = dyn_cast<ConstantInt>(C);
5122 C2 = dyn_cast<ConstantInt>(D);
5123 if (C1 && C2) { // (A & C1)|(B & C2)
5124 // If we have: ((V + N) & C1) | (V & C2)
5125 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5126 // replace with V+N.
5127 if (C1->getValue() == ~C2->getValue()) {
5128 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00005129 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005130 // Add commutes, try both ways.
5131 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5132 return ReplaceInstUsesWith(I, A);
5133 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5134 return ReplaceInstUsesWith(I, A);
5135 }
5136 // Or commutes, try both ways.
5137 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005138 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139 // Add commutes, try both ways.
5140 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5141 return ReplaceInstUsesWith(I, B);
5142 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5143 return ReplaceInstUsesWith(I, B);
5144 }
5145 }
5146 V1 = 0; V2 = 0; V3 = 0;
5147 }
5148
5149 // Check to see if we have any common things being and'ed. If so, find the
5150 // terms for V1 & (V2|V3).
5151 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5152 if (A == B) // (A & C)|(A & D) == A & (C|D)
5153 V1 = A, V2 = C, V3 = D;
5154 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5155 V1 = A, V2 = B, V3 = C;
5156 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5157 V1 = C, V2 = A, V3 = D;
5158 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5159 V1 = C, V2 = A, V3 = B;
5160
5161 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005162 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005163 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005164 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005165 }
Dan Gohman279952c2008-10-28 22:38:57 +00005166
Dan Gohman35b76162008-10-30 20:40:10 +00005167 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00005168 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005169 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005170 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005171 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005172 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005173 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005174 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005175 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00005176
Bill Wendling22ca8352008-11-30 13:52:49 +00005177 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005178 if ((match(C, m_Not(m_Specific(D))) &&
5179 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005180 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005181 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005182 if ((match(A, m_Not(m_Specific(D))) &&
5183 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005184 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005185 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005186 if ((match(C, m_Not(m_Specific(B))) &&
5187 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005188 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00005189 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005190 if ((match(A, m_Not(m_Specific(B))) &&
5191 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005192 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005193 }
5194
5195 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5196 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5197 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5198 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5199 SI0->getOperand(1) == SI1->getOperand(1) &&
5200 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005201 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5202 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005203 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005204 SI1->getOperand(1));
5205 }
5206 }
5207
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005208 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005209 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5210 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005211 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005212 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005213 }
5214 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005215 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5216 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005217 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005218 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005219 }
5220
Chris Lattnera3e46f62009-11-10 00:55:12 +00005221 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5222 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5223 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5224 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5225 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5226 I.getName()+".demorgan");
5227 return BinaryOperator::CreateNot(And);
5228 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005229
5230 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5231 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005232 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005233 return R;
5234
Chris Lattner0c678e52008-11-16 05:20:07 +00005235 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5236 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5237 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005238 }
5239
5240 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005241 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5243 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005244 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5245 !isa<ICmpInst>(Op1C->getOperand(0))) {
5246 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005247 if (SrcTy == Op1C->getOperand(0)->getType() &&
5248 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005249 // Only do this if the casts both really cause code to be
5250 // generated.
5251 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5252 I.getType(), TD) &&
5253 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5254 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005255 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5256 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005257 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005258 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005259 }
5260 }
Chris Lattner91882432007-10-24 05:38:08 +00005261 }
5262
5263
5264 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5265 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005266 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5267 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5268 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005269 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005270
5271 return Changed ? &I : 0;
5272}
5273
Dan Gohman089efff2008-05-13 00:00:25 +00005274namespace {
5275
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005276// XorSelf - Implements: X ^ X --> 0
5277struct XorSelf {
5278 Value *RHS;
5279 XorSelf(Value *rhs) : RHS(rhs) {}
5280 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5281 Instruction *apply(BinaryOperator &Xor) const {
5282 return &Xor;
5283 }
5284};
5285
Dan Gohman089efff2008-05-13 00:00:25 +00005286}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287
5288Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5289 bool Changed = SimplifyCommutative(I);
5290 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5291
Evan Chenge5cd8032008-03-25 20:07:13 +00005292 if (isa<UndefValue>(Op1)) {
5293 if (isa<UndefValue>(Op0))
5294 // Handle undef ^ undef -> 0 special case. This is a common
5295 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005297 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005298 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005299
5300 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005301 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005302 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005304 }
5305
5306 // See if we can simplify any instructions used by the instruction whose sole
5307 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005308 if (SimplifyDemandedInstructionBits(I))
5309 return &I;
5310 if (isa<VectorType>(I.getType()))
5311 if (isa<ConstantAggregateZero>(Op1))
5312 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005313
5314 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005315 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005316 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5317 if (Op0I->getOpcode() == Instruction::And ||
5318 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00005319 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5320 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5321 if (dyn_castNotVal(Op0I->getOperand(1)))
5322 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005323 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005324 Value *NotY =
5325 Builder->CreateNot(Op0I->getOperand(1),
5326 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005327 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005328 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005329 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005330 }
Chris Lattner6e060db2009-10-26 15:40:07 +00005331
5332 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5333 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5334 if (isFreeToInvert(Op0I->getOperand(0)) &&
5335 isFreeToInvert(Op0I->getOperand(1))) {
5336 Value *NotX =
5337 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5338 Value *NotY =
5339 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5340 if (Op0I->getOpcode() == Instruction::And)
5341 return BinaryOperator::CreateOr(NotX, NotY);
5342 return BinaryOperator::CreateAnd(NotX, NotY);
5343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005344 }
5345 }
5346 }
5347
5348
5349 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005350 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005351 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005352 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005353 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005354 ICI->getOperand(0), ICI->getOperand(1));
5355
Nick Lewycky1405e922007-08-06 20:04:16 +00005356 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005357 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005358 FCI->getOperand(0), FCI->getOperand(1));
5359 }
5360
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005361 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5362 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5363 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5364 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5365 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005366 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5367 (RHS == ConstantExpr::getCast(Opcode,
5368 ConstantInt::getTrue(*Context),
5369 Op0C->getDestTy()))) {
5370 CI->setPredicate(CI->getInversePredicate());
5371 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005372 }
5373 }
5374 }
5375 }
5376
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005377 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5378 // ~(c-X) == X-c-1 == X+(-c-1)
5379 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5380 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005381 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5382 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005383 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005384 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005385 }
5386
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005387 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005388 if (Op0I->getOpcode() == Instruction::Add) {
5389 // ~(X-c) --> (-c-1)-X
5390 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005391 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005392 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005393 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005394 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005395 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005396 } else if (RHS->getValue().isSignBit()) {
5397 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005398 Constant *C = ConstantInt::get(*Context,
5399 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005400 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005401
5402 }
5403 } else if (Op0I->getOpcode() == Instruction::Or) {
5404 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5405 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005406 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005407 // Anything in both C1 and C2 is known to be zero, remove it from
5408 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005409 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5410 NewRHS = ConstantExpr::getAnd(NewRHS,
5411 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005412 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005413 I.setOperand(0, Op0I->getOperand(0));
5414 I.setOperand(1, NewRHS);
5415 return &I;
5416 }
5417 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005418 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005419 }
5420
5421 // Try to fold constant and into select arguments.
5422 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5424 return R;
5425 if (isa<PHINode>(Op0))
5426 if (Instruction *NV = FoldOpIntoPhi(I))
5427 return NV;
5428 }
5429
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005430 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005432 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005433
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005434 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005435 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005436 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005437
5438
5439 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5440 if (Op1I) {
5441 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005442 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005443 if (A == Op0) { // B^(B|A) == (A|B)^B
5444 Op1I->swapOperands();
5445 I.swapOperands();
5446 std::swap(Op0, Op1);
5447 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5448 I.swapOperands(); // Simplified below.
5449 std::swap(Op0, Op1);
5450 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005451 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005452 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005453 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005454 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005455 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005456 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005457 if (A == Op0) { // A^(A&B) -> A^(B&A)
5458 Op1I->swapOperands();
5459 std::swap(A, B);
5460 }
5461 if (B == Op0) { // A^(B&A) -> (B&A)^A
5462 I.swapOperands(); // Simplified below.
5463 std::swap(Op0, Op1);
5464 }
5465 }
5466 }
5467
5468 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5469 if (Op0I) {
5470 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005471 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005472 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005473 if (A == Op1) // (B|A)^B == (A|B)^B
5474 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005475 if (B == Op1) // (A|B)^B == A & ~B
5476 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005477 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005478 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005479 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005480 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005481 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005482 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005483 if (A == Op1) // (A&B)^A -> (B&A)^A
5484 std::swap(A, B);
5485 if (B == Op1 && // (B&A)^A == ~B & A
5486 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005487 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005488 }
5489 }
5490 }
5491
5492 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5493 if (Op0I && Op1I && Op0I->isShift() &&
5494 Op0I->getOpcode() == Op1I->getOpcode() &&
5495 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5496 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005497 Value *NewOp =
5498 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5499 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005500 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005501 Op1I->getOperand(1));
5502 }
5503
5504 if (Op0I && Op1I) {
5505 Value *A, *B, *C, *D;
5506 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005507 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5508 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005509 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005510 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511 }
5512 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005513 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5514 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005515 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005516 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005517 }
5518
5519 // (A & B)^(C & D)
5520 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005521 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5522 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005523 // (X & Y)^(X & Y) -> (Y^Z) & X
5524 Value *X = 0, *Y = 0, *Z = 0;
5525 if (A == C)
5526 X = A, Y = B, Z = D;
5527 else if (A == D)
5528 X = A, Y = B, Z = C;
5529 else if (B == C)
5530 X = B, Y = A, Z = D;
5531 else if (B == D)
5532 X = B, Y = A, Z = C;
5533
5534 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005535 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005536 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005537 }
5538 }
5539 }
5540
5541 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5542 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005543 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005544 return R;
5545
5546 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005547 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005548 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5549 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5550 const Type *SrcTy = Op0C->getOperand(0)->getType();
5551 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5552 // Only do this if the casts both really cause code to be generated.
5553 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5554 I.getType(), TD) &&
5555 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5556 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005557 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5558 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005559 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005560 }
5561 }
Chris Lattner91882432007-10-24 05:38:08 +00005562 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005563
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005564 return Changed ? &I : 0;
5565}
5566
Owen Anderson24be4c12009-07-03 00:17:18 +00005567static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005568 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005569 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005570}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005571
Dan Gohman8fd520a2009-06-15 22:12:54 +00005572static bool HasAddOverflow(ConstantInt *Result,
5573 ConstantInt *In1, ConstantInt *In2,
5574 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005575 if (IsSigned)
5576 if (In2->getValue().isNegative())
5577 return Result->getValue().sgt(In1->getValue());
5578 else
5579 return Result->getValue().slt(In1->getValue());
5580 else
5581 return Result->getValue().ult(In1->getValue());
5582}
5583
Dan Gohman8fd520a2009-06-15 22:12:54 +00005584/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005585/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005586static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005587 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005588 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005589 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005590
Dan Gohman8fd520a2009-06-15 22:12:54 +00005591 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5592 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005593 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005594 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5595 ExtractElement(In1, Idx, Context),
5596 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005597 IsSigned))
5598 return true;
5599 }
5600 return false;
5601 }
5602
5603 return HasAddOverflow(cast<ConstantInt>(Result),
5604 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5605 IsSigned);
5606}
5607
5608static bool HasSubOverflow(ConstantInt *Result,
5609 ConstantInt *In1, ConstantInt *In2,
5610 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005611 if (IsSigned)
5612 if (In2->getValue().isNegative())
5613 return Result->getValue().slt(In1->getValue());
5614 else
5615 return Result->getValue().sgt(In1->getValue());
5616 else
5617 return Result->getValue().ugt(In1->getValue());
5618}
5619
Dan Gohman8fd520a2009-06-15 22:12:54 +00005620/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5621/// overflowed for this type.
5622static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005623 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005624 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005625 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005626
5627 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5628 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005629 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005630 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5631 ExtractElement(In1, Idx, Context),
5632 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005633 IsSigned))
5634 return true;
5635 }
5636 return false;
5637 }
5638
5639 return HasSubOverflow(cast<ConstantInt>(Result),
5640 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5641 IsSigned);
5642}
5643
Chris Lattnereba75862008-04-22 02:53:33 +00005644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005645/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5646/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005647Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005648 ICmpInst::Predicate Cond,
5649 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005650 // Look through bitcasts.
5651 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5652 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005653
5654 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005655 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005656 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005657 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005658 // know pointers can't overflow since the gep is inbounds. See if we can
5659 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005660 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5661
5662 // If not, synthesize the offset the hard way.
5663 if (Offset == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005664 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005665 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005666 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005667 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005668 // If the base pointers are different, but the indices are the same, just
5669 // compare the base pointer.
5670 if (PtrBase != GEPRHS->getOperand(0)) {
5671 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5672 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5673 GEPRHS->getOperand(0)->getType();
5674 if (IndicesTheSame)
5675 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5676 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5677 IndicesTheSame = false;
5678 break;
5679 }
5680
5681 // If all indices are the same, just compare the base pointers.
5682 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005683 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005684 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5685
5686 // Otherwise, the base pointers are different and the indices are
5687 // different, bail out.
5688 return 0;
5689 }
5690
5691 // If one of the GEPs has all zero indices, recurse.
5692 bool AllZeros = true;
5693 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5694 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5695 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5696 AllZeros = false;
5697 break;
5698 }
5699 if (AllZeros)
5700 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5701 ICmpInst::getSwappedPredicate(Cond), I);
5702
5703 // If the other GEP has all zero indices, recurse.
5704 AllZeros = true;
5705 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5706 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5707 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5708 AllZeros = false;
5709 break;
5710 }
5711 if (AllZeros)
5712 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5713
5714 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5715 // If the GEPs only differ by one index, compare it.
5716 unsigned NumDifferences = 0; // Keep track of # differences.
5717 unsigned DiffOperand = 0; // The operand that differs.
5718 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5719 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5720 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5721 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5722 // Irreconcilable differences.
5723 NumDifferences = 2;
5724 break;
5725 } else {
5726 if (NumDifferences++) break;
5727 DiffOperand = i;
5728 }
5729 }
5730
5731 if (NumDifferences == 0) // SAME GEP?
5732 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005733 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005734 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005735
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005736 else if (NumDifferences == 1) {
5737 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5738 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5739 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005740 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005741 }
5742 }
5743
5744 // Only lower this if the icmp is the only user of the GEP or if we expect
5745 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005746 if (TD &&
5747 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005748 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5749 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005750 Value *L = EmitGEPOffset(GEPLHS, *this);
5751 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005752 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005753 }
5754 }
5755 return 0;
5756}
5757
Chris Lattnere6b62d92008-05-19 20:18:56 +00005758/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5759///
5760Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5761 Instruction *LHSI,
5762 Constant *RHSC) {
5763 if (!isa<ConstantFP>(RHSC)) return 0;
5764 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5765
5766 // Get the width of the mantissa. We don't want to hack on conversions that
5767 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005768 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005769 if (MantissaWidth == -1) return 0; // Unknown.
5770
5771 // Check to see that the input is converted from an integer type that is small
5772 // enough that preserves all bits. TODO: check here for "known" sign bits.
5773 // 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 +00005774 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005775
5776 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005777 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5778 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005779 ++InputSize;
5780
5781 // If the conversion would lose info, don't hack on this.
5782 if ((int)InputSize > MantissaWidth)
5783 return 0;
5784
5785 // Otherwise, we can potentially simplify the comparison. We know that it
5786 // will always come through as an integer value and we know the constant is
5787 // not a NAN (it would have been previously simplified).
5788 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5789
5790 ICmpInst::Predicate Pred;
5791 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005792 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005793 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005794 case FCmpInst::FCMP_OEQ:
5795 Pred = ICmpInst::ICMP_EQ;
5796 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005797 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005798 case FCmpInst::FCMP_OGT:
5799 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5800 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005801 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005802 case FCmpInst::FCMP_OGE:
5803 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5804 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005805 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005806 case FCmpInst::FCMP_OLT:
5807 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5808 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005809 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005810 case FCmpInst::FCMP_OLE:
5811 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5812 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005813 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005814 case FCmpInst::FCMP_ONE:
5815 Pred = ICmpInst::ICMP_NE;
5816 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005817 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005818 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005819 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005820 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005821 }
5822
5823 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5824
5825 // Now we know that the APFloat is a normal number, zero or inf.
5826
Chris Lattnerf13ff492008-05-20 03:50:52 +00005827 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005828 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005829 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005830
Bill Wendling20636df2008-11-09 04:26:50 +00005831 if (!LHSUnsigned) {
5832 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5833 // and large values.
5834 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5835 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5836 APFloat::rmNearestTiesToEven);
5837 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5838 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5839 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005840 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5841 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005842 }
5843 } else {
5844 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5845 // +INF and large values.
5846 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5847 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5848 APFloat::rmNearestTiesToEven);
5849 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5850 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5851 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005852 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5853 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005854 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005855 }
5856
Bill Wendling20636df2008-11-09 04:26:50 +00005857 if (!LHSUnsigned) {
5858 // See if the RHS value is < SignedMin.
5859 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5860 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5861 APFloat::rmNearestTiesToEven);
5862 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5863 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5864 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005865 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5866 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005867 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005868 }
5869
Bill Wendling20636df2008-11-09 04:26:50 +00005870 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5871 // [0, UMAX], but it may still be fractional. See if it is fractional by
5872 // casting the FP value to the integer value and back, checking for equality.
5873 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005874 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005875 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5876 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005877 if (!RHS.isZero()) {
5878 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005879 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5880 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005881 if (!Equal) {
5882 // If we had a comparison against a fractional value, we have to adjust
5883 // the compare predicate and sometimes the value. RHSC is rounded towards
5884 // zero at this point.
5885 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005886 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005887 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005889 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005890 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005891 case ICmpInst::ICMP_ULE:
5892 // (float)int <= 4.4 --> int <= 4
5893 // (float)int <= -4.4 --> false
5894 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005895 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005896 break;
5897 case ICmpInst::ICMP_SLE:
5898 // (float)int <= 4.4 --> int <= 4
5899 // (float)int <= -4.4 --> int < -4
5900 if (RHS.isNegative())
5901 Pred = ICmpInst::ICMP_SLT;
5902 break;
5903 case ICmpInst::ICMP_ULT:
5904 // (float)int < -4.4 --> false
5905 // (float)int < 4.4 --> int <= 4
5906 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005907 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005908 Pred = ICmpInst::ICMP_ULE;
5909 break;
5910 case ICmpInst::ICMP_SLT:
5911 // (float)int < -4.4 --> int < -4
5912 // (float)int < 4.4 --> int <= 4
5913 if (!RHS.isNegative())
5914 Pred = ICmpInst::ICMP_SLE;
5915 break;
5916 case ICmpInst::ICMP_UGT:
5917 // (float)int > 4.4 --> int > 4
5918 // (float)int > -4.4 --> true
5919 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005920 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005921 break;
5922 case ICmpInst::ICMP_SGT:
5923 // (float)int > 4.4 --> int > 4
5924 // (float)int > -4.4 --> int >= -4
5925 if (RHS.isNegative())
5926 Pred = ICmpInst::ICMP_SGE;
5927 break;
5928 case ICmpInst::ICMP_UGE:
5929 // (float)int >= -4.4 --> true
5930 // (float)int >= 4.4 --> int > 4
5931 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005932 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005933 Pred = ICmpInst::ICMP_UGT;
5934 break;
5935 case ICmpInst::ICMP_SGE:
5936 // (float)int >= -4.4 --> int >= -4
5937 // (float)int >= 4.4 --> int > 4
5938 if (!RHS.isNegative())
5939 Pred = ICmpInst::ICMP_SGT;
5940 break;
5941 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005942 }
5943 }
5944
5945 // Lower this FP comparison into an appropriate integer version of the
5946 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005947 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005948}
5949
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005950Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00005951 bool Changed = false;
5952
5953 /// Orders the operands of the compare so that they are listed from most
5954 /// complex to least complex. This puts constants before unary operators,
5955 /// before binary operators.
5956 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5957 I.swapOperands();
5958 Changed = true;
5959 }
5960
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962
Chris Lattner54c21352009-11-09 23:55:12 +00005963 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5964 return ReplaceInstUsesWith(I, V);
5965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005966 // Simplify 'fcmp pred X, X'
5967 if (Op0 == Op1) {
5968 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005969 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005970 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5971 case FCmpInst::FCMP_ULT: // True if unordered or less than
5972 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5973 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5974 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5975 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005976 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005977 return &I;
5978
5979 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5980 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5981 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5982 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5983 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5984 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005985 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005986 return &I;
5987 }
5988 }
5989
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005990 // Handle fcmp with constant RHS
5991 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5992 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5993 switch (LHSI->getOpcode()) {
5994 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005995 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5996 // block. If in the same block, we're encouraging jump threading. If
5997 // not, we are just pessimizing the code by making an i1 phi.
5998 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00005999 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006000 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006001 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00006002 case Instruction::SIToFP:
6003 case Instruction::UIToFP:
6004 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6005 return NV;
6006 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006007 case Instruction::Select:
6008 // If either operand of the select is a constant, we can fold the
6009 // comparison into the select arms, which will cause one to be
6010 // constant folded and the select turned into a bitwise or.
6011 Value *Op1 = 0, *Op2 = 0;
6012 if (LHSI->hasOneUse()) {
6013 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6014 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006015 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006016 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006017 Op2 = Builder->CreateFCmp(I.getPredicate(),
6018 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006019 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6020 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006021 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006022 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006023 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6024 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006025 }
6026 }
6027
6028 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006029 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006030 break;
6031 }
6032 }
6033
6034 return Changed ? &I : 0;
6035}
6036
6037Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006038 bool Changed = false;
6039
6040 /// Orders the operands of the compare so that they are listed from most
6041 /// complex to least complex. This puts constants before unary operators,
6042 /// before binary operators.
6043 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6044 I.swapOperands();
6045 Changed = true;
6046 }
6047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lambf78cd322007-12-18 21:32:20 +00006049
Chris Lattner54c21352009-11-09 23:55:12 +00006050 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6051 return ReplaceInstUsesWith(I, V);
6052
6053 const Type *Ty = Op0->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006054
6055 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006056 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006057 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006058 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006059 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006060 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006061 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006062 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006063 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006064 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006065
6066 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006067 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006068 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006069 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006070 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006071 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006072 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006073 case ICmpInst::ICMP_SGT:
6074 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006075 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006076 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006077 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006078 return BinaryOperator::CreateAnd(Not, Op0);
6079 }
6080 case ICmpInst::ICMP_UGE:
6081 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6082 // FALL THROUGH
6083 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006084 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006085 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006086 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006087 case ICmpInst::ICMP_SGE:
6088 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6089 // FALL THROUGH
6090 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006091 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006092 return BinaryOperator::CreateOr(Not, Op0);
6093 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006094 }
6095 }
6096
Dan Gohman7934d592009-04-25 17:12:48 +00006097 unsigned BitWidth = 0;
6098 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006099 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6100 else if (Ty->isIntOrIntVector())
6101 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006102
6103 bool isSignBit = false;
6104
Dan Gohman58c09632008-09-16 18:46:06 +00006105 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006106 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006107 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006108
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006109 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6110 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006111 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006112 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006113 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006114 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006115
Dan Gohman58c09632008-09-16 18:46:06 +00006116 // If we have an icmp le or icmp ge instruction, turn it into the
6117 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner54c21352009-11-09 23:55:12 +00006118 // them being folded in the code below. The SimplifyICmpInst code has
6119 // already handled the edge cases for us, so we just assert on them.
Chris Lattner62d0f232008-07-11 05:08:55 +00006120 switch (I.getPredicate()) {
6121 default: break;
6122 case ICmpInst::ICMP_ULE:
Chris Lattner54c21352009-11-09 23:55:12 +00006123 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006124 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006125 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006126 case ICmpInst::ICMP_SLE:
Chris Lattner54c21352009-11-09 23:55:12 +00006127 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006128 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006129 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006130 case ICmpInst::ICMP_UGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006131 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006132 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006133 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006134 case ICmpInst::ICMP_SGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006135 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006136 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006137 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006138 }
6139
Chris Lattnera1308652008-07-11 05:40:05 +00006140 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006141 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006142 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006143 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6144 }
6145
6146 // See if we can fold the comparison based on range information we can get
6147 // by checking whether bits are known to be zero or one in the input.
6148 if (BitWidth != 0) {
6149 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6150 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6151
6152 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006153 isSignBit ? APInt::getSignBit(BitWidth)
6154 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006155 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006156 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006157 if (SimplifyDemandedBits(I.getOperandUse(1),
6158 APInt::getAllOnesValue(BitWidth),
6159 Op1KnownZero, Op1KnownOne, 0))
6160 return &I;
6161
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006162 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006163 // in. Compute the Min, Max and RHS values based on the known bits. For the
6164 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006165 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6166 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006167 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006168 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6169 Op0Min, Op0Max);
6170 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6171 Op1Min, Op1Max);
6172 } else {
6173 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6174 Op0Min, Op0Max);
6175 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6176 Op1Min, Op1Max);
6177 }
6178
Chris Lattnera1308652008-07-11 05:40:05 +00006179 // If Min and Max are known to be the same, then SimplifyDemandedBits
6180 // figured out that the LHS is a constant. Just constant fold this now so
6181 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006182 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006183 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006184 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006185 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006186 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006187 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006188
Chris Lattnera1308652008-07-11 05:40:05 +00006189 // Based on the range information we know about the LHS, see if we can
6190 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006191 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006192 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006193 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006194 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006195 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006196 break;
6197 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006198 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006200 break;
6201 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006202 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006203 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006204 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006205 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006206 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006207 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006208 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6209 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006210 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006211 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006212
6213 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6214 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006215 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006216 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006217 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006218 break;
6219 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006220 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006221 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006222 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006223 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006224
6225 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006226 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006227 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6228 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006230 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006231
6232 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6233 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006234 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006235 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006236 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006237 break;
6238 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006239 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006240 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006241 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006242 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006243 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006244 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006245 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6246 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006248 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006249 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006250 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006251 case ICmpInst::ICMP_SGT:
6252 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006253 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006254 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006255 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006256
6257 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006258 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006259 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6260 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006261 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006262 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006263 }
6264 break;
6265 case ICmpInst::ICMP_SGE:
6266 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6267 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006268 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006269 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006270 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006271 break;
6272 case ICmpInst::ICMP_SLE:
6273 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6274 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006275 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006276 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006277 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006278 break;
6279 case ICmpInst::ICMP_UGE:
6280 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6281 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006282 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006283 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006284 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006285 break;
6286 case ICmpInst::ICMP_ULE:
6287 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6288 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006289 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006290 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006291 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006292 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006293 }
Dan Gohman7934d592009-04-25 17:12:48 +00006294
6295 // Turn a signed comparison into an unsigned one if both operands
6296 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006297 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006298 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6299 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006300 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006301 }
6302
6303 // Test if the ICmpInst instruction is used exclusively by a select as
6304 // part of a minimum or maximum operation. If so, refrain from doing
6305 // any other folding. This helps out other analyses which understand
6306 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6307 // and CodeGen. And in this case, at least one of the comparison
6308 // operands has at least one user besides the compare (the select),
6309 // which would often largely negate the benefit of folding anyway.
6310 if (I.hasOneUse())
6311 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6312 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6313 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6314 return 0;
6315
6316 // See if we are doing a comparison between a constant and an instruction that
6317 // can be folded into the comparison.
6318 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006319 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6320 // instruction, see if that instruction also has constants so that the
6321 // instruction can be folded into the icmp
6322 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6323 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6324 return Res;
6325 }
6326
6327 // Handle icmp with constant (but not simple integer constant) RHS
6328 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6329 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6330 switch (LHSI->getOpcode()) {
6331 case Instruction::GetElementPtr:
6332 if (RHSC->isNullValue()) {
6333 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6334 bool isAllZeros = true;
6335 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6336 if (!isa<Constant>(LHSI->getOperand(i)) ||
6337 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6338 isAllZeros = false;
6339 break;
6340 }
6341 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006342 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006343 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006344 }
6345 break;
6346
6347 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006348 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006349 // block. If in the same block, we're encouraging jump threading. If
6350 // not, we are just pessimizing the code by making an i1 phi.
6351 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006352 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006353 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006354 break;
6355 case Instruction::Select: {
6356 // If either operand of the select is a constant, we can fold the
6357 // comparison into the select arms, which will cause one to be
6358 // constant folded and the select turned into a bitwise or.
6359 Value *Op1 = 0, *Op2 = 0;
Eli Friedman4779a952009-12-18 08:22:35 +00006360 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6361 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6362 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6363 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6364
6365 // We only want to perform this transformation if it will not lead to
6366 // additional code. This is true if either both sides of the select
6367 // fold to a constant (in which case the icmp is replaced with a select
6368 // which will usually simplify) or this is the only user of the
6369 // select (in which case we are trading a select+icmp for a simpler
6370 // select+icmp).
6371 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6372 if (!Op1)
Chris Lattnerc7694852009-08-30 07:44:24 +00006373 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6374 RHSC, I.getName());
Eli Friedman4779a952009-12-18 08:22:35 +00006375 if (!Op2)
6376 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6377 RHSC, I.getName());
Gabor Greifd6da1d02008-04-06 20:25:17 +00006378 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman4779a952009-12-18 08:22:35 +00006379 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006380 break;
6381 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006382 case Instruction::Call:
6383 // If we have (malloc != null), and if the malloc has a single use, we
6384 // can assume it is successful and remove the malloc.
6385 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6386 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006387 // Need to explicitly erase malloc call here, instead of adding it to
6388 // Worklist, because it won't get DCE'd from the Worklist since
6389 // isInstructionTriviallyDead() returns false for function calls.
6390 // It is OK to replace LHSI/MallocCall with Undef because the
6391 // instruction that uses it will be erased via Worklist.
6392 if (extractMallocCall(LHSI)) {
6393 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6394 EraseInstFromFunction(*LHSI);
6395 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006396 ConstantInt::get(Type::getInt1Ty(*Context),
6397 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006398 }
6399 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6400 if (MallocCall->hasOneUse()) {
6401 MallocCall->replaceAllUsesWith(
6402 UndefValue::get(MallocCall->getType()));
6403 EraseInstFromFunction(*MallocCall);
6404 Worklist.Add(LHSI); // The malloc's bitcast use.
6405 return ReplaceInstUsesWith(I,
6406 ConstantInt::get(Type::getInt1Ty(*Context),
6407 !I.isTrueWhenEqual()));
6408 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006409 }
6410 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006411 }
6412 }
6413
6414 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006415 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006416 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6417 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006418 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006419 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6420 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6421 return NI;
6422
6423 // Test to see if the operands of the icmp are casted versions of other
6424 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6425 // now.
6426 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6427 if (isa<PointerType>(Op0->getType()) &&
6428 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6429 // We keep moving the cast from the left operand over to the right
6430 // operand, where it can often be eliminated completely.
6431 Op0 = CI->getOperand(0);
6432
6433 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6434 // so eliminate it as well.
6435 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6436 Op1 = CI2->getOperand(0);
6437
6438 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006439 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006440 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006441 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006442 } else {
6443 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006444 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006445 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006446 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006447 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006448 }
6449 }
6450
6451 if (isa<CastInst>(Op0)) {
6452 // Handle the special case of: icmp (cast bool to X), <cst>
6453 // This comes up when you have code like
6454 // int X = A < B;
6455 // if (X) ...
6456 // For generality, we handle any zero-extension of any operand comparison
6457 // with a constant or another cast from the same type.
Eli Friedmanbb8954b2009-12-17 21:27:47 +00006458 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006459 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6460 return R;
6461 }
6462
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006463 // See if it's the same type of instruction on the left and right.
6464 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6465 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006466 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006467 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006468 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006469 default: break;
6470 case Instruction::Add:
6471 case Instruction::Sub:
6472 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006473 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006474 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006475 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006476 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6477 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6478 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006479 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006480 ? I.getUnsignedPredicate()
6481 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006482 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006483 Op1I->getOperand(0));
6484 }
6485
6486 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006487 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006488 ? I.getUnsignedPredicate()
6489 : I.getSignedPredicate();
6490 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006491 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006492 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006493 }
6494 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006495 break;
6496 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006497 if (!I.isEquality())
6498 break;
6499
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006500 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6501 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6502 // Mask = -1 >> count-trailing-zeros(Cst).
6503 if (!CI->isZero() && !CI->isOne()) {
6504 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006505 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006506 APInt::getLowBitsSet(AP.getBitWidth(),
6507 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006508 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006509 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6510 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006511 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006512 }
6513 }
6514 break;
6515 }
6516 }
6517 }
6518 }
6519
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006520 // ~x < ~y --> y < x
6521 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006522 if (match(Op0, m_Not(m_Value(A))) &&
6523 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006524 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006525 }
6526
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006527 if (I.isEquality()) {
6528 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006529
6530 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006531 if (match(Op0, m_Neg(m_Value(A))) &&
6532 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006533 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006534
Dan Gohmancdff2122009-08-12 16:23:25 +00006535 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006536 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6537 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006538 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006539 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006540 }
6541
Dan Gohmancdff2122009-08-12 16:23:25 +00006542 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006543 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006544 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006545 if (match(B, m_ConstantInt(C1)) &&
6546 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006547 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006548 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006549 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6550 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006551 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006552
6553 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006554 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6555 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6556 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6557 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006558 }
6559 }
6560
Dan Gohmancdff2122009-08-12 16:23:25 +00006561 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006562 (A == Op0 || B == Op0)) {
6563 // A == (A^B) -> B == 0
6564 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006565 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006566 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006567 }
Chris Lattner3b874082008-11-16 05:38:51 +00006568
6569 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006570 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006571 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006572 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006573
6574 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006575 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006576 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006577 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006578
6579 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6580 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006581 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6582 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006583 Value *X = 0, *Y = 0, *Z = 0;
6584
6585 if (A == C) {
6586 X = B; Y = D; Z = A;
6587 } else if (A == D) {
6588 X = B; Y = C; Z = A;
6589 } else if (B == C) {
6590 X = A; Y = D; Z = B;
6591 } else if (B == D) {
6592 X = A; Y = C; Z = B;
6593 }
6594
6595 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006596 Op1 = Builder->CreateXor(X, Y, "tmp");
6597 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006599 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006600 return &I;
6601 }
6602 }
6603 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006604
6605 {
6606 Value *X; ConstantInt *Cst;
6607 // icmp (X+Cst), X
6608 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
6609 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
6610
6611 // icmp X, X+Cst
6612 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
6613 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
6614 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006615 return Changed ? &I : 0;
6616}
6617
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006618/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6619Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6620 Value *X, ConstantInt *CI,
6621 ICmpInst::Predicate Pred) {
6622 // If we have X+0, exit early (simplifying logic below) and let it get folded
6623 // elsewhere. icmp X+0, X -> icmp X, X
6624 if (CI->isZero()) {
6625 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6626 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6627 }
6628
6629 // (X+4) == X -> false.
6630 if (Pred == ICmpInst::ICMP_EQ)
6631 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6632
6633 // (X+4) != X -> true.
6634 if (Pred == ICmpInst::ICMP_NE)
6635 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
6636
6637 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6638 // so the values can never be equal. Similiarly for all other "or equals"
6639 // operators.
6640
6641 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6642 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6643 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6644 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
6645 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6646 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6647 }
6648
6649 // (X+1) >u X --> X <u (0-1) --> X != 255
6650 // (X+2) >u X --> X <u (0-2) --> X <u 254
6651 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
6652 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
6653 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
6654
6655 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6656 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6657 APInt::getSignedMaxValue(BitWidth));
6658
6659 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6660 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6661 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6662 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6663 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6664 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
6665 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
6666 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
6667
6668 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6669 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6670 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6671 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6672 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6673 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
6674 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6675 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6676 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6677}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006678
6679/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6680/// and CmpRHS are both known to be integer constants.
6681Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6682 ConstantInt *DivRHS) {
6683 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6684 const APInt &CmpRHSV = CmpRHS->getValue();
6685
6686 // FIXME: If the operand types don't match the type of the divide
6687 // then don't attempt this transform. The code below doesn't have the
6688 // logic to deal with a signed divide and an unsigned compare (and
6689 // vice versa). This is because (x /s C1) <s C2 produces different
6690 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6691 // (x /u C1) <u C2. Simply casting the operands and result won't
6692 // work. :( The if statement below tests that condition and bails
6693 // if it finds it.
6694 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006695 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006696 return 0;
6697 if (DivRHS->isZero())
6698 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006699 if (DivIsSigned && DivRHS->isAllOnesValue())
6700 return 0; // The overflow computation also screws up here
6701 if (DivRHS->isOne())
6702 return 0; // Not worth bothering, and eliminates some funny cases
6703 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006704
6705 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6706 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6707 // C2 (CI). By solving for X we can turn this into a range check
6708 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006709 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006710
6711 // Determine if the product overflows by seeing if the product is
6712 // not equal to the divide. Make sure we do the same kind of divide
6713 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006714 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6715 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006716
6717 // Get the ICmp opcode
6718 ICmpInst::Predicate Pred = ICI.getPredicate();
6719
6720 // Figure out the interval that is being checked. For example, a comparison
6721 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6722 // Compute this interval based on the constants involved and the signedness of
6723 // the compare/divide. This computes a half-open interval, keeping track of
6724 // whether either value in the interval overflows. After analysis each
6725 // overflow variable is set to 0 if it's corresponding bound variable is valid
6726 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6727 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006728 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006729
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006730 if (!DivIsSigned) { // udiv
6731 // e.g. X/5 op 3 --> [15, 20)
6732 LoBound = Prod;
6733 HiOverflow = LoOverflow = ProdOV;
6734 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006735 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006736 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006737 if (CmpRHSV == 0) { // (X / pos) op 0
6738 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006739 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006740 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006741 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006742 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6743 HiOverflow = LoOverflow = ProdOV;
6744 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006745 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006746 } else { // (X / pos) op neg
6747 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006748 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006749 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6750 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006751 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006752 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006753 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006754 true) ? -1 : 0;
6755 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006756 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006757 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006758 if (CmpRHSV == 0) { // (X / neg) op 0
6759 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006760 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006761 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006762 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6763 HiOverflow = 1; // [INTMIN+1, overflow)
6764 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6765 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006766 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006767 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006768 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006769 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6770 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006771 LoOverflow = AddWithOverflow(LoBound, HiBound,
6772 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006773 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006774 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6775 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006776 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006777 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006778 }
6779
6780 // Dividing by a negative swaps the condition. LT <-> GT
6781 Pred = ICmpInst::getSwappedPredicate(Pred);
6782 }
6783
6784 Value *X = DivI->getOperand(0);
6785 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006786 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006787 case ICmpInst::ICMP_EQ:
6788 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006789 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006790 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006791 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006792 ICmpInst::ICMP_UGE, X, LoBound);
6793 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006794 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006795 ICmpInst::ICMP_ULT, X, HiBound);
6796 else
6797 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6798 case ICmpInst::ICMP_NE:
6799 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006800 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006801 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006802 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006803 ICmpInst::ICMP_ULT, X, LoBound);
6804 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006805 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006806 ICmpInst::ICMP_UGE, X, HiBound);
6807 else
6808 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6809 case ICmpInst::ICMP_ULT:
6810 case ICmpInst::ICMP_SLT:
6811 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006812 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006813 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006814 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006815 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006816 case ICmpInst::ICMP_UGT:
6817 case ICmpInst::ICMP_SGT:
6818 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006819 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006820 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006821 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006822 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006823 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006824 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006825 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006826 }
6827}
6828
6829
6830/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6831///
6832Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6833 Instruction *LHSI,
6834 ConstantInt *RHS) {
6835 const APInt &RHSV = RHS->getValue();
6836
6837 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006838 case Instruction::Trunc:
6839 if (ICI.isEquality() && LHSI->hasOneUse()) {
6840 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6841 // of the high bits truncated out of x are known.
6842 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6843 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6844 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6845 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6846 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6847
6848 // If all the high bits are known, we can do this xform.
6849 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6850 // Pull in the high bits from known-ones set.
6851 APInt NewRHS(RHS->getValue());
6852 NewRHS.zext(SrcBits);
6853 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006854 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006855 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006856 }
6857 }
6858 break;
6859
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006860 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6861 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6862 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6863 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006864 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6865 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006866 Value *CompareVal = LHSI->getOperand(0);
6867
6868 // If the sign bit of the XorCST is not set, there is no change to
6869 // the operation, just stop using the Xor.
6870 if (!XorCST->getValue().isNegative()) {
6871 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006872 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006873 return &ICI;
6874 }
6875
6876 // Was the old condition true if the operand is positive?
6877 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6878
6879 // If so, the new one isn't.
6880 isTrueIfPositive ^= true;
6881
6882 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006883 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006884 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006886 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006887 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006888 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006889
6890 if (LHSI->hasOneUse()) {
6891 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6892 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6893 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006894 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006895 ? ICI.getUnsignedPredicate()
6896 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006897 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006898 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006899 }
6900
6901 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006902 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006903 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006904 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006905 ? ICI.getUnsignedPredicate()
6906 : ICI.getSignedPredicate();
6907 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006908 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006909 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006910 }
6911 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006912 }
6913 break;
6914 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6915 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6916 LHSI->getOperand(0)->hasOneUse()) {
6917 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6918
6919 // If the LHS is an AND of a truncating cast, we can widen the
6920 // and/compare to be the input width without changing the value
6921 // produced, eliminating a cast.
6922 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6923 // We can do this transformation if either the AND constant does not
6924 // have its sign bit set or if it is an equality comparison.
6925 // Extending a relational comparison when we're checking the sign
6926 // bit would not work.
6927 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006928 (ICI.isEquality() ||
6929 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006930 uint32_t BitWidth =
6931 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6932 APInt NewCST = AndCST->getValue();
6933 NewCST.zext(BitWidth);
6934 APInt NewCI = RHSV;
6935 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006936 Value *NewAnd =
6937 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006938 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006939 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006940 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006941 }
6942 }
6943
6944 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6945 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6946 // happens a LOT in code produced by the C front-end, for bitfield
6947 // access.
6948 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6949 if (Shift && !Shift->isShift())
6950 Shift = 0;
6951
6952 ConstantInt *ShAmt;
6953 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6954 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6955 const Type *AndTy = AndCST->getType(); // Type of the and.
6956
6957 // We can fold this as long as we can't shift unknown bits
6958 // into the mask. This can only happen with signed shift
6959 // rights, as they sign-extend.
6960 if (ShAmt) {
6961 bool CanFold = Shift->isLogicalShift();
6962 if (!CanFold) {
6963 // To test for the bad case of the signed shr, see if any
6964 // of the bits shifted in could be tested after the mask.
6965 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6966 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6967
6968 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6969 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6970 AndCST->getValue()) == 0)
6971 CanFold = true;
6972 }
6973
6974 if (CanFold) {
6975 Constant *NewCst;
6976 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006977 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006978 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006979 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006980
6981 // Check to see if we are shifting out any of the bits being
6982 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006983 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006984 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006985 // If we shifted bits out, the fold is not going to work out.
6986 // As a special case, check to see if this means that the
6987 // result is always true or false now.
6988 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006989 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006990 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006991 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006992 } else {
6993 ICI.setOperand(1, NewCst);
6994 Constant *NewAndCST;
6995 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006996 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006997 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006998 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006999 LHSI->setOperand(1, NewAndCST);
7000 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00007001 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007002 return &ICI;
7003 }
7004 }
7005 }
7006
7007 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7008 // preferable because it allows the C<<Y expression to be hoisted out
7009 // of a loop if Y is invariant and X is not.
7010 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00007011 ICI.isEquality() && !Shift->isArithmeticShift() &&
7012 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007013 // Compute C << Y.
7014 Value *NS;
7015 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007016 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007017 } else {
7018 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00007019 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007020 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007021
7022 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00007023 Value *NewAnd =
7024 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007025
7026 ICI.setOperand(0, NewAnd);
7027 return &ICI;
7028 }
7029 }
7030 break;
7031
7032 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7033 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7034 if (!ShAmt) break;
7035
7036 uint32_t TypeBits = RHSV.getBitWidth();
7037
7038 // Check that the shift amount is in range. If not, don't perform
7039 // undefined shifts. When the shift is visited it will be
7040 // simplified.
7041 if (ShAmt->uge(TypeBits))
7042 break;
7043
7044 if (ICI.isEquality()) {
7045 // If we are comparing against bits always shifted out, the
7046 // comparison cannot succeed.
7047 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00007048 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00007049 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007050 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7051 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007052 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007053 return ReplaceInstUsesWith(ICI, Cst);
7054 }
7055
7056 if (LHSI->hasOneUse()) {
7057 // Otherwise strength reduce the shift into an and.
7058 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7059 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007060 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00007061 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007062
Chris Lattnerc7694852009-08-30 07:44:24 +00007063 Value *And =
7064 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007065 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007066 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007067 }
7068 }
7069
7070 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7071 bool TrueIfSigned = false;
7072 if (LHSI->hasOneUse() &&
7073 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7074 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00007075 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007076 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00007077 Value *And =
7078 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007079 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00007080 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007081 }
7082 break;
7083 }
7084
7085 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
7086 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007087 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007088 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007089 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007090
Chris Lattner5ee84f82008-03-21 05:19:58 +00007091 // Check that the shift amount is in range. If not, don't perform
7092 // undefined shifts. When the shift is visited it will be
7093 // simplified.
7094 uint32_t TypeBits = RHSV.getBitWidth();
7095 if (ShAmt->uge(TypeBits))
7096 break;
7097
7098 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099
Chris Lattner5ee84f82008-03-21 05:19:58 +00007100 // If we are comparing against bits always shifted out, the
7101 // comparison cannot succeed.
7102 APInt Comp = RHSV << ShAmtVal;
7103 if (LHSI->getOpcode() == Instruction::LShr)
7104 Comp = Comp.lshr(ShAmtVal);
7105 else
7106 Comp = Comp.ashr(ShAmtVal);
7107
7108 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7109 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007110 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007111 return ReplaceInstUsesWith(ICI, Cst);
7112 }
7113
7114 // Otherwise, check to see if the bits shifted out are known to be zero.
7115 // If so, we can compare against the unshifted value:
7116 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007117 if (LHSI->hasOneUse() &&
7118 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007119 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007120 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007121 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007122 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007123
Evan Chengfb9292a2008-04-23 00:38:06 +00007124 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007125 // Otherwise strength reduce the shift into an and.
7126 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007127 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007128
Chris Lattnerc7694852009-08-30 07:44:24 +00007129 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7130 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007131 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007132 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007133 }
7134 break;
7135 }
7136
7137 case Instruction::SDiv:
7138 case Instruction::UDiv:
7139 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7140 // Fold this div into the comparison, producing a range check.
7141 // Determine, based on the divide type, what the range is being
7142 // checked. If there is an overflow on the low or high side, remember
7143 // it, otherwise compute the range [low, hi) bounding the new value.
7144 // See: InsertRangeTest above for the kinds of replacements possible.
7145 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7146 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7147 DivRHS))
7148 return R;
7149 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007150
7151 case Instruction::Add:
Chris Lattner258a2ffb2009-12-21 03:19:28 +00007152 // Fold: icmp pred (add X, C1), C2
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007153 if (!ICI.isEquality()) {
7154 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7155 if (!LHSC) break;
7156 const APInt &LHSV = LHSC->getValue();
7157
7158 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7159 .subtract(LHSV);
7160
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007161 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007162 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007163 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007164 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007165 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007166 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007167 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007168 }
7169 } else {
7170 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007171 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007172 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007173 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007174 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007175 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007176 }
7177 }
7178 }
7179 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007180 }
7181
7182 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7183 if (ICI.isEquality()) {
7184 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7185
7186 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7187 // the second operand is a constant, simplify a bit.
7188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7189 switch (BO->getOpcode()) {
7190 case Instruction::SRem:
7191 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7192 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7193 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7194 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007195 Value *NewRem =
7196 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7197 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007198 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007199 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007200 }
7201 }
7202 break;
7203 case Instruction::Add:
7204 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7205 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7206 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007207 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007208 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007209 } else if (RHSV == 0) {
7210 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7211 // efficiently invertible, or if the add has just this one use.
7212 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7213
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007214 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007215 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007216 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007217 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007218 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007219 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007220 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007221 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007222 }
7223 }
7224 break;
7225 case Instruction::Xor:
7226 // For the xor case, we can xor two constants together, eliminating
7227 // the explicit xor.
7228 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007229 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007230 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007231
7232 // FALLTHROUGH
7233 case Instruction::Sub:
7234 // Replace (([sub|xor] A, B) != 0) with (A != B)
7235 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007236 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007237 BO->getOperand(1));
7238 break;
7239
7240 case Instruction::Or:
7241 // If bits are being or'd in that are not present in the constant we
7242 // are comparing against, then the comparison could never succeed!
7243 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007244 Constant *NotCI = ConstantExpr::getNot(RHS);
7245 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007246 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007247 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007248 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007249 }
7250 break;
7251
7252 case Instruction::And:
7253 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7254 // If bits are being compared against that are and'd out, then the
7255 // comparison can never succeed!
7256 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007257 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007258 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007259 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007260
7261 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7262 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007263 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007264 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007265 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007266
7267 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007268 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007269 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007270 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007271 ICmpInst::Predicate pred = isICMP_NE ?
7272 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007273 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007274 }
7275
7276 // ((X & ~7) == 0) --> X < 8
7277 if (RHSV == 0 && isHighOnes(BOC)) {
7278 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007279 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007280 ICmpInst::Predicate pred = isICMP_NE ?
7281 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007282 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007283 }
7284 }
7285 default: break;
7286 }
7287 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7288 // Handle icmp {eq|ne} <intrinsic>, intcst.
7289 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007290 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007291 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007292 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007293 return &ICI;
7294 }
7295 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007296 }
7297 return 0;
7298}
7299
7300/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7301/// We only handle extending casts so far.
7302///
7303Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7304 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7305 Value *LHSCIOp = LHSCI->getOperand(0);
7306 const Type *SrcTy = LHSCIOp->getType();
7307 const Type *DestTy = LHSCI->getType();
7308 Value *RHSCIOp;
7309
7310 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7311 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007312 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7313 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007314 cast<IntegerType>(DestTy)->getBitWidth()) {
7315 Value *RHSOp = 0;
7316 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007317 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007318 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7319 RHSOp = RHSC->getOperand(0);
7320 // If the pointer types don't match, insert a bitcast.
7321 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007322 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007323 }
7324
7325 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007326 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007327 }
7328
7329 // The code below only handles extension cast instructions, so far.
7330 // Enforce this.
7331 if (LHSCI->getOpcode() != Instruction::ZExt &&
7332 LHSCI->getOpcode() != Instruction::SExt)
7333 return 0;
7334
7335 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007336 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007337
7338 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7339 // Not an extension from the same type?
7340 RHSCIOp = CI->getOperand(0);
7341 if (RHSCIOp->getType() != LHSCIOp->getType())
7342 return 0;
7343
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007344 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007345 // and the other is a zext), then we can't handle this.
7346 if (CI->getOpcode() != LHSCI->getOpcode())
7347 return 0;
7348
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007349 // Deal with equality cases early.
7350 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007351 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007352
7353 // A signed comparison of sign extended values simplifies into a
7354 // signed comparison.
7355 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007356 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007357
7358 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007359 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007360 }
7361
7362 // If we aren't dealing with a constant on the RHS, exit early
7363 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7364 if (!CI)
7365 return 0;
7366
7367 // Compute the constant that would happen if we truncated to SrcTy then
7368 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007369 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7370 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007371 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007372
7373 // If the re-extended constant didn't change...
7374 if (Res2 == CI) {
Eli Friedman96438472009-12-17 22:42:29 +00007375 // Deal with equality cases early.
7376 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007377 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedman96438472009-12-17 22:42:29 +00007378
7379 // A signed comparison of sign extended values simplifies into a
7380 // signed comparison.
7381 if (isSignedExt && isSignedCmp)
7382 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7383
7384 // The other three cases all fold into an unsigned comparison.
7385 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007386 }
7387
7388 // The re-extended constant changed so the constant cannot be represented
7389 // in the shorter type. Consequently, we cannot emit a simple comparison.
7390
7391 // First, handle some easy cases. We know the result cannot be equal at this
7392 // point so handle the ICI.isEquality() cases
7393 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007394 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007395 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007396 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007397
7398 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7399 // should have been folded away previously and not enter in here.
7400 Value *Result;
7401 if (isSignedCmp) {
7402 // We're performing a signed comparison.
7403 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007404 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007405 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007406 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007407 } else {
7408 // We're performing an unsigned comparison.
7409 if (isSignedExt) {
7410 // We're performing an unsigned comp with a sign extended value.
7411 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007412 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007413 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007414 } else {
7415 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007416 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007417 }
7418 }
7419
7420 // Finally, return the value computed.
7421 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007422 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007423 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007424
7425 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7426 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7427 "ICmp should be folded!");
7428 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007429 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007430 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007431}
7432
7433Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7434 return commonShiftTransforms(I);
7435}
7436
7437Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7438 return commonShiftTransforms(I);
7439}
7440
7441Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007442 if (Instruction *R = commonShiftTransforms(I))
7443 return R;
7444
7445 Value *Op0 = I.getOperand(0);
7446
7447 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7448 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7449 if (CSI->isAllOnesValue())
7450 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007451
Dan Gohman2526aea2009-06-16 19:55:29 +00007452 // See if we can turn a signed shr into an unsigned shr.
7453 if (MaskedValueIsZero(Op0,
7454 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7455 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7456
7457 // Arithmetic shifting an all-sign-bit value is a no-op.
7458 unsigned NumSignBits = ComputeNumSignBits(Op0);
7459 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7460 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007461
Chris Lattnere3c504f2007-12-06 01:59:46 +00007462 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007463}
7464
7465Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7466 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7467 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7468
7469 // shl X, 0 == X and shr X, 0 == X
7470 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007471 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7472 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007473 return ReplaceInstUsesWith(I, Op0);
7474
7475 if (isa<UndefValue>(Op0)) {
7476 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7477 return ReplaceInstUsesWith(I, Op0);
7478 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007479 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007480 }
7481 if (isa<UndefValue>(Op1)) {
7482 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7483 return ReplaceInstUsesWith(I, Op0);
7484 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007485 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007486 }
7487
Dan Gohman2bc21562009-05-21 02:28:33 +00007488 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007489 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007490 return &I;
7491
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007492 // Try to fold constant and into select arguments.
7493 if (isa<Constant>(Op0))
7494 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7495 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7496 return R;
7497
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007498 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7499 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7500 return Res;
7501 return 0;
7502}
7503
7504Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7505 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007506 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007507
7508 // See if we can simplify any instructions used by the instruction whose sole
7509 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007510 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007511
Dan Gohman9e1657f2009-06-14 23:30:43 +00007512 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7513 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007514 //
7515 if (Op1->uge(TypeBits)) {
7516 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007517 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007518 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007519 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007520 return &I;
7521 }
7522 }
7523
7524 // ((X*C1) << C2) == (X * (C1 << C2))
7525 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7526 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7527 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007528 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007529 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007530
7531 // Try to fold constant and into select arguments.
7532 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7533 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7534 return R;
7535 if (isa<PHINode>(Op0))
7536 if (Instruction *NV = FoldOpIntoPhi(I))
7537 return NV;
7538
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007539 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7540 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7541 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7542 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7543 // place. Don't try to do this transformation in this case. Also, we
7544 // require that the input operand is a shift-by-constant so that we have
7545 // confidence that the shifts will get folded together. We could do this
7546 // xform in more cases, but it is unlikely to be profitable.
7547 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7548 isa<ConstantInt>(TrOp->getOperand(1))) {
7549 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007550 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007551 // (shift2 (shift1 & 0x00FF), c2)
7552 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007553
7554 // For logical shifts, the truncation has the effect of making the high
7555 // part of the register be zeros. Emulate this by inserting an AND to
7556 // clear the top bits as needed. This 'and' will usually be zapped by
7557 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007558 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7559 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007560 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7561
7562 // The mask we constructed says what the trunc would do if occurring
7563 // between the shifts. We want to know the effect *after* the second
7564 // shift. We know that it is a logical shift by a constant, so adjust the
7565 // mask as appropriate.
7566 if (I.getOpcode() == Instruction::Shl)
7567 MaskV <<= Op1->getZExtValue();
7568 else {
7569 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7570 MaskV = MaskV.lshr(Op1->getZExtValue());
7571 }
7572
Chris Lattnerc7694852009-08-30 07:44:24 +00007573 // shift1 & 0x00FF
7574 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7575 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007576
7577 // Return the value truncated to the interesting size.
7578 return new TruncInst(And, I.getType());
7579 }
7580 }
7581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007582 if (Op0->hasOneUse()) {
7583 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7584 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7585 Value *V1, *V2;
7586 ConstantInt *CC;
7587 switch (Op0BO->getOpcode()) {
7588 default: break;
7589 case Instruction::Add:
7590 case Instruction::And:
7591 case Instruction::Or:
7592 case Instruction::Xor: {
7593 // These operators commute.
7594 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7595 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007596 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007597 m_Specific(Op1)))) {
7598 Value *YS = // (Y << C)
7599 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7600 // (X + (Y << C))
7601 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7602 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007604 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007605 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7606 }
7607
7608 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7609 Value *Op0BOOp1 = Op0BO->getOperand(1);
7610 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7611 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007612 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007613 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007614 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007615 Value *YS = // (Y << C)
7616 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7617 Op0BO->getName());
7618 // X & (CC << C)
7619 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7620 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007621 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007622 }
7623 }
7624
7625 // FALL THROUGH.
7626 case Instruction::Sub: {
7627 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7628 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007629 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007630 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007631 Value *YS = // (Y << C)
7632 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7633 // (X + (Y << C))
7634 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7635 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007636 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007637 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007638 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7639 }
7640
7641 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7642 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7643 match(Op0BO->getOperand(0),
7644 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007645 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007646 cast<BinaryOperator>(Op0BO->getOperand(0))
7647 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007648 Value *YS = // (Y << C)
7649 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7650 // X & (CC << C)
7651 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7652 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007653
Gabor Greifa645dd32008-05-16 19:29:10 +00007654 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 }
7656
7657 break;
7658 }
7659 }
7660
7661
7662 // If the operand is an bitwise operator with a constant RHS, and the
7663 // shift is the only use, we can pull it out of the shift.
7664 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7665 bool isValid = true; // Valid only for And, Or, Xor
7666 bool highBitSet = false; // Transform if high bit of constant set?
7667
7668 switch (Op0BO->getOpcode()) {
7669 default: isValid = false; break; // Do not perform transform!
7670 case Instruction::Add:
7671 isValid = isLeftShift;
7672 break;
7673 case Instruction::Or:
7674 case Instruction::Xor:
7675 highBitSet = false;
7676 break;
7677 case Instruction::And:
7678 highBitSet = true;
7679 break;
7680 }
7681
7682 // If this is a signed shift right, and the high bit is modified
7683 // by the logical operation, do not perform the transformation.
7684 // The highBitSet boolean indicates the value of the high bit of
7685 // the constant which would cause it to be modified for this
7686 // operation.
7687 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007688 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007689 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007690
7691 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007692 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007693
Chris Lattnerad7516a2009-08-30 18:50:58 +00007694 Value *NewShift =
7695 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 NewShift->takeName(Op0BO);
7697
Gabor Greifa645dd32008-05-16 19:29:10 +00007698 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007699 NewRHS);
7700 }
7701 }
7702 }
7703 }
7704
7705 // Find out if this is a shift of a shift by a constant.
7706 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7707 if (ShiftOp && !ShiftOp->isShift())
7708 ShiftOp = 0;
7709
7710 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7711 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7712 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7713 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7714 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7715 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7716 Value *X = ShiftOp->getOperand(0);
7717
7718 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719
7720 const IntegerType *Ty = cast<IntegerType>(I.getType());
7721
7722 // Check for (X << c1) << c2 and (X >> c1) >> c2
7723 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007724 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7725 // saturates.
7726 if (AmtSum >= TypeBits) {
7727 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007728 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007729 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7730 }
7731
Gabor Greifa645dd32008-05-16 19:29:10 +00007732 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007733 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007734 }
7735
7736 if (ShiftOp->getOpcode() == Instruction::LShr &&
7737 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007738 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007739 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007740
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007741 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007742 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007743 }
7744
7745 if (ShiftOp->getOpcode() == Instruction::AShr &&
7746 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007747 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007748 if (AmtSum >= TypeBits)
7749 AmtSum = TypeBits-1;
7750
Chris Lattnerad7516a2009-08-30 18:50:58 +00007751 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007752
7753 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007754 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007755 }
7756
7757 // Okay, if we get here, one shift must be left, and the other shift must be
7758 // right. See if the amounts are equal.
7759 if (ShiftAmt1 == ShiftAmt2) {
7760 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7761 if (I.getOpcode() == Instruction::Shl) {
7762 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007763 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007764 }
7765 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7766 if (I.getOpcode() == Instruction::LShr) {
7767 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007768 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007769 }
7770 // We can simplify ((X << C) >>s C) into a trunc + sext.
7771 // NOTE: we could do this for any C, but that would make 'unusual' integer
7772 // types. For now, just stick to ones well-supported by the code
7773 // generators.
7774 const Type *SExtType = 0;
7775 switch (Ty->getBitWidth() - ShiftAmt1) {
7776 case 1 :
7777 case 8 :
7778 case 16 :
7779 case 32 :
7780 case 64 :
7781 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007782 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007783 break;
7784 default: break;
7785 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007786 if (SExtType)
7787 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007788 // Otherwise, we can't handle it yet.
7789 } else if (ShiftAmt1 < ShiftAmt2) {
7790 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7791
7792 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7793 if (I.getOpcode() == Instruction::Shl) {
7794 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7795 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007796 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007797
7798 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007799 return BinaryOperator::CreateAnd(Shift,
7800 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007801 }
7802
7803 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7804 if (I.getOpcode() == Instruction::LShr) {
7805 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007806 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007807
7808 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007809 return BinaryOperator::CreateAnd(Shift,
7810 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007811 }
7812
7813 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7814 } else {
7815 assert(ShiftAmt2 < ShiftAmt1);
7816 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7817
7818 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7819 if (I.getOpcode() == Instruction::Shl) {
7820 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7821 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007822 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7823 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007824
7825 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007826 return BinaryOperator::CreateAnd(Shift,
7827 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007828 }
7829
7830 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7831 if (I.getOpcode() == Instruction::LShr) {
7832 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007833 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007834
7835 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007836 return BinaryOperator::CreateAnd(Shift,
7837 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007838 }
7839
7840 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7841 }
7842 }
7843 return 0;
7844}
7845
7846
7847/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7848/// expression. If so, decompose it, returning some value X, such that Val is
7849/// X*Scale+Offset.
7850///
7851static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007852 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007853 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7854 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7856 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007857 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007858 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007859 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7860 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7861 if (I->getOpcode() == Instruction::Shl) {
7862 // This is a value scaled by '1 << the shift amt'.
7863 Scale = 1U << RHS->getZExtValue();
7864 Offset = 0;
7865 return I->getOperand(0);
7866 } else if (I->getOpcode() == Instruction::Mul) {
7867 // This value is scaled by 'RHS'.
7868 Scale = RHS->getZExtValue();
7869 Offset = 0;
7870 return I->getOperand(0);
7871 } else if (I->getOpcode() == Instruction::Add) {
7872 // We have X+C. Check to see if we really have (X*C2)+C1,
7873 // where C1 is divisible by C2.
7874 unsigned SubScale;
7875 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007876 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7877 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007878 Offset += RHS->getZExtValue();
7879 Scale = SubScale;
7880 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007881 }
7882 }
7883 }
7884
7885 // Otherwise, we can't look past this.
7886 Scale = 1;
7887 Offset = 0;
7888 return Val;
7889}
7890
7891
7892/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7893/// try to eliminate the cast by moving the type information into the alloc.
7894Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00007895 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007896 const PointerType *PTy = cast<PointerType>(CI.getType());
7897
Chris Lattnerad7516a2009-08-30 18:50:58 +00007898 BuilderTy AllocaBuilder(*Builder);
7899 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7900
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007901 // Remove any uses of AI that are dead.
7902 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7903
7904 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7905 Instruction *User = cast<Instruction>(*UI++);
7906 if (isInstructionTriviallyDead(User)) {
7907 while (UI != E && *UI == User)
7908 ++UI; // If this instruction uses AI more than once, don't break UI.
7909
7910 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007911 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007912 EraseInstFromFunction(*User);
7913 }
7914 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007915
7916 // This requires TargetData to get the alloca alignment and size information.
7917 if (!TD) return 0;
7918
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007919 // Get the type really allocated and the type casted to.
7920 const Type *AllocElTy = AI.getAllocatedType();
7921 const Type *CastElTy = PTy->getElementType();
7922 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7923
7924 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7925 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7926 if (CastElTyAlign < AllocElTyAlign) return 0;
7927
7928 // If the allocation has multiple uses, only promote it if we are strictly
7929 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007930 // same, we open the door to infinite loops of various kinds. (A reference
7931 // from a dbg.declare doesn't count as a use for this purpose.)
7932 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7933 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007934
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007935 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7936 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007937 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7938
7939 // See if we can satisfy the modulus by pulling a scale out of the array
7940 // size argument.
7941 unsigned ArraySizeScale;
7942 int ArrayOffset;
7943 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007944 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7945 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007946
7947 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7948 // do the xform.
7949 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7950 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7951
7952 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7953 Value *Amt = 0;
7954 if (Scale == 1) {
7955 Amt = NumElements;
7956 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007957 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007958 // Insert before the alloca, not before the cast.
7959 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007960 }
7961
7962 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007963 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007964 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007965 }
7966
Victor Hernandezb1687302009-10-23 21:09:37 +00007967 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007968 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007969 New->takeName(&AI);
7970
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007971 // If the allocation has one real use plus a dbg.declare, just remove the
7972 // declare.
7973 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7974 EraseInstFromFunction(*DI);
7975 }
7976 // If the allocation has multiple real uses, insert a cast and change all
7977 // things that used it to use the new cast. This will also hack on CI, but it
7978 // will die soon.
7979 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007980 // New is the allocation instruction, pointer typed. AI is the original
7981 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007982 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007983 AI.replaceAllUsesWith(NewCast);
7984 }
7985 return ReplaceInstUsesWith(CI, New);
7986}
7987
7988/// CanEvaluateInDifferentType - Return true if we can take the specified value
7989/// and return it as type Ty without inserting any new casts and without
7990/// changing the computed value. This is used by code that tries to decide
7991/// whether promoting or shrinking integer operations to wider or smaller types
7992/// will allow us to eliminate a truncate or extend.
7993///
7994/// This is a truncation operation if Ty is smaller than V->getType(), or an
7995/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007996///
7997/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7998/// should return true if trunc(V) can be computed by computing V in the smaller
7999/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8000/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8001/// efficiently truncated.
8002///
8003/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8004/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8005/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008006bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00008007 unsigned CastOpc,
8008 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008010 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008011 return true;
8012
8013 Instruction *I = dyn_cast<Instruction>(V);
8014 if (!I) return false;
8015
Dan Gohman8fd520a2009-06-15 22:12:54 +00008016 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008017
Chris Lattneref70bb82007-08-02 06:11:14 +00008018 // If this is an extension or truncate, we can often eliminate it.
8019 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8020 // If this is a cast from the destination type, we can trivially eliminate
8021 // it, and this will remove a cast overall.
8022 if (I->getOperand(0)->getType() == Ty) {
8023 // If the first operand is itself a cast, and is eliminable, do not count
8024 // this as an eliminable cast. We would prefer to eliminate those two
8025 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00008026 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00008027 ++NumCastsRemoved;
8028 return true;
8029 }
8030 }
8031
8032 // We can't extend or shrink something that has multiple uses: doing so would
8033 // require duplicating the instruction in general, which isn't profitable.
8034 if (!I->hasOneUse()) return false;
8035
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008036 unsigned Opc = I->getOpcode();
8037 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008038 case Instruction::Add:
8039 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008040 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008041 case Instruction::And:
8042 case Instruction::Or:
8043 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008044 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00008045 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008046 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00008047 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008048 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008049
Eli Friedman08c45bc2009-07-13 22:46:01 +00008050 case Instruction::UDiv:
8051 case Instruction::URem: {
8052 // UDiv and URem can be truncated if all the truncated bits are zero.
8053 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8054 uint32_t BitWidth = Ty->getScalarSizeInBits();
8055 if (BitWidth < OrigBitWidth) {
8056 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8057 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8058 MaskedValueIsZero(I->getOperand(1), Mask)) {
8059 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8060 NumCastsRemoved) &&
8061 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8062 NumCastsRemoved);
8063 }
8064 }
8065 break;
8066 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008067 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008068 // If we are truncating the result of this SHL, and if it's a shift of a
8069 // constant amount, we can always perform a SHL in a smaller type.
8070 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008071 uint32_t BitWidth = Ty->getScalarSizeInBits();
8072 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008073 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008074 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008075 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008076 }
8077 break;
8078 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008079 // If this is a truncate of a logical shr, we can truncate it to a smaller
8080 // lshr iff we know that the bits we would otherwise be shifting in are
8081 // already zeros.
8082 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008083 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8084 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008085 if (BitWidth < OrigBitWidth &&
8086 MaskedValueIsZero(I->getOperand(0),
8087 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8088 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008089 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008090 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008091 }
8092 }
8093 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008094 case Instruction::ZExt:
8095 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008096 case Instruction::Trunc:
8097 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008098 // can safely replace it. Note that replacing it does not reduce the number
8099 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008100 if (Opc == CastOpc)
8101 return true;
8102
8103 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008104 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008105 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008106 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008107 case Instruction::Select: {
8108 SelectInst *SI = cast<SelectInst>(I);
8109 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008110 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008111 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008112 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008113 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008114 case Instruction::PHI: {
8115 // We can change a phi if we can change all operands.
8116 PHINode *PN = cast<PHINode>(I);
8117 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8118 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008119 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008120 return false;
8121 return true;
8122 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008123 default:
8124 // TODO: Can handle more cases here.
8125 break;
8126 }
8127
8128 return false;
8129}
8130
8131/// EvaluateInDifferentType - Given an expression that
8132/// CanEvaluateInDifferentType returns true for, actually insert the code to
8133/// evaluate the expression.
8134Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8135 bool isSigned) {
8136 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008137 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008138
8139 // Otherwise, it must be an instruction.
8140 Instruction *I = cast<Instruction>(V);
8141 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008142 unsigned Opc = I->getOpcode();
8143 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008144 case Instruction::Add:
8145 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008146 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008147 case Instruction::And:
8148 case Instruction::Or:
8149 case Instruction::Xor:
8150 case Instruction::AShr:
8151 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008152 case Instruction::Shl:
8153 case Instruction::UDiv:
8154 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008155 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8156 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008157 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008158 break;
8159 }
8160 case Instruction::Trunc:
8161 case Instruction::ZExt:
8162 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008163 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008164 // just return the source. There's no need to insert it because it is not
8165 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008166 if (I->getOperand(0)->getType() == Ty)
8167 return I->getOperand(0);
8168
Chris Lattner4200c2062008-06-18 04:00:49 +00008169 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008170 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008171 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008172 case Instruction::Select: {
8173 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8174 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8175 Res = SelectInst::Create(I->getOperand(0), True, False);
8176 break;
8177 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008178 case Instruction::PHI: {
8179 PHINode *OPN = cast<PHINode>(I);
8180 PHINode *NPN = PHINode::Create(Ty);
8181 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8182 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8183 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8184 }
8185 Res = NPN;
8186 break;
8187 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008188 default:
8189 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008190 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008191 break;
8192 }
8193
Chris Lattner4200c2062008-06-18 04:00:49 +00008194 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008195 return InsertNewInstBefore(Res, *I);
8196}
8197
8198/// @brief Implement the transforms common to all CastInst visitors.
8199Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8200 Value *Src = CI.getOperand(0);
8201
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008202 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8203 // eliminate it now.
8204 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8205 if (Instruction::CastOps opc =
8206 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8207 // The first cast (CSrc) is eliminable so we need to fix up or replace
8208 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008209 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008210 }
8211 }
8212
8213 // If we are casting a select then fold the cast into the select
8214 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8215 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8216 return NV;
8217
8218 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00008219 if (isa<PHINode>(Src)) {
8220 // We don't do this if this would create a PHI node with an illegal type if
8221 // it is currently legal.
8222 if (!isa<IntegerType>(Src->getType()) ||
8223 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerd0011092009-11-10 07:23:37 +00008224 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008225 if (Instruction *NV = FoldOpIntoPhi(CI))
8226 return NV;
Chris Lattner1cd526b2009-11-08 19:23:30 +00008227 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008228
8229 return 0;
8230}
8231
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008232/// FindElementAtOffset - Given a type and a constant offset, determine whether
8233/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008234/// the specified offset. If so, fill them into NewIndices and return the
8235/// resultant element type, otherwise return null.
8236static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8237 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008238 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008239 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008240 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008241 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008242
8243 // Start with the index over the outer type. Note that the type size
8244 // might be zero (even if the offset isn't zero) if the indexed type
8245 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008246 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008247 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008248 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008249 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008250 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008251
Chris Lattnerce48c462009-01-11 20:15:20 +00008252 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008253 if (Offset < 0) {
8254 --FirstIdx;
8255 Offset += TySize;
8256 assert(Offset >= 0);
8257 }
8258 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8259 }
8260
Owen Andersoneacb44d2009-07-24 23:12:02 +00008261 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008262
8263 // Index into the types. If we fail, set OrigBase to null.
8264 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008265 // Indexing into tail padding between struct/array elements.
8266 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008267 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008268
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008269 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8270 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008271 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8272 "Offset must stay within the indexed type");
8273
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008274 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008275 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008276
8277 Offset -= SL->getElementOffset(Elt);
8278 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008279 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008280 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008281 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008282 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008283 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008284 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008285 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008286 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008287 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008288 }
8289 }
8290
Chris Lattner54dddc72009-01-24 01:00:13 +00008291 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008292}
8293
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008294/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8295Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8296 Value *Src = CI.getOperand(0);
8297
8298 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8299 // If casting the result of a getelementptr instruction with no offset, turn
8300 // this into a cast of the original pointer!
8301 if (GEP->hasAllZeroIndices()) {
8302 // Changing the cast operand is usually not a good idea but it is safe
8303 // here because the pointer operand is being replaced with another
8304 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008305 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008306 CI.setOperand(0, GEP->getOperand(0));
8307 return &CI;
8308 }
8309
8310 // If the GEP has a single use, and the base pointer is a bitcast, and the
8311 // GEP computes a constant offset, see if we can convert these three
8312 // instructions into fewer. This typically happens with unions and other
8313 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008314 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008315 if (GEP->hasAllConstantIndices()) {
8316 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +00008317 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 int64_t Offset = OffsetV->getSExtValue();
8319
8320 // Get the base pointer input of the bitcast, and the type it points to.
8321 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8322 const Type *GEPIdxTy =
8323 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008324 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008325 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008326 // If we were able to index down into an element, create the GEP
8327 // and bitcast the result. This eliminates one bitcast, potentially
8328 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008329 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8330 Builder->CreateInBoundsGEP(OrigBase,
8331 NewIndices.begin(), NewIndices.end()) :
8332 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008333 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008334
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008335 if (isa<BitCastInst>(CI))
8336 return new BitCastInst(NGEP, CI.getType());
8337 assert(isa<PtrToIntInst>(CI));
8338 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008339 }
8340 }
8341 }
8342 }
8343
8344 return commonCastTransforms(CI);
8345}
8346
Eli Friedman827e37a2009-07-13 20:58:59 +00008347/// commonIntCastTransforms - This function implements the common transforms
8348/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008349Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8350 if (Instruction *Result = commonCastTransforms(CI))
8351 return Result;
8352
8353 Value *Src = CI.getOperand(0);
8354 const Type *SrcTy = Src->getType();
8355 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008356 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8357 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008358
8359 // See if we can simplify any instructions used by the LHS whose sole
8360 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008361 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008362 return &CI;
8363
8364 // If the source isn't an instruction or has more than one use then we
8365 // can't do anything more.
8366 Instruction *SrcI = dyn_cast<Instruction>(Src);
8367 if (!SrcI || !Src->hasOneUse())
8368 return 0;
8369
8370 // Attempt to propagate the cast into the instruction for int->int casts.
8371 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008372 // Only do this if the dest type is a simple type, don't convert the
8373 // expression tree to something weird like i93 unless the source is also
8374 // strange.
Chris Lattnerbc5d0132009-11-10 17:00:47 +00008375 if ((isa<VectorType>(DestTy) ||
8376 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8377 CanEvaluateInDifferentType(SrcI, DestTy,
8378 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008379 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008380 // eliminates the cast, so it is always a win. If this is a zero-extension,
8381 // we need to do an AND to maintain the clear top-part of the computation,
8382 // so we require that the input have eliminated at least one cast. If this
8383 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008384 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008385 bool DoXForm = false;
8386 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008387 switch (CI.getOpcode()) {
8388 default:
8389 // All the others use floating point so we shouldn't actually
8390 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008391 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008392 case Instruction::Trunc:
8393 DoXForm = true;
8394 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008395 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008396 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008397
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008398 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008399 // If it's unnecessary to issue an AND to clear the high bits, it's
8400 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008401 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008402 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8403 if (MaskedValueIsZero(TryRes, Mask))
8404 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008405
8406 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008407 if (TryI->use_empty())
8408 EraseInstFromFunction(*TryI);
8409 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008410 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008411 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008412 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008414 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008415 // If we do not have to emit the truncate + sext pair, then it's always
8416 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008417 //
8418 // It's not safe to eliminate the trunc + sext pair if one of the
8419 // eliminated cast is a truncate. e.g.
8420 // t2 = trunc i32 t1 to i16
8421 // t3 = sext i16 t2 to i32
8422 // !=
8423 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008424 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008425 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8426 if (NumSignBits > (DestBitSize - SrcBitSize))
8427 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008428
8429 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008430 if (TryI->use_empty())
8431 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008432 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008434 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008435 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008436
8437 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008438 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8439 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008440 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8441 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008442 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008443 // Just replace this cast with the result.
8444 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008445
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008446 assert(Res->getType() == DestTy);
8447 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008448 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008449 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008450 // Just replace this cast with the result.
8451 return ReplaceInstUsesWith(CI, Res);
8452 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008453 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008454
8455 // If the high bits are already zero, just replace this cast with the
8456 // result.
8457 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8458 if (MaskedValueIsZero(Res, Mask))
8459 return ReplaceInstUsesWith(CI, Res);
8460
8461 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008462 Constant *C = ConstantInt::get(*Context,
8463 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008464 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008465 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008466 case Instruction::SExt: {
8467 // If the high bits are already filled with sign bit, just replace this
8468 // cast with the result.
8469 unsigned NumSignBits = ComputeNumSignBits(Res);
8470 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008471 return ReplaceInstUsesWith(CI, Res);
8472
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008473 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008474 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008475 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008476 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008477 }
8478 }
8479
8480 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8481 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8482
8483 switch (SrcI->getOpcode()) {
8484 case Instruction::Add:
8485 case Instruction::Mul:
8486 case Instruction::And:
8487 case Instruction::Or:
8488 case Instruction::Xor:
8489 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008490 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8491 // Don't insert two casts unless at least one can be eliminated.
8492 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008493 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008494 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8495 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008496 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008497 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8498 }
8499 }
8500
8501 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8502 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8503 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008504 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008505 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008506 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008507 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008508 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008509 }
8510 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008511
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008512 case Instruction::Shl: {
8513 // Canonicalize trunc inside shl, if we can.
8514 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8515 if (CI && DestBitSize < SrcBitSize &&
8516 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008517 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8518 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008519 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008520 }
8521 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008522 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008523 }
8524 return 0;
8525}
8526
8527Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8528 if (Instruction *Result = commonIntCastTransforms(CI))
8529 return Result;
8530
8531 Value *Src = CI.getOperand(0);
8532 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008533 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8534 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008535
8536 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008537 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008538 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008539 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008540 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008541 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008542 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008543
Chris Lattner32177f82009-03-24 18:15:30 +00008544 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8545 ConstantInt *ShAmtV = 0;
8546 Value *ShiftOp = 0;
8547 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008548 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008549 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8550
8551 // Get a mask for the bits shifting in.
8552 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8553 if (MaskedValueIsZero(ShiftOp, Mask)) {
8554 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008555 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008556
8557 // Okay, we can shrink this. Truncate the input, then return a new
8558 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008559 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008560 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008561 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008562 }
8563 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008564
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008565 return 0;
8566}
8567
Evan Chenge3779cf2008-03-24 00:21:34 +00008568/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8569/// in order to eliminate the icmp.
8570Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8571 bool DoXform) {
8572 // If we are just checking for a icmp eq of a single bit and zext'ing it
8573 // to an integer, then shift the bit to the appropriate place and then
8574 // cast to integer to avoid the comparison.
8575 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8576 const APInt &Op1CV = Op1C->getValue();
8577
8578 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8579 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8580 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8581 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8582 if (!DoXform) return ICI;
8583
8584 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008585 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008586 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008587 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008588 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008589 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008590
8591 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008592 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008593 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008594 }
8595
8596 return ReplaceInstUsesWith(CI, In);
8597 }
8598
8599
8600
8601 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8602 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8603 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8604 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8605 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8606 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8607 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8608 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8609 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8610 // This only works for EQ and NE
8611 ICI->isEquality()) {
8612 // If Op1C some other power of two, convert:
8613 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8614 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8615 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8616 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8617
8618 APInt KnownZeroMask(~KnownZero);
8619 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8620 if (!DoXform) return ICI;
8621
8622 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8623 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8624 // (X&4) == 2 --> false
8625 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008626 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008627 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008628 return ReplaceInstUsesWith(CI, Res);
8629 }
8630
8631 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8632 Value *In = ICI->getOperand(0);
8633 if (ShiftAmt) {
8634 // Perform a logical shr by shiftamt.
8635 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008636 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8637 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008638 }
8639
8640 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008641 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008642 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008643 }
8644
8645 if (CI.getType() == In->getType())
8646 return ReplaceInstUsesWith(CI, In);
8647 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008648 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008649 }
8650 }
8651 }
8652
Nick Lewyckyef61f692009-11-23 03:17:33 +00008653 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8654 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8655 // may lead to additional simplifications.
8656 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8657 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8658 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008659 Value *LHS = ICI->getOperand(0);
8660 Value *RHS = ICI->getOperand(1);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008661
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008662 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8663 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8664 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8665 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8666 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008667
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008668 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8669 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8670 APInt UnknownBit = ~KnownBits;
8671 if (UnknownBit.countPopulation() == 1) {
Nick Lewyckyef61f692009-11-23 03:17:33 +00008672 if (!DoXform) return ICI;
8673
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008674 Value *Result = Builder->CreateXor(LHS, RHS);
8675
8676 // Mask off any bits that are set and won't be shifted away.
8677 if (KnownOneLHS.uge(UnknownBit))
8678 Result = Builder->CreateAnd(Result,
8679 ConstantInt::get(ITy, UnknownBit));
8680
8681 // Shift the bit we're testing down to the lsb.
8682 Result = Builder->CreateLShr(
8683 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8684
Nick Lewyckyef61f692009-11-23 03:17:33 +00008685 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008686 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8687 Result->takeName(ICI);
8688 return ReplaceInstUsesWith(CI, Result);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008689 }
8690 }
8691 }
8692 }
8693
Evan Chenge3779cf2008-03-24 00:21:34 +00008694 return 0;
8695}
8696
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008697Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8698 // If one of the common conversion will work ..
8699 if (Instruction *Result = commonIntCastTransforms(CI))
8700 return Result;
8701
8702 Value *Src = CI.getOperand(0);
8703
Chris Lattner215d56e2009-02-17 20:47:23 +00008704 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8705 // types and if the sizes are just right we can convert this into a logical
8706 // 'and' which will be much cheaper than the pair of casts.
8707 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8708 // Get the sizes of the types involved. We know that the intermediate type
8709 // will be smaller than A or C, but don't know the relation between A and C.
8710 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008711 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8712 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8713 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008714 // If we're actually extending zero bits, then if
8715 // SrcSize < DstSize: zext(a & mask)
8716 // SrcSize == DstSize: a & mask
8717 // SrcSize > DstSize: trunc(a) & mask
8718 if (SrcSize < DstSize) {
8719 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008720 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008721 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008722 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008723 }
8724
8725 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008726 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008727 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008728 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008729 }
8730 if (SrcSize > DstSize) {
8731 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008732 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008733 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008734 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008735 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008736 }
8737 }
8738
Evan Chenge3779cf2008-03-24 00:21:34 +00008739 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8740 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008741
Evan Chenge3779cf2008-03-24 00:21:34 +00008742 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8743 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8744 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8745 // of the (zext icmp) will be transformed.
8746 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8747 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8748 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8749 (transformZExtICmp(LHS, CI, false) ||
8750 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008751 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8752 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008753 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008754 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008755 }
8756
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008757 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008758 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8759 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8760 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8761 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008762 if (TI0->getType() == CI.getType())
8763 return
8764 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008765 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008766 }
8767
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008768 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8769 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8770 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8771 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8772 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8773 And->getOperand(1) == C)
8774 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8775 Value *TI0 = TI->getOperand(0);
8776 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008777 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008778 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008779 return BinaryOperator::CreateXor(NewAnd, ZC);
8780 }
8781 }
8782
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008783 return 0;
8784}
8785
8786Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8787 if (Instruction *I = commonIntCastTransforms(CI))
8788 return I;
8789
8790 Value *Src = CI.getOperand(0);
8791
Dan Gohman35b76162008-10-30 20:40:10 +00008792 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008793 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008794 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008795 Constant::getAllOnesValue(CI.getType()),
8796 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008797
8798 // See if the value being truncated is already sign extended. If so, just
8799 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008800 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008801 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008802 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8803 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8804 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008805 unsigned NumSignBits = ComputeNumSignBits(Op);
8806
8807 if (OpBits == DestBits) {
8808 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8809 // bits, it is already ready.
8810 if (NumSignBits > DestBits-MidBits)
8811 return ReplaceInstUsesWith(CI, Op);
8812 } else if (OpBits < DestBits) {
8813 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8814 // bits, just sext from i32.
8815 if (NumSignBits > OpBits-MidBits)
8816 return new SExtInst(Op, CI.getType(), "tmp");
8817 } else {
8818 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8819 // bits, just truncate to i32.
8820 if (NumSignBits > OpBits-MidBits)
8821 return new TruncInst(Op, CI.getType(), "tmp");
8822 }
8823 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008824
8825 // If the input is a shl/ashr pair of a same constant, then this is a sign
8826 // extension from a smaller value. If we could trust arbitrary bitwidth
8827 // integers, we could turn this into a truncate to the smaller bit and then
8828 // use a sext for the whole extension. Since we don't, look deeper and check
8829 // for a truncate. If the source and dest are the same type, eliminate the
8830 // trunc and extend and just do shifts. For example, turn:
8831 // %a = trunc i32 %i to i8
8832 // %b = shl i8 %a, 6
8833 // %c = ashr i8 %b, 6
8834 // %d = sext i8 %c to i32
8835 // into:
8836 // %a = shl i32 %i, 30
8837 // %d = ashr i32 %a, 30
8838 Value *A = 0;
8839 ConstantInt *BA = 0, *CA = 0;
8840 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008841 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008842 BA == CA && isa<TruncInst>(A)) {
8843 Value *I = cast<TruncInst>(A)->getOperand(0);
8844 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008845 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8846 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008847 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008848 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008849 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008850 return BinaryOperator::CreateAShr(I, ShAmtV);
8851 }
8852 }
8853
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008854 return 0;
8855}
8856
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008857/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8858/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008859static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008860 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008861 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008862 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008863 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8864 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008865 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008866 return 0;
8867}
8868
8869/// LookThroughFPExtensions - If this is an fp extension instruction, look
8870/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008871static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008872 if (Instruction *I = dyn_cast<Instruction>(V))
8873 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008874 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008875
8876 // If this value is a constant, return the constant in the smallest FP type
8877 // that can accurately represent it. This allows us to turn
8878 // (float)((double)X+2.0) into x+2.0f.
8879 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008880 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008881 return V; // No constant folding of this.
8882 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008883 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008884 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008885 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008886 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008887 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008888 return V;
8889 // Don't try to shrink to various long double types.
8890 }
8891
8892 return V;
8893}
8894
8895Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8896 if (Instruction *I = commonCastTransforms(CI))
8897 return I;
8898
Dan Gohman7ce405e2009-06-04 22:49:04 +00008899 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008900 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008901 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008902 // many builtins (sqrt, etc).
8903 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8904 if (OpI && OpI->hasOneUse()) {
8905 switch (OpI->getOpcode()) {
8906 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008907 case Instruction::FAdd:
8908 case Instruction::FSub:
8909 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008910 case Instruction::FDiv:
8911 case Instruction::FRem:
8912 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008913 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8914 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008915 if (LHSTrunc->getType() != SrcTy &&
8916 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008917 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008918 // If the source types were both smaller than the destination type of
8919 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008920 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8921 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008922 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8923 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008924 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008925 }
8926 }
8927 break;
8928 }
8929 }
8930 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008931}
8932
8933Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8934 return commonCastTransforms(CI);
8935}
8936
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008937Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008938 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8939 if (OpI == 0)
8940 return commonCastTransforms(FI);
8941
8942 // fptoui(uitofp(X)) --> X
8943 // fptoui(sitofp(X)) --> X
8944 // This is safe if the intermediate type has enough bits in its mantissa to
8945 // accurately represent all values of X. For example, do not do this with
8946 // i64->float->i64. This is also safe for sitofp case, because any negative
8947 // 'X' value would cause an undefined result for the fptoui.
8948 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8949 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008950 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008951 OpI->getType()->getFPMantissaWidth())
8952 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008953
8954 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008955}
8956
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008957Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008958 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8959 if (OpI == 0)
8960 return commonCastTransforms(FI);
8961
8962 // fptosi(sitofp(X)) --> X
8963 // fptosi(uitofp(X)) --> X
8964 // This is safe if the intermediate type has enough bits in its mantissa to
8965 // accurately represent all values of X. For example, do not do this with
8966 // i64->float->i64. This is also safe for sitofp case, because any negative
8967 // 'X' value would cause an undefined result for the fptoui.
8968 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8969 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008970 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008971 OpI->getType()->getFPMantissaWidth())
8972 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008973
8974 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008975}
8976
8977Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8978 return commonCastTransforms(CI);
8979}
8980
8981Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8982 return commonCastTransforms(CI);
8983}
8984
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008985Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8986 // If the destination integer type is smaller than the intptr_t type for
8987 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8988 // trunc to be exposed to other transforms. Don't do this for extending
8989 // ptrtoint's, because we don't know if the target sign or zero extends its
8990 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008991 if (TD &&
8992 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008993 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8994 TD->getIntPtrType(CI.getContext()),
8995 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008996 return new TruncInst(P, CI.getType());
8997 }
8998
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008999 return commonPointerCastTransforms(CI);
9000}
9001
Chris Lattner7c1626482008-01-08 07:23:51 +00009002Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009003 // If the source integer type is larger than the intptr_t type for
9004 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9005 // allows the trunc to be exposed to other transforms. Don't do this for
9006 // extending inttoptr's, because we don't know if the target sign or zero
9007 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009008 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009009 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009010 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9011 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009012 return new IntToPtrInst(P, CI.getType());
9013 }
9014
Chris Lattner7c1626482008-01-08 07:23:51 +00009015 if (Instruction *I = commonCastTransforms(CI))
9016 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00009017
Chris Lattner7c1626482008-01-08 07:23:51 +00009018 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009019}
9020
9021Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9022 // If the operands are integer typed then apply the integer transforms,
9023 // otherwise just apply the common ones.
9024 Value *Src = CI.getOperand(0);
9025 const Type *SrcTy = Src->getType();
9026 const Type *DestTy = CI.getType();
9027
Eli Friedman5013d3f2009-07-13 20:53:00 +00009028 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009029 if (Instruction *I = commonPointerCastTransforms(CI))
9030 return I;
9031 } else {
9032 if (Instruction *Result = commonCastTransforms(CI))
9033 return Result;
9034 }
9035
9036
9037 // Get rid of casts from one type to the same type. These are useless and can
9038 // be replaced by the operand.
9039 if (DestTy == Src->getType())
9040 return ReplaceInstUsesWith(CI, Src);
9041
9042 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9043 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9044 const Type *DstElTy = DstPTy->getElementType();
9045 const Type *SrcElTy = SrcPTy->getElementType();
9046
Nate Begemandf5b3612008-03-31 00:22:16 +00009047 // If the address spaces don't match, don't eliminate the bitcast, which is
9048 // required for changing types.
9049 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9050 return 0;
9051
Victor Hernandez48c3c542009-09-18 22:35:49 +00009052 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009053 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00009054 // There is no need to modify malloc calls because it is their bitcast that
9055 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00009056 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009057 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9058 return V;
9059
9060 // If the source and destination are pointers, and this cast is equivalent
9061 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9062 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00009063 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009064 unsigned NumZeros = 0;
9065 while (SrcElTy != DstElTy &&
9066 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9067 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9068 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9069 ++NumZeros;
9070 }
9071
9072 // If we found a path from the src to dest, create the getelementptr now.
9073 if (SrcElTy == DstElTy) {
9074 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00009075 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9076 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009077 }
9078 }
9079
Eli Friedman1d31dee2009-07-18 23:06:53 +00009080 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9081 if (DestVTy->getNumElements() == 1) {
9082 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009083 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009084 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00009085 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009086 }
9087 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9088 }
9089 }
9090
9091 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9092 if (SrcVTy->getNumElements() == 1) {
9093 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009094 Value *Elem =
9095 Builder->CreateExtractElement(Src,
9096 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009097 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9098 }
9099 }
9100 }
9101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009102 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9103 if (SVI->hasOneUse()) {
9104 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9105 // a bitconvert to a vector with the same # elts.
9106 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009107 cast<VectorType>(DestTy)->getNumElements() ==
9108 SVI->getType()->getNumElements() &&
9109 SVI->getType()->getNumElements() ==
9110 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009111 CastInst *Tmp;
9112 // If either of the operands is a cast from CI.getType(), then
9113 // evaluating the shuffle in the casted destination's type will allow
9114 // us to eliminate at least one cast.
9115 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9116 Tmp->getOperand(0)->getType() == DestTy) ||
9117 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9118 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009119 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9120 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009121 // Return a new shuffle vector. Use the same element ID's, as we
9122 // know the vector types match #elts.
9123 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9124 }
9125 }
9126 }
9127 }
9128 return 0;
9129}
9130
9131/// GetSelectFoldableOperands - We want to turn code that looks like this:
9132/// %C = or %A, %B
9133/// %D = select %cond, %C, %A
9134/// into:
9135/// %C = select %cond, %B, 0
9136/// %D = or %A, %C
9137///
9138/// Assuming that the specified instruction is an operand to the select, return
9139/// a bitmask indicating which operands of this instruction are foldable if they
9140/// equal the other incoming value of the select.
9141///
9142static unsigned GetSelectFoldableOperands(Instruction *I) {
9143 switch (I->getOpcode()) {
9144 case Instruction::Add:
9145 case Instruction::Mul:
9146 case Instruction::And:
9147 case Instruction::Or:
9148 case Instruction::Xor:
9149 return 3; // Can fold through either operand.
9150 case Instruction::Sub: // Can only fold on the amount subtracted.
9151 case Instruction::Shl: // Can only fold on the shift amount.
9152 case Instruction::LShr:
9153 case Instruction::AShr:
9154 return 1;
9155 default:
9156 return 0; // Cannot fold
9157 }
9158}
9159
9160/// GetSelectFoldableConstant - For the same transformation as the previous
9161/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009162static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009163 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009164 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009165 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009166 case Instruction::Add:
9167 case Instruction::Sub:
9168 case Instruction::Or:
9169 case Instruction::Xor:
9170 case Instruction::Shl:
9171 case Instruction::LShr:
9172 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009173 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009174 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009175 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009176 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009177 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009178 }
9179}
9180
9181/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9182/// have the same opcode and only one use each. Try to simplify this.
9183Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9184 Instruction *FI) {
9185 if (TI->getNumOperands() == 1) {
9186 // If this is a non-volatile load or a cast from the same type,
9187 // merge.
9188 if (TI->isCast()) {
9189 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9190 return 0;
9191 } else {
9192 return 0; // unknown unary op.
9193 }
9194
9195 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009196 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009197 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009198 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009199 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009200 TI->getType());
9201 }
9202
9203 // Only handle binary operators here.
9204 if (!isa<BinaryOperator>(TI))
9205 return 0;
9206
9207 // Figure out if the operations have any operands in common.
9208 Value *MatchOp, *OtherOpT, *OtherOpF;
9209 bool MatchIsOpZero;
9210 if (TI->getOperand(0) == FI->getOperand(0)) {
9211 MatchOp = TI->getOperand(0);
9212 OtherOpT = TI->getOperand(1);
9213 OtherOpF = FI->getOperand(1);
9214 MatchIsOpZero = true;
9215 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9216 MatchOp = TI->getOperand(1);
9217 OtherOpT = TI->getOperand(0);
9218 OtherOpF = FI->getOperand(0);
9219 MatchIsOpZero = false;
9220 } else if (!TI->isCommutative()) {
9221 return 0;
9222 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9223 MatchOp = TI->getOperand(0);
9224 OtherOpT = TI->getOperand(1);
9225 OtherOpF = FI->getOperand(0);
9226 MatchIsOpZero = true;
9227 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9228 MatchOp = TI->getOperand(1);
9229 OtherOpT = TI->getOperand(0);
9230 OtherOpF = FI->getOperand(1);
9231 MatchIsOpZero = true;
9232 } else {
9233 return 0;
9234 }
9235
9236 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009237 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9238 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009239 InsertNewInstBefore(NewSI, SI);
9240
9241 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9242 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009243 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009244 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009245 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009246 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009247 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009248 return 0;
9249}
9250
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009251static bool isSelect01(Constant *C1, Constant *C2) {
9252 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9253 if (!C1I)
9254 return false;
9255 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9256 if (!C2I)
9257 return false;
9258 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9259}
9260
9261/// FoldSelectIntoOp - Try fold the select into one of the operands to
9262/// facilitate further optimization.
9263Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9264 Value *FalseVal) {
9265 // See the comment above GetSelectFoldableOperands for a description of the
9266 // transformation we are doing here.
9267 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9268 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9269 !isa<Constant>(FalseVal)) {
9270 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9271 unsigned OpToFold = 0;
9272 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9273 OpToFold = 1;
9274 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9275 OpToFold = 2;
9276 }
9277
9278 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009279 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009280 Value *OOp = TVI->getOperand(2-OpToFold);
9281 // Avoid creating select between 2 constants unless it's selecting
9282 // between 0 and 1.
9283 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9284 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9285 InsertNewInstBefore(NewSel, SI);
9286 NewSel->takeName(TVI);
9287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9288 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009289 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009290 }
9291 }
9292 }
9293 }
9294 }
9295
9296 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9297 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9298 !isa<Constant>(TrueVal)) {
9299 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9300 unsigned OpToFold = 0;
9301 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9302 OpToFold = 1;
9303 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9304 OpToFold = 2;
9305 }
9306
9307 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009308 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009309 Value *OOp = FVI->getOperand(2-OpToFold);
9310 // Avoid creating select between 2 constants unless it's selecting
9311 // between 0 and 1.
9312 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9313 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9314 InsertNewInstBefore(NewSel, SI);
9315 NewSel->takeName(FVI);
9316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9317 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009318 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009319 }
9320 }
9321 }
9322 }
9323 }
9324
9325 return 0;
9326}
9327
Dan Gohman58c09632008-09-16 18:46:06 +00009328/// visitSelectInstWithICmp - Visit a SelectInst that has an
9329/// ICmpInst as its first operand.
9330///
9331Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9332 ICmpInst *ICI) {
9333 bool Changed = false;
9334 ICmpInst::Predicate Pred = ICI->getPredicate();
9335 Value *CmpLHS = ICI->getOperand(0);
9336 Value *CmpRHS = ICI->getOperand(1);
9337 Value *TrueVal = SI.getTrueValue();
9338 Value *FalseVal = SI.getFalseValue();
9339
9340 // Check cases where the comparison is with a constant that
9341 // can be adjusted to fit the min/max idiom. We may edit ICI in
9342 // place here, so make sure the select is the only user.
9343 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009344 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009345 switch (Pred) {
9346 default: break;
9347 case ICmpInst::ICMP_ULT:
9348 case ICmpInst::ICMP_SLT: {
9349 // X < MIN ? T : F --> F
9350 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9351 return ReplaceInstUsesWith(SI, FalseVal);
9352 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009353 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009354 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9355 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9356 Pred = ICmpInst::getSwappedPredicate(Pred);
9357 CmpRHS = AdjustedRHS;
9358 std::swap(FalseVal, TrueVal);
9359 ICI->setPredicate(Pred);
9360 ICI->setOperand(1, CmpRHS);
9361 SI.setOperand(1, TrueVal);
9362 SI.setOperand(2, FalseVal);
9363 Changed = true;
9364 }
9365 break;
9366 }
9367 case ICmpInst::ICMP_UGT:
9368 case ICmpInst::ICMP_SGT: {
9369 // X > MAX ? T : F --> F
9370 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9371 return ReplaceInstUsesWith(SI, FalseVal);
9372 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009373 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009374 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9375 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9376 Pred = ICmpInst::getSwappedPredicate(Pred);
9377 CmpRHS = AdjustedRHS;
9378 std::swap(FalseVal, TrueVal);
9379 ICI->setPredicate(Pred);
9380 ICI->setOperand(1, CmpRHS);
9381 SI.setOperand(1, TrueVal);
9382 SI.setOperand(2, FalseVal);
9383 Changed = true;
9384 }
9385 break;
9386 }
9387 }
9388
Dan Gohman35b76162008-10-30 20:40:10 +00009389 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9390 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009391 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009392 if (match(TrueVal, m_ConstantInt<-1>()) &&
9393 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009394 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009395 else if (match(TrueVal, m_ConstantInt<0>()) &&
9396 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009397 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9398
Dan Gohman35b76162008-10-30 20:40:10 +00009399 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9400 // If we are just checking for a icmp eq of a single bit and zext'ing it
9401 // to an integer, then shift the bit to the appropriate place and then
9402 // cast to integer to avoid the comparison.
9403 const APInt &Op1CV = CI->getValue();
9404
9405 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9406 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9407 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009408 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009409 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009410 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009411 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009412 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009413 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009414 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009415 if (In->getType() != SI.getType())
9416 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009417 true/*SExt*/, "tmp", ICI);
9418
9419 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009420 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009421 In->getName()+".not"), *ICI);
9422
9423 return ReplaceInstUsesWith(SI, In);
9424 }
9425 }
9426 }
9427
Dan Gohman58c09632008-09-16 18:46:06 +00009428 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9429 // Transform (X == Y) ? X : Y -> Y
9430 if (Pred == ICmpInst::ICMP_EQ)
9431 return ReplaceInstUsesWith(SI, FalseVal);
9432 // Transform (X != Y) ? X : Y -> X
9433 if (Pred == ICmpInst::ICMP_NE)
9434 return ReplaceInstUsesWith(SI, TrueVal);
9435 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9436
9437 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9438 // Transform (X == Y) ? Y : X -> X
9439 if (Pred == ICmpInst::ICMP_EQ)
9440 return ReplaceInstUsesWith(SI, FalseVal);
9441 // Transform (X != Y) ? Y : X -> Y
9442 if (Pred == ICmpInst::ICMP_NE)
9443 return ReplaceInstUsesWith(SI, TrueVal);
9444 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9445 }
9446
9447 /// NOTE: if we wanted to, this is where to detect integer ABS
9448
9449 return Changed ? &SI : 0;
9450}
9451
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009452
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009453/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9454/// PHI node (but the two may be in different blocks). See if the true/false
9455/// values (V) are live in all of the predecessor blocks of the PHI. For
9456/// example, cases like this cannot be mapped:
9457///
9458/// X = phi [ C1, BB1], [C2, BB2]
9459/// Y = add
9460/// Z = select X, Y, 0
9461///
9462/// because Y is not live in BB1/BB2.
9463///
9464static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9465 const SelectInst &SI) {
9466 // If the value is a non-instruction value like a constant or argument, it
9467 // can always be mapped.
9468 const Instruction *I = dyn_cast<Instruction>(V);
9469 if (I == 0) return true;
9470
9471 // If V is a PHI node defined in the same block as the condition PHI, we can
9472 // map the arguments.
9473 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9474
9475 if (const PHINode *VP = dyn_cast<PHINode>(I))
9476 if (VP->getParent() == CondPHI->getParent())
9477 return true;
9478
9479 // Otherwise, if the PHI and select are defined in the same block and if V is
9480 // defined in a different block, then we can transform it.
9481 if (SI.getParent() == CondPHI->getParent() &&
9482 I->getParent() != CondPHI->getParent())
9483 return true;
9484
9485 // Otherwise we have a 'hard' case and we can't tell without doing more
9486 // detailed dominator based analysis, punt.
9487 return false;
9488}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009489
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009490Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9491 Value *CondVal = SI.getCondition();
9492 Value *TrueVal = SI.getTrueValue();
9493 Value *FalseVal = SI.getFalseValue();
9494
9495 // select true, X, Y -> X
9496 // select false, X, Y -> Y
9497 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9498 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9499
9500 // select C, X, X -> X
9501 if (TrueVal == FalseVal)
9502 return ReplaceInstUsesWith(SI, TrueVal);
9503
9504 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9505 return ReplaceInstUsesWith(SI, FalseVal);
9506 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9507 return ReplaceInstUsesWith(SI, TrueVal);
9508 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9509 if (isa<Constant>(TrueVal))
9510 return ReplaceInstUsesWith(SI, TrueVal);
9511 else
9512 return ReplaceInstUsesWith(SI, FalseVal);
9513 }
9514
Owen Anderson35b47072009-08-13 21:58:54 +00009515 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009516 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9517 if (C->getZExtValue()) {
9518 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009519 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009520 } else {
9521 // Change: A = select B, false, C --> A = and !B, C
9522 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009523 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009524 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009525 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009526 }
9527 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9528 if (C->getZExtValue() == false) {
9529 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009530 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009531 } else {
9532 // Change: A = select B, C, true --> A = or !B, C
9533 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009534 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009535 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009536 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009537 }
9538 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009539
9540 // select a, b, a -> a&b
9541 // select a, a, b -> a|b
9542 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009543 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009544 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009545 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009546 }
9547
9548 // Selecting between two integer constants?
9549 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9550 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9551 // select C, 1, 0 -> zext C to int
9552 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009553 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009554 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9555 // select C, 0, 1 -> zext !C to int
9556 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009557 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009558 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009559 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009560 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009561
9562 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009563 // If one of the constants is zero (we know they can't both be) and we
9564 // have an icmp instruction with zero, and we have an 'and' with the
9565 // non-constant value, eliminate this whole mess. This corresponds to
9566 // cases like this: ((X & 27) ? 27 : 0)
9567 if (TrueValC->isZero() || FalseValC->isZero())
9568 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9569 cast<Constant>(IC->getOperand(1))->isNullValue())
9570 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9571 if (ICA->getOpcode() == Instruction::And &&
9572 isa<ConstantInt>(ICA->getOperand(1)) &&
9573 (ICA->getOperand(1) == TrueValC ||
9574 ICA->getOperand(1) == FalseValC) &&
9575 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9576 // Okay, now we know that everything is set up, we just don't
9577 // know whether we have a icmp_ne or icmp_eq and whether the
9578 // true or false val is the zero.
9579 bool ShouldNotVal = !TrueValC->isZero();
9580 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9581 Value *V = ICA;
9582 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009583 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009584 Instruction::Xor, V, ICA->getOperand(1)), SI);
9585 return ReplaceInstUsesWith(SI, V);
9586 }
9587 }
9588 }
9589
9590 // See if we are selecting two values based on a comparison of the two values.
9591 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9592 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9593 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009594 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9595 // This is not safe in general for floating point:
9596 // consider X== -0, Y== +0.
9597 // It becomes safe if either operand is a nonzero constant.
9598 ConstantFP *CFPt, *CFPf;
9599 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9600 !CFPt->getValueAPF().isZero()) ||
9601 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9602 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009603 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009604 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009605 // Transform (X != Y) ? X : Y -> X
9606 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9607 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009608 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009609
9610 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9611 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009612 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9613 // This is not safe in general for floating point:
9614 // consider X== -0, Y== +0.
9615 // It becomes safe if either operand is a nonzero constant.
9616 ConstantFP *CFPt, *CFPf;
9617 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9618 !CFPt->getValueAPF().isZero()) ||
9619 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9620 !CFPf->getValueAPF().isZero()))
9621 return ReplaceInstUsesWith(SI, FalseVal);
9622 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009623 // Transform (X != Y) ? Y : X -> Y
9624 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9625 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009626 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009627 }
Dan Gohman58c09632008-09-16 18:46:06 +00009628 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009629 }
9630
9631 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009632 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9633 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9634 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009635
9636 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9637 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9638 if (TI->hasOneUse() && FI->hasOneUse()) {
9639 Instruction *AddOp = 0, *SubOp = 0;
9640
9641 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9642 if (TI->getOpcode() == FI->getOpcode())
9643 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9644 return IV;
9645
9646 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9647 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009648 if ((TI->getOpcode() == Instruction::Sub &&
9649 FI->getOpcode() == Instruction::Add) ||
9650 (TI->getOpcode() == Instruction::FSub &&
9651 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009652 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009653 } else if ((FI->getOpcode() == Instruction::Sub &&
9654 TI->getOpcode() == Instruction::Add) ||
9655 (FI->getOpcode() == Instruction::FSub &&
9656 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009657 AddOp = TI; SubOp = FI;
9658 }
9659
9660 if (AddOp) {
9661 Value *OtherAddOp = 0;
9662 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9663 OtherAddOp = AddOp->getOperand(1);
9664 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9665 OtherAddOp = AddOp->getOperand(0);
9666 }
9667
9668 if (OtherAddOp) {
9669 // So at this point we know we have (Y -> OtherAddOp):
9670 // select C, (add X, Y), (sub X, Z)
9671 Value *NegVal; // Compute -Z
9672 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009673 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009674 } else {
9675 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009676 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009677 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009678 }
9679
9680 Value *NewTrueOp = OtherAddOp;
9681 Value *NewFalseOp = NegVal;
9682 if (AddOp != TI)
9683 std::swap(NewTrueOp, NewFalseOp);
9684 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009685 SelectInst::Create(CondVal, NewTrueOp,
9686 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009687
9688 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009689 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009690 }
9691 }
9692 }
9693
9694 // See if we can fold the select into one of our operands.
9695 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009696 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9697 if (FoldI)
9698 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009699 }
9700
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009701 // See if we can fold the select into a phi node if the condition is a select.
9702 if (isa<PHINode>(SI.getCondition()))
9703 // The true/false values have to be live in the PHI predecessor's blocks.
9704 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9705 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9706 if (Instruction *NV = FoldOpIntoPhi(SI))
9707 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00009708
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009709 if (BinaryOperator::isNot(CondVal)) {
9710 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9711 SI.setOperand(1, FalseVal);
9712 SI.setOperand(2, TrueVal);
9713 return &SI;
9714 }
9715
9716 return 0;
9717}
9718
Dan Gohman2d648bb2008-04-10 18:43:06 +00009719/// EnforceKnownAlignment - If the specified pointer points to an object that
9720/// we control, modify the object's alignment to PrefAlign. This isn't
9721/// often possible though. If alignment is important, a more reliable approach
9722/// is to simply align all global variables and allocation instructions to
9723/// their preferred alignment from the beginning.
9724///
9725static unsigned EnforceKnownAlignment(Value *V,
9726 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009727
Dan Gohman2d648bb2008-04-10 18:43:06 +00009728 User *U = dyn_cast<User>(V);
9729 if (!U) return Align;
9730
Dan Gohman9545fb02009-07-17 20:47:02 +00009731 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009732 default: break;
9733 case Instruction::BitCast:
9734 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9735 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009736 // If all indexes are zero, it is just the alignment of the base pointer.
9737 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009738 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009739 if (!isa<Constant>(*i) ||
9740 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009741 AllZeroOperands = false;
9742 break;
9743 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009744
9745 if (AllZeroOperands) {
9746 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009747 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009748 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009749 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009750 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009751 }
9752
9753 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9754 // If there is a large requested alignment and we can, bump up the alignment
9755 // of the global.
9756 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009757 if (GV->getAlignment() >= PrefAlign)
9758 Align = GV->getAlignment();
9759 else {
9760 GV->setAlignment(PrefAlign);
9761 Align = PrefAlign;
9762 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009763 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009764 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9765 // If there is a requested alignment and if this is an alloca, round up.
9766 if (AI->getAlignment() >= PrefAlign)
9767 Align = AI->getAlignment();
9768 else {
9769 AI->setAlignment(PrefAlign);
9770 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009771 }
9772 }
9773
9774 return Align;
9775}
9776
9777/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9778/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9779/// and it is more than the alignment of the ultimate object, see if we can
9780/// increase the alignment of the ultimate object, making this check succeed.
9781unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9782 unsigned PrefAlign) {
9783 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9784 sizeof(PrefAlign) * CHAR_BIT;
9785 APInt Mask = APInt::getAllOnesValue(BitWidth);
9786 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9787 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9788 unsigned TrailZ = KnownZero.countTrailingOnes();
9789 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9790
9791 if (PrefAlign > Align)
9792 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9793
9794 // We don't need to make any adjustment.
9795 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009796}
9797
Chris Lattner00ae5132008-01-13 23:50:23 +00009798Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009799 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009800 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009801 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009802 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009803
9804 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009805 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009806 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009807 return MI;
9808 }
9809
9810 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9811 // load/store.
9812 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9813 if (MemOpLength == 0) return 0;
9814
Chris Lattnerc669fb62008-01-14 00:28:35 +00009815 // Source and destination pointer types are always "i8*" for intrinsic. See
9816 // if the size is something we can handle with a single primitive load/store.
9817 // A single load+store correctly handles overlapping memory in the memmove
9818 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009819 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009820 if (Size == 0) return MI; // Delete this mem transfer.
9821
9822 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009823 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009824
Chris Lattnerc669fb62008-01-14 00:28:35 +00009825 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009826 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009827 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009828
9829 // Memcpy forces the use of i8* for the source and destination. That means
9830 // that if you're using memcpy to move one double around, you'll get a cast
9831 // from double* to i8*. We'd much rather use a double load+store rather than
9832 // an i64 load+store, here because this improves the odds that the source or
9833 // dest address will be promotable. See if we can find a better type than the
9834 // integer datatype.
9835 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9836 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009837 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009838 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9839 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009840 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009841 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9842 if (STy->getNumElements() == 1)
9843 SrcETy = STy->getElementType(0);
9844 else
9845 break;
9846 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9847 if (ATy->getNumElements() == 1)
9848 SrcETy = ATy->getElementType();
9849 else
9850 break;
9851 } else
9852 break;
9853 }
9854
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009855 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009856 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009857 }
9858 }
9859
9860
Chris Lattner00ae5132008-01-13 23:50:23 +00009861 // If the memcpy/memmove provides better alignment info than we can
9862 // infer, use it.
9863 SrcAlign = std::max(SrcAlign, CopyAlign);
9864 DstAlign = std::max(DstAlign, CopyAlign);
9865
Chris Lattner78628292009-08-30 19:47:22 +00009866 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9867 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009868 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9869 InsertNewInstBefore(L, *MI);
9870 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9871
9872 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009873 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009874 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009875}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009876
Chris Lattner5af8a912008-04-30 06:39:11 +00009877Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9878 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009879 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009880 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009881 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009882 return MI;
9883 }
9884
9885 // Extract the length and alignment and fill if they are constant.
9886 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9887 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009888 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009889 return 0;
9890 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009891 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009892
9893 // If the length is zero, this is a no-op
9894 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9895
9896 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9897 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009898 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009899
9900 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009901 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009902
9903 // Alignment 0 is identity for alignment 1 for memset, but not store.
9904 if (Alignment == 0) Alignment = 1;
9905
9906 // Extract the fill value and store.
9907 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009908 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009909 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009910
9911 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009912 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009913 return MI;
9914 }
9915
9916 return 0;
9917}
9918
9919
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009920/// visitCallInst - CallInst simplification. This mostly only handles folding
9921/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9922/// the heavy lifting.
9923///
9924Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00009925 if (isFreeCall(&CI))
9926 return visitFree(CI);
9927
Chris Lattneraa295aa2009-05-13 17:39:14 +00009928 // If the caller function is nounwind, mark the call as nounwind, even if the
9929 // callee isn't.
9930 if (CI.getParent()->getParent()->doesNotThrow() &&
9931 !CI.doesNotThrow()) {
9932 CI.setDoesNotThrow();
9933 return &CI;
9934 }
9935
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009936 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9937 if (!II) return visitCallSite(&CI);
9938
9939 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9940 // visitCallSite.
9941 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9942 bool Changed = false;
9943
9944 // memmove/cpy/set of zero bytes is a noop.
9945 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9946 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9947
9948 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9949 if (CI->getZExtValue() == 1) {
9950 // Replace the instruction with just byte operations. We would
9951 // transform other cases to loads/stores, but we don't know if
9952 // alignment is sufficient.
9953 }
9954 }
9955
9956 // If we have a memmove and the source operation is a constant global,
9957 // then the source and dest pointers can't alias, so we can change this
9958 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009959 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009960 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9961 if (GVSrc->isConstant()) {
9962 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009963 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9964 const Type *Tys[1];
9965 Tys[0] = CI.getOperand(3)->getType();
9966 CI.setOperand(0,
9967 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009968 Changed = true;
9969 }
Eli Friedman626e32a2009-12-17 21:07:31 +00009970 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009971
Eli Friedman626e32a2009-12-17 21:07:31 +00009972 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +00009973 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +00009974 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +00009975 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009976 }
9977
9978 // If we can determine a pointer alignment that is bigger than currently
9979 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009980 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009981 if (Instruction *I = SimplifyMemTransfer(MI))
9982 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009983 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9984 if (Instruction *I = SimplifyMemSet(MSI))
9985 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009986 }
9987
9988 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009989 }
9990
9991 switch (II->getIntrinsicID()) {
9992 default: break;
9993 case Intrinsic::bswap:
9994 // bswap(bswap(x)) -> x
9995 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9996 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9997 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9998 break;
Chris Lattner0b452262009-11-26 21:42:47 +00009999 case Intrinsic::uadd_with_overflow: {
10000 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10001 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10002 uint32_t BitWidth = IT->getBitWidth();
10003 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +000010004 APInt LHSKnownZero(BitWidth, 0);
10005 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010006 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10007 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10008 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10009
10010 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +000010011 APInt RHSKnownZero(BitWidth, 0);
10012 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010013 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10014 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10015 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10016 if (LHSKnownNegative && RHSKnownNegative) {
10017 // The sign bit is set in both cases: this MUST overflow.
10018 // Create a simple add instruction, and insert it into the struct.
10019 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10020 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010021 Constant *V[] = {
10022 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10023 };
Chris Lattner0b452262009-11-26 21:42:47 +000010024 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10025 return InsertValueInst::Create(Struct, Add, 0);
10026 }
10027
10028 if (LHSKnownPositive && RHSKnownPositive) {
10029 // The sign bit is clear in both cases: this CANNOT overflow.
10030 // Create a simple add instruction, and insert it into the struct.
10031 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10032 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010033 Constant *V[] = {
10034 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10035 };
Chris Lattner0b452262009-11-26 21:42:47 +000010036 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10037 return InsertValueInst::Create(Struct, Add, 0);
10038 }
10039 }
10040 }
10041 // FALL THROUGH uadd into sadd
10042 case Intrinsic::sadd_with_overflow:
10043 // Canonicalize constants into the RHS.
10044 if (isa<Constant>(II->getOperand(1)) &&
10045 !isa<Constant>(II->getOperand(2))) {
10046 Value *LHS = II->getOperand(1);
10047 II->setOperand(1, II->getOperand(2));
10048 II->setOperand(2, LHS);
10049 return II;
10050 }
10051
10052 // X + undef -> undef
10053 if (isa<UndefValue>(II->getOperand(2)))
10054 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10055
10056 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10057 // X + 0 -> {X, false}
10058 if (RHS->isZero()) {
10059 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010060 UndefValue::get(II->getOperand(0)->getType()),
10061 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010062 };
10063 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10064 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10065 }
10066 }
10067 break;
10068 case Intrinsic::usub_with_overflow:
10069 case Intrinsic::ssub_with_overflow:
10070 // undef - X -> undef
10071 // X - undef -> undef
10072 if (isa<UndefValue>(II->getOperand(1)) ||
10073 isa<UndefValue>(II->getOperand(2)))
10074 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10075
10076 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10077 // X - 0 -> {X, false}
10078 if (RHS->isZero()) {
10079 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010080 UndefValue::get(II->getOperand(1)->getType()),
10081 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010082 };
10083 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10084 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10085 }
10086 }
10087 break;
10088 case Intrinsic::umul_with_overflow:
10089 case Intrinsic::smul_with_overflow:
10090 // Canonicalize constants into the RHS.
10091 if (isa<Constant>(II->getOperand(1)) &&
10092 !isa<Constant>(II->getOperand(2))) {
10093 Value *LHS = II->getOperand(1);
10094 II->setOperand(1, II->getOperand(2));
10095 II->setOperand(2, LHS);
10096 return II;
10097 }
10098
10099 // X * undef -> undef
10100 if (isa<UndefValue>(II->getOperand(2)))
10101 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10102
10103 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10104 // X*0 -> {0, false}
10105 if (RHSI->isZero())
10106 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10107
10108 // X * 1 -> {X, false}
10109 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010110 Constant *V[] = {
10111 UndefValue::get(II->getOperand(1)->getType()),
10112 ConstantInt::getFalse(*Context)
10113 };
Chris Lattner0b452262009-11-26 21:42:47 +000010114 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010115 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010116 }
10117 }
10118 break;
Chris Lattner989ba312008-06-18 04:33:20 +000010119 case Intrinsic::ppc_altivec_lvx:
10120 case Intrinsic::ppc_altivec_lvxl:
10121 case Intrinsic::x86_sse_loadu_ps:
10122 case Intrinsic::x86_sse2_loadu_pd:
10123 case Intrinsic::x86_sse2_loadu_dq:
10124 // Turn PPC lvx -> load if the pointer is known aligned.
10125 // Turn X86 loadups -> load if the pointer is known aligned.
10126 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +000010127 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10128 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +000010129 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010130 }
Chris Lattner989ba312008-06-18 04:33:20 +000010131 break;
10132 case Intrinsic::ppc_altivec_stvx:
10133 case Intrinsic::ppc_altivec_stvxl:
10134 // Turn stvx -> store if the pointer is known aligned.
10135 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10136 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010137 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010138 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010139 return new StoreInst(II->getOperand(1), Ptr);
10140 }
10141 break;
10142 case Intrinsic::x86_sse_storeu_ps:
10143 case Intrinsic::x86_sse2_storeu_pd:
10144 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +000010145 // Turn X86 storeu -> store if the pointer is known aligned.
10146 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10147 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010148 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010149 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010150 return new StoreInst(II->getOperand(2), Ptr);
10151 }
10152 break;
10153
10154 case Intrinsic::x86_sse_cvttss2si: {
10155 // These intrinsics only demands the 0th element of its input vector. If
10156 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +000010157 unsigned VWidth =
10158 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10159 APInt DemandedElts(VWidth, 1);
10160 APInt UndefElts(VWidth, 0);
10161 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +000010162 UndefElts)) {
10163 II->setOperand(1, V);
10164 return II;
10165 }
10166 break;
10167 }
10168
10169 case Intrinsic::ppc_altivec_vperm:
10170 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10171 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10172 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010173
Chris Lattner989ba312008-06-18 04:33:20 +000010174 // Check that all of the elements are integer constants or undefs.
10175 bool AllEltsOk = true;
10176 for (unsigned i = 0; i != 16; ++i) {
10177 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10178 !isa<UndefValue>(Mask->getOperand(i))) {
10179 AllEltsOk = false;
10180 break;
10181 }
10182 }
10183
10184 if (AllEltsOk) {
10185 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +000010186 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10187 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +000010188 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010189
Chris Lattner989ba312008-06-18 04:33:20 +000010190 // Only extract each element once.
10191 Value *ExtractedElts[32];
10192 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10193
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010194 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +000010195 if (isa<UndefValue>(Mask->getOperand(i)))
10196 continue;
10197 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10198 Idx &= 31; // Match the hardware behavior.
10199
10200 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010201 ExtractedElts[Idx] =
10202 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10203 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10204 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010205 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010206
Chris Lattner989ba312008-06-18 04:33:20 +000010207 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +000010208 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10209 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10210 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010211 }
Chris Lattner989ba312008-06-18 04:33:20 +000010212 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010213 }
Chris Lattner989ba312008-06-18 04:33:20 +000010214 }
10215 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010216
Chris Lattner989ba312008-06-18 04:33:20 +000010217 case Intrinsic::stackrestore: {
10218 // If the save is right next to the restore, remove the restore. This can
10219 // happen when variable allocas are DCE'd.
10220 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10221 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10222 BasicBlock::iterator BI = SS;
10223 if (&*++BI == II)
10224 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010225 }
Chris Lattner989ba312008-06-18 04:33:20 +000010226 }
10227
10228 // Scan down this block to see if there is another stack restore in the
10229 // same block without an intervening call/alloca.
10230 BasicBlock::iterator BI = II;
10231 TerminatorInst *TI = II->getParent()->getTerminator();
10232 bool CannotRemove = false;
10233 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000010234 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +000010235 CannotRemove = true;
10236 break;
10237 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010238 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10239 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10240 // If there is a stackrestore below this one, remove this one.
10241 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10242 return EraseInstFromFunction(CI);
10243 // Otherwise, ignore the intrinsic.
10244 } else {
10245 // If we found a non-intrinsic call, we can't remove the stack
10246 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010247 CannotRemove = true;
10248 break;
10249 }
Chris Lattner989ba312008-06-18 04:33:20 +000010250 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010251 }
Chris Lattner989ba312008-06-18 04:33:20 +000010252
10253 // If the stack restore is in a return/unwind block and if there are no
10254 // allocas or calls between the restore and the return, nuke the restore.
10255 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10256 return EraseInstFromFunction(CI);
10257 break;
10258 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010259 }
10260
10261 return visitCallSite(II);
10262}
10263
10264// InvokeInst simplification
10265//
10266Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10267 return visitCallSite(&II);
10268}
10269
Dale Johannesen96021832008-04-25 21:16:07 +000010270/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10271/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010272static bool isSafeToEliminateVarargsCast(const CallSite CS,
10273 const CastInst * const CI,
10274 const TargetData * const TD,
10275 const int ix) {
10276 if (!CI->isLosslessCast())
10277 return false;
10278
10279 // The size of ByVal arguments is derived from the type, so we
10280 // can't change to a type with a different size. If the size were
10281 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010282 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010283 return true;
10284
10285 const Type* SrcTy =
10286 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10287 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10288 if (!SrcTy->isSized() || !DstTy->isSized())
10289 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010290 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010291 return false;
10292 return true;
10293}
10294
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010295// visitCallSite - Improvements for call and invoke instructions.
10296//
10297Instruction *InstCombiner::visitCallSite(CallSite CS) {
10298 bool Changed = false;
10299
10300 // If the callee is a constexpr cast of a function, attempt to move the cast
10301 // to the arguments of the call/invoke.
10302 if (transformConstExprCastCall(CS)) return 0;
10303
10304 Value *Callee = CS.getCalledValue();
10305
10306 if (Function *CalleeF = dyn_cast<Function>(Callee))
10307 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10308 Instruction *OldCall = CS.getInstruction();
10309 // If the call and callee calling conventions don't match, this call must
10310 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010311 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010312 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010313 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010314 // If OldCall dues not return void then replaceAllUsesWith undef.
10315 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010316 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010317 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010318 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10319 return EraseInstFromFunction(*OldCall);
10320 return 0;
10321 }
10322
10323 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10324 // This instruction is not reachable, just remove it. We insert a store to
10325 // undef so that we know that this code is not reachable, despite the fact
10326 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010327 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010328 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010329 CS.getInstruction());
10330
Devang Patele3829c82009-10-13 22:56:32 +000010331 // If CS dues not return void then replaceAllUsesWith undef.
10332 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010333 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010334 CS.getInstruction()->
10335 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010336
10337 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10338 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010339 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010340 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010341 }
10342 return EraseInstFromFunction(*CS.getInstruction());
10343 }
10344
Duncan Sands74833f22007-09-17 10:26:40 +000010345 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10346 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10347 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10348 return transformCallThroughTrampoline(CS);
10349
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010350 const PointerType *PTy = cast<PointerType>(Callee->getType());
10351 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10352 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010353 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010354 // See if we can optimize any arguments passed through the varargs area of
10355 // the call.
10356 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010357 E = CS.arg_end(); I != E; ++I, ++ix) {
10358 CastInst *CI = dyn_cast<CastInst>(*I);
10359 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10360 *I = CI->getOperand(0);
10361 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010362 }
Dale Johannesen35615462008-04-23 18:34:37 +000010363 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010364 }
10365
Duncan Sands2937e352007-12-19 21:13:37 +000010366 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010367 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010368 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010369 Changed = true;
10370 }
10371
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010372 return Changed ? CS.getInstruction() : 0;
10373}
10374
10375// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10376// attempt to move the cast to the arguments of the call/invoke.
10377//
10378bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10379 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10380 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10381 if (CE->getOpcode() != Instruction::BitCast ||
10382 !isa<Function>(CE->getOperand(0)))
10383 return false;
10384 Function *Callee = cast<Function>(CE->getOperand(0));
10385 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010386 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010387
10388 // Okay, this is a cast from a function to a different type. Unless doing so
10389 // would cause a type conversion of one of our arguments, change this call to
10390 // be a direct call with arguments casted to the appropriate types.
10391 //
10392 const FunctionType *FT = Callee->getFunctionType();
10393 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010394 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010395
Duncan Sands7901ce12008-06-01 07:38:42 +000010396 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010397 return false; // TODO: Handle multiple return values.
10398
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010399 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010400 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010401 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010402 // Conversion is ok if changing from one pointer type to another or from
10403 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010404 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010405 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010406 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010407 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010408 return false; // Cannot transform this return value.
10409
Duncan Sands5c489582008-01-06 10:12:28 +000010410 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010411 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010412 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010413 return false; // Cannot transform this return value.
10414
Chris Lattner1c8733e2008-03-12 17:45:29 +000010415 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010416 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010417 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010418 return false; // Attribute not compatible with transformed value.
10419 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010420
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010421 // If the callsite is an invoke instruction, and the return value is used by
10422 // a PHI node in a successor, we cannot change the return type of the call
10423 // because there is no place to put the cast instruction (without breaking
10424 // the critical edge). Bail out in this case.
10425 if (!Caller->use_empty())
10426 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10427 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10428 UI != E; ++UI)
10429 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10430 if (PN->getParent() == II->getNormalDest() ||
10431 PN->getParent() == II->getUnwindDest())
10432 return false;
10433 }
10434
10435 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10436 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10437
10438 CallSite::arg_iterator AI = CS.arg_begin();
10439 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10440 const Type *ParamTy = FT->getParamType(i);
10441 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010442
10443 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010444 return false; // Cannot transform this parameter value.
10445
Devang Patelf2a4a922008-09-26 22:53:05 +000010446 if (CallerPAL.getParamAttributes(i + 1)
10447 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010448 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010449
Duncan Sands7901ce12008-06-01 07:38:42 +000010450 // Converting from one pointer type to another or between a pointer and an
10451 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010452 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010453 (TD && ((isa<PointerType>(ParamTy) ||
10454 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10455 (isa<PointerType>(ActTy) ||
10456 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010457 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010458 }
10459
10460 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10461 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010462 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010463
Chris Lattner1c8733e2008-03-12 17:45:29 +000010464 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10465 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010466 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010467 // won't be dropping them. Check that these extra arguments have attributes
10468 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010469 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10470 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010471 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010472 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010473 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010474 return false;
10475 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010476
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010477 // Okay, we decided that this is a safe thing to do: go ahead and start
10478 // inserting cast instructions as necessary...
10479 std::vector<Value*> Args;
10480 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010481 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010482 attrVec.reserve(NumCommonArgs);
10483
10484 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010485 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010486
10487 // If the return value is not being used, the type may not be compatible
10488 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010489 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010490
10491 // Add the new return attributes.
10492 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010493 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010494
10495 AI = CS.arg_begin();
10496 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10497 const Type *ParamTy = FT->getParamType(i);
10498 if ((*AI)->getType() == ParamTy) {
10499 Args.push_back(*AI);
10500 } else {
10501 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10502 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010503 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010504 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010505
10506 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010507 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010508 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010509 }
10510
10511 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010512 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010513 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010514 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010515
Chris Lattnerad7516a2009-08-30 18:50:58 +000010516 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010517 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010518 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010519 errs() << "WARNING: While resolving call to function '"
10520 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010521 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010522 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010523 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10524 const Type *PTy = getPromotedType((*AI)->getType());
10525 if (PTy != (*AI)->getType()) {
10526 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010527 Instruction::CastOps opcode =
10528 CastInst::getCastOpcode(*AI, false, PTy, false);
10529 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010530 } else {
10531 Args.push_back(*AI);
10532 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010533
Duncan Sands4ced1f82008-01-13 08:02:44 +000010534 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010535 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010536 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010537 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010538 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010539 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010540
Devang Patelf2a4a922008-09-26 22:53:05 +000010541 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10542 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10543
Devang Patele9d08b82009-10-14 17:29:00 +000010544 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010545 Caller->setName(""); // Void type should not have a name.
10546
Eric Christopher3e7381f2009-07-25 02:45:27 +000010547 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10548 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010549
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010550 Instruction *NC;
10551 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010552 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010553 Args.begin(), Args.end(),
10554 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010555 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010556 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010557 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010558 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10559 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010560 CallInst *CI = cast<CallInst>(Caller);
10561 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010562 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010563 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010564 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010565 }
10566
10567 // Insert a cast of the return type as necessary.
10568 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010569 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010570 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010571 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010572 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010573 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010574
10575 // If this is an invoke instruction, we should insert it after the first
10576 // non-phi, instruction in the normal successor block.
10577 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010578 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010579 InsertNewInstBefore(NC, *I);
10580 } else {
10581 // Otherwise, it's a call, just insert cast right after the call instr
10582 InsertNewInstBefore(NC, *Caller);
10583 }
Chris Lattner4796b622009-08-30 06:22:51 +000010584 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010585 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010586 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010587 }
10588 }
10589
Devang Pateledad36f2009-10-13 21:41:20 +000010590
Chris Lattner26b7f942009-08-31 05:17:58 +000010591 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010592 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010593
10594 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010595 return true;
10596}
10597
Duncan Sands74833f22007-09-17 10:26:40 +000010598// transformCallThroughTrampoline - Turn a call to a function created by the
10599// init_trampoline intrinsic into a direct call to the underlying function.
10600//
10601Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10602 Value *Callee = CS.getCalledValue();
10603 const PointerType *PTy = cast<PointerType>(Callee->getType());
10604 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010605 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010606
10607 // If the call already has the 'nest' attribute somewhere then give up -
10608 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010609 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010610 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010611
10612 IntrinsicInst *Tramp =
10613 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10614
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010615 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010616 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10617 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10618
Devang Pateld222f862008-09-25 21:00:45 +000010619 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010620 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010621 unsigned NestIdx = 1;
10622 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010623 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010624
10625 // Look for a parameter marked with the 'nest' attribute.
10626 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10627 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010628 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010629 // Record the parameter type and any other attributes.
10630 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010631 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010632 break;
10633 }
10634
10635 if (NestTy) {
10636 Instruction *Caller = CS.getInstruction();
10637 std::vector<Value*> NewArgs;
10638 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10639
Devang Pateld222f862008-09-25 21:00:45 +000010640 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010641 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010642
Duncan Sands74833f22007-09-17 10:26:40 +000010643 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010644 // mean appending it. Likewise for attributes.
10645
Devang Patelf2a4a922008-09-26 22:53:05 +000010646 // Add any result attributes.
10647 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010648 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010649
Duncan Sands74833f22007-09-17 10:26:40 +000010650 {
10651 unsigned Idx = 1;
10652 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10653 do {
10654 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010655 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010656 Value *NestVal = Tramp->getOperand(3);
10657 if (NestVal->getType() != NestTy)
10658 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10659 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010660 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010661 }
10662
10663 if (I == E)
10664 break;
10665
Duncan Sands48b81112008-01-14 19:52:09 +000010666 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010667 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010668 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010669 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010670 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010671
10672 ++Idx, ++I;
10673 } while (1);
10674 }
10675
Devang Patelf2a4a922008-09-26 22:53:05 +000010676 // Add any function attributes.
10677 if (Attributes Attr = Attrs.getFnAttributes())
10678 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10679
Duncan Sands74833f22007-09-17 10:26:40 +000010680 // The trampoline may have been bitcast to a bogus type (FTy).
10681 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010682 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010683
Duncan Sands74833f22007-09-17 10:26:40 +000010684 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010685 NewTypes.reserve(FTy->getNumParams()+1);
10686
Duncan Sands74833f22007-09-17 10:26:40 +000010687 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010688 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010689 {
10690 unsigned Idx = 1;
10691 FunctionType::param_iterator I = FTy->param_begin(),
10692 E = FTy->param_end();
10693
10694 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010695 if (Idx == NestIdx)
10696 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010697 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010698
10699 if (I == E)
10700 break;
10701
Duncan Sands48b81112008-01-14 19:52:09 +000010702 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010703 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010704
10705 ++Idx, ++I;
10706 } while (1);
10707 }
10708
10709 // Replace the trampoline call with a direct call. Let the generic
10710 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010711 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010712 FTy->isVarArg());
10713 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010714 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010715 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010716 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010717 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10718 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010719
10720 Instruction *NewCaller;
10721 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010722 NewCaller = InvokeInst::Create(NewCallee,
10723 II->getNormalDest(), II->getUnwindDest(),
10724 NewArgs.begin(), NewArgs.end(),
10725 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010726 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010727 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010728 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010729 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10730 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010731 if (cast<CallInst>(Caller)->isTailCall())
10732 cast<CallInst>(NewCaller)->setTailCall();
10733 cast<CallInst>(NewCaller)->
10734 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010735 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010736 }
Devang Patele9d08b82009-10-14 17:29:00 +000010737 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010738 Caller->replaceAllUsesWith(NewCaller);
10739 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010740 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010741 return 0;
10742 }
10743 }
10744
10745 // Replace the trampoline call with a direct call. Since there is no 'nest'
10746 // parameter, there is no need to adjust the argument list. Let the generic
10747 // code sort out any function type mismatches.
10748 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010749 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010750 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010751 CS.setCalledFunction(NewCallee);
10752 return CS.getInstruction();
10753}
10754
Dan Gohman09cf2b62009-09-16 16:50:24 +000010755/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10756/// 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 +000010757/// and a single binop.
10758Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10759 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010760 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010761 unsigned Opc = FirstInst->getOpcode();
10762 Value *LHSVal = FirstInst->getOperand(0);
10763 Value *RHSVal = FirstInst->getOperand(1);
10764
10765 const Type *LHSType = LHSVal->getType();
10766 const Type *RHSType = RHSVal->getType();
10767
Dan Gohman09cf2b62009-09-16 16:50:24 +000010768 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010769 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010770 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10771 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10772 // Verify type of the LHS matches so we don't fold cmp's of different
10773 // types or GEP's with different index types.
10774 I->getOperand(0)->getType() != LHSType ||
10775 I->getOperand(1)->getType() != RHSType)
10776 return 0;
10777
10778 // If they are CmpInst instructions, check their predicates
10779 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10780 if (cast<CmpInst>(I)->getPredicate() !=
10781 cast<CmpInst>(FirstInst)->getPredicate())
10782 return 0;
10783
10784 // Keep track of which operand needs a phi node.
10785 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10786 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10787 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010788
10789 // If both LHS and RHS would need a PHI, don't do this transformation,
10790 // because it would increase the number of PHIs entering the block,
10791 // which leads to higher register pressure. This is especially
10792 // bad when the PHIs are in the header of a loop.
10793 if (!LHSVal && !RHSVal)
10794 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010795
Chris Lattner30078012008-12-01 03:42:51 +000010796 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010797
10798 Value *InLHS = FirstInst->getOperand(0);
10799 Value *InRHS = FirstInst->getOperand(1);
10800 PHINode *NewLHS = 0, *NewRHS = 0;
10801 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010802 NewLHS = PHINode::Create(LHSType,
10803 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010804 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10805 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10806 InsertNewInstBefore(NewLHS, PN);
10807 LHSVal = NewLHS;
10808 }
10809
10810 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010811 NewRHS = PHINode::Create(RHSType,
10812 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010813 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10814 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10815 InsertNewInstBefore(NewRHS, PN);
10816 RHSVal = NewRHS;
10817 }
10818
10819 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010820 if (NewLHS || NewRHS) {
10821 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10822 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10823 if (NewLHS) {
10824 Value *NewInLHS = InInst->getOperand(0);
10825 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10826 }
10827 if (NewRHS) {
10828 Value *NewInRHS = InInst->getOperand(1);
10829 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10830 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010831 }
10832 }
10833
10834 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010835 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010836 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010837 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010838 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010839}
10840
Chris Lattner9e1916e2008-12-01 02:34:36 +000010841Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10842 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10843
10844 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10845 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010846 // This is true if all GEP bases are allocas and if all indices into them are
10847 // constants.
10848 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010849
10850 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010851 // more than one phi, which leads to higher register pressure. This is
10852 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010853 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010854
Dan Gohman09cf2b62009-09-16 16:50:24 +000010855 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010856 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10857 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10858 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10859 GEP->getNumOperands() != FirstInst->getNumOperands())
10860 return 0;
10861
Chris Lattneradf354b2009-02-21 00:46:50 +000010862 // Keep track of whether or not all GEPs are of alloca pointers.
10863 if (AllBasePointersAreAllocas &&
10864 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10865 !GEP->hasAllConstantIndices()))
10866 AllBasePointersAreAllocas = false;
10867
Chris Lattner9e1916e2008-12-01 02:34:36 +000010868 // Compare the operand lists.
10869 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10870 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10871 continue;
10872
10873 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10874 // if one of the PHIs has a constant for the index. The index may be
10875 // substantially cheaper to compute for the constants, so making it a
10876 // variable index could pessimize the path. This also handles the case
10877 // for struct indices, which must always be constant.
10878 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10879 isa<ConstantInt>(GEP->getOperand(op)))
10880 return 0;
10881
10882 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10883 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010884
10885 // If we already needed a PHI for an earlier operand, and another operand
10886 // also requires a PHI, we'd be introducing more PHIs than we're
10887 // eliminating, which increases register pressure on entry to the PHI's
10888 // block.
10889 if (NeededPhi)
10890 return 0;
10891
Chris Lattner9e1916e2008-12-01 02:34:36 +000010892 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010893 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010894 }
10895 }
10896
Chris Lattneradf354b2009-02-21 00:46:50 +000010897 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010898 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010899 // offset calculation, but all the predecessors will have to materialize the
10900 // stack address into a register anyway. We'd actually rather *clone* the
10901 // load up into the predecessors so that we have a load of a gep of an alloca,
10902 // which can usually all be folded into the load.
10903 if (AllBasePointersAreAllocas)
10904 return 0;
10905
Chris Lattner9e1916e2008-12-01 02:34:36 +000010906 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10907 // that is variable.
10908 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10909
10910 bool HasAnyPHIs = false;
10911 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10912 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10913 Value *FirstOp = FirstInst->getOperand(i);
10914 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10915 FirstOp->getName()+".pn");
10916 InsertNewInstBefore(NewPN, PN);
10917
10918 NewPN->reserveOperandSpace(e);
10919 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10920 OperandPhis[i] = NewPN;
10921 FixedOperands[i] = NewPN;
10922 HasAnyPHIs = true;
10923 }
10924
10925
10926 // Add all operands to the new PHIs.
10927 if (HasAnyPHIs) {
10928 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10929 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10930 BasicBlock *InBB = PN.getIncomingBlock(i);
10931
10932 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10933 if (PHINode *OpPhi = OperandPhis[op])
10934 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10935 }
10936 }
10937
10938 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010939 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10940 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10941 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010942 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10943 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010944}
10945
10946
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010947/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10948/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010949/// obvious the value of the load is not changed from the point of the load to
10950/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010951///
10952/// Finally, it is safe, but not profitable, to sink a load targetting a
10953/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10954/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010955static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010956 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10957
10958 for (++BBI; BBI != E; ++BBI)
10959 if (BBI->mayWriteToMemory())
10960 return false;
10961
10962 // Check for non-address taken alloca. If not address-taken already, it isn't
10963 // profitable to do this xform.
10964 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10965 bool isAddressTaken = false;
10966 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10967 UI != E; ++UI) {
10968 if (isa<LoadInst>(UI)) continue;
10969 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10970 // If storing TO the alloca, then the address isn't taken.
10971 if (SI->getOperand(1) == AI) continue;
10972 }
10973 isAddressTaken = true;
10974 break;
10975 }
10976
Chris Lattneradf354b2009-02-21 00:46:50 +000010977 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010978 return false;
10979 }
10980
Chris Lattneradf354b2009-02-21 00:46:50 +000010981 // If this load is a load from a GEP with a constant offset from an alloca,
10982 // then we don't want to sink it. In its present form, it will be
10983 // load [constant stack offset]. Sinking it will cause us to have to
10984 // materialize the stack addresses in each predecessor in a register only to
10985 // do a shared load from register in the successor.
10986 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10987 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10988 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10989 return false;
10990
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010991 return true;
10992}
10993
Chris Lattner38751f82009-11-01 20:04:24 +000010994Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10995 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10996
10997 // When processing loads, we need to propagate two bits of information to the
10998 // sunk load: whether it is volatile, and what its alignment is. We currently
10999 // don't sink loads when some have their alignment specified and some don't.
11000 // visitLoadInst will propagate an alignment onto the load when TD is around,
11001 // and if TD isn't around, we can't handle the mixed case.
11002 bool isVolatile = FirstLI->isVolatile();
11003 unsigned LoadAlignment = FirstLI->getAlignment();
11004
11005 // We can't sink the load if the loaded value could be modified between the
11006 // load and the PHI.
11007 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11008 !isSafeAndProfitableToSinkLoad(FirstLI))
11009 return 0;
11010
11011 // If the PHI is of volatile loads and the load block has multiple
11012 // successors, sinking it would remove a load of the volatile value from
11013 // the path through the other successor.
11014 if (isVolatile &&
11015 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11016 return 0;
11017
11018 // Check to see if all arguments are the same operation.
11019 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11020 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11021 if (!LI || !LI->hasOneUse())
11022 return 0;
11023
11024 // We can't sink the load if the loaded value could be modified between
11025 // the load and the PHI.
11026 if (LI->isVolatile() != isVolatile ||
11027 LI->getParent() != PN.getIncomingBlock(i) ||
11028 !isSafeAndProfitableToSinkLoad(LI))
11029 return 0;
11030
11031 // If some of the loads have an alignment specified but not all of them,
11032 // we can't do the transformation.
11033 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11034 return 0;
11035
Chris Lattner52fe1bc2009-11-01 20:07:07 +000011036 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +000011037
11038 // If the PHI is of volatile loads and the load block has multiple
11039 // successors, sinking it would remove a load of the volatile value from
11040 // the path through the other successor.
11041 if (isVolatile &&
11042 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11043 return 0;
11044 }
11045
11046 // Okay, they are all the same operation. Create a new PHI node of the
11047 // correct type, and PHI together all of the LHS's of the instructions.
11048 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11049 PN.getName()+".in");
11050 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11051
11052 Value *InVal = FirstLI->getOperand(0);
11053 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11054
11055 // Add all operands to the new PHI.
11056 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11057 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11058 if (NewInVal != InVal)
11059 InVal = 0;
11060 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11061 }
11062
11063 Value *PhiVal;
11064 if (InVal) {
11065 // The new PHI unions all of the same values together. This is really
11066 // common, so we handle it intelligently here for compile-time speed.
11067 PhiVal = InVal;
11068 delete NewPN;
11069 } else {
11070 InsertNewInstBefore(NewPN, PN);
11071 PhiVal = NewPN;
11072 }
11073
11074 // If this was a volatile load that we are merging, make sure to loop through
11075 // and mark all the input loads as non-volatile. If we don't do this, we will
11076 // insert a new volatile load and the old ones will not be deletable.
11077 if (isVolatile)
11078 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11079 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11080
11081 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11082}
11083
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011084
Chris Lattnerd0011092009-11-10 07:23:37 +000011085
11086/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11087/// operator and they all are only used by the PHI, PHI together their
11088/// inputs, and do the operation once, to the result of the PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011089Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11090 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11091
Chris Lattner38751f82009-11-01 20:04:24 +000011092 if (isa<GetElementPtrInst>(FirstInst))
11093 return FoldPHIArgGEPIntoPHI(PN);
11094 if (isa<LoadInst>(FirstInst))
11095 return FoldPHIArgLoadIntoPHI(PN);
11096
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011097 // Scan the instruction, looking for input operations that can be folded away.
11098 // If all input operands to the phi are the same instruction (e.g. a cast from
11099 // the same type or "+42") we can pull the operation through the PHI, reducing
11100 // code size and simplifying code.
11101 Constant *ConstantOp = 0;
11102 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +000011103
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011104 if (isa<CastInst>(FirstInst)) {
11105 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +000011106
11107 // Be careful about transforming integer PHIs. We don't want to pessimize
11108 // the code by turning an i32 into an i1293.
11109 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerd0011092009-11-10 07:23:37 +000011110 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattner4ca73902009-11-08 21:20:06 +000011111 return 0;
11112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011113 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11114 // Can fold binop, compare or shift here if the RHS is a constant,
11115 // otherwise call FoldPHIArgBinOpIntoPHI.
11116 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11117 if (ConstantOp == 0)
11118 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011119 } else {
11120 return 0; // Cannot fold this operation.
11121 }
11122
11123 // Check to see if all arguments are the same operation.
11124 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +000011125 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11126 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011127 return 0;
11128 if (CastSrcTy) {
11129 if (I->getOperand(0)->getType() != CastSrcTy)
11130 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011131 } else if (I->getOperand(1) != ConstantOp) {
11132 return 0;
11133 }
11134 }
11135
11136 // Okay, they are all the same operation. Create a new PHI node of the
11137 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000011138 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11139 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011140 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11141
11142 Value *InVal = FirstInst->getOperand(0);
11143 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11144
11145 // Add all operands to the new PHI.
11146 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11147 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11148 if (NewInVal != InVal)
11149 InVal = 0;
11150 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11151 }
11152
11153 Value *PhiVal;
11154 if (InVal) {
11155 // The new PHI unions all of the same values together. This is really
11156 // common, so we handle it intelligently here for compile-time speed.
11157 PhiVal = InVal;
11158 delete NewPN;
11159 } else {
11160 InsertNewInstBefore(NewPN, PN);
11161 PhiVal = NewPN;
11162 }
11163
11164 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +000011165 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011166 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +000011167
Chris Lattnerfc984e92008-04-29 17:13:43 +000011168 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011169 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +000011170
Chris Lattner38751f82009-11-01 20:04:24 +000011171 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11172 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11173 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011174}
11175
11176/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11177/// that is dead.
11178static bool DeadPHICycle(PHINode *PN,
11179 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11180 if (PN->use_empty()) return true;
11181 if (!PN->hasOneUse()) return false;
11182
11183 // Remember this node, and if we find the cycle, return.
11184 if (!PotentiallyDeadPHIs.insert(PN))
11185 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000011186
11187 // Don't scan crazily complex things.
11188 if (PotentiallyDeadPHIs.size() == 16)
11189 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011190
11191 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11192 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11193
11194 return false;
11195}
11196
Chris Lattner27b695d2007-11-06 21:52:06 +000011197/// PHIsEqualValue - Return true if this phi node is always equal to
11198/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11199/// z = some value; x = phi (y, z); y = phi (x, z)
11200static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11201 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11202 // See if we already saw this PHI node.
11203 if (!ValueEqualPHIs.insert(PN))
11204 return true;
11205
11206 // Don't scan crazily complex things.
11207 if (ValueEqualPHIs.size() == 16)
11208 return false;
11209
11210 // Scan the operands to see if they are either phi nodes or are equal to
11211 // the value.
11212 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11213 Value *Op = PN->getIncomingValue(i);
11214 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11215 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11216 return false;
11217 } else if (Op != NonPhiInVal)
11218 return false;
11219 }
11220
11221 return true;
11222}
11223
11224
Chris Lattner1cd526b2009-11-08 19:23:30 +000011225namespace {
11226struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +000011227 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +000011228 unsigned Shift; // The amount shifted.
11229 Instruction *Inst; // The trunc instruction.
11230
Chris Lattner073c12c2009-11-09 01:38:00 +000011231 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11232 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +000011233
11234 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +000011235 if (PHIId < RHS.PHIId) return true;
11236 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011237 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +000011238 if (Shift > RHS.Shift) return false;
11239 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +000011240 RHS.Inst->getType()->getPrimitiveSizeInBits();
11241 }
11242};
Chris Lattner073c12c2009-11-09 01:38:00 +000011243
11244struct LoweredPHIRecord {
11245 PHINode *PN; // The PHI that was lowered.
11246 unsigned Shift; // The amount shifted.
11247 unsigned Width; // The width extracted.
11248
11249 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11250 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11251
11252 // Ctor form used by DenseMap.
11253 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11254 : PN(pn), Shift(Sh), Width(0) {}
11255};
11256}
11257
11258namespace llvm {
11259 template<>
11260 struct DenseMapInfo<LoweredPHIRecord> {
11261 static inline LoweredPHIRecord getEmptyKey() {
11262 return LoweredPHIRecord(0, 0);
11263 }
11264 static inline LoweredPHIRecord getTombstoneKey() {
11265 return LoweredPHIRecord(0, 1);
11266 }
11267 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11268 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11269 (Val.Width>>3);
11270 }
11271 static bool isEqual(const LoweredPHIRecord &LHS,
11272 const LoweredPHIRecord &RHS) {
11273 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11274 LHS.Width == RHS.Width;
11275 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011276 };
Chris Lattner169f3a22009-12-15 07:26:43 +000011277 template <>
11278 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner1cd526b2009-11-08 19:23:30 +000011279}
11280
11281
11282/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11283/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11284/// so, we split the PHI into the various pieces being extracted. This sort of
11285/// thing is introduced when SROA promotes an aggregate to large integer values.
11286///
11287/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11288/// inttoptr. We should produce new PHIs in the right type.
11289///
Chris Lattner073c12c2009-11-09 01:38:00 +000011290Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11291 // PHIUsers - Keep track of all of the truncated values extracted from a set
11292 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011293 SmallVector<PHIUsageRecord, 16> PHIUsers;
11294
Chris Lattner073c12c2009-11-09 01:38:00 +000011295 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11296 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11297 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11298 // check the uses of (to ensure they are all extracts).
11299 SmallVector<PHINode*, 8> PHIsToSlice;
11300 SmallPtrSet<PHINode*, 8> PHIsInspected;
11301
11302 PHIsToSlice.push_back(&FirstPhi);
11303 PHIsInspected.insert(&FirstPhi);
11304
11305 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11306 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011307
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011308 // Scan the input list of the PHI. If any input is an invoke, and if the
11309 // input is defined in the predecessor, then we won't be split the critical
11310 // edge which is required to insert a truncate. Because of this, we have to
11311 // bail out.
11312 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11313 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11314 if (II == 0) continue;
11315 if (II->getParent() != PN->getIncomingBlock(i))
11316 continue;
11317
11318 // If we have a phi, and if it's directly in the predecessor, then we have
11319 // a critical edge where we need to put the truncate. Since we can't
11320 // split the edge in instcombine, we have to bail out.
11321 return 0;
11322 }
11323
11324
Chris Lattner073c12c2009-11-09 01:38:00 +000011325 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11326 UI != E; ++UI) {
11327 Instruction *User = cast<Instruction>(*UI);
11328
11329 // If the user is a PHI, inspect its uses recursively.
11330 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11331 if (PHIsInspected.insert(UserPN))
11332 PHIsToSlice.push_back(UserPN);
11333 continue;
11334 }
11335
11336 // Truncates are always ok.
11337 if (isa<TruncInst>(User)) {
11338 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11339 continue;
11340 }
11341
11342 // Otherwise it must be a lshr which can only be used by one trunc.
11343 if (User->getOpcode() != Instruction::LShr ||
11344 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11345 !isa<ConstantInt>(User->getOperand(1)))
11346 return 0;
11347
11348 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11349 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011350 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011351 }
11352
11353 // If we have no users, they must be all self uses, just nuke the PHI.
11354 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +000011355 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011356
11357 // If this phi node is transformable, create new PHIs for all the pieces
11358 // extracted out of it. First, sort the users by their offset and size.
11359 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11360
Chris Lattner073c12c2009-11-09 01:38:00 +000011361 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11362 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11363 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11364 );
Chris Lattner1cd526b2009-11-08 19:23:30 +000011365
Chris Lattner073c12c2009-11-09 01:38:00 +000011366 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11367 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011368 DenseMap<BasicBlock*, Value*> PredValues;
11369
Chris Lattner073c12c2009-11-09 01:38:00 +000011370 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11371 // introduce redundant PHIs.
11372 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11373
11374 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11375 unsigned PHIId = PHIUsers[UserI].PHIId;
11376 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011377 unsigned Offset = PHIUsers[UserI].Shift;
11378 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011379
Chris Lattner073c12c2009-11-09 01:38:00 +000011380 PHINode *EltPHI;
11381
11382 // If we've already lowered a user like this, reuse the previously lowered
11383 // value.
11384 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +000011385
Chris Lattner073c12c2009-11-09 01:38:00 +000011386 // Otherwise, Create the new PHI node for this user.
11387 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11388 assert(EltPHI->getType() != PN->getType() &&
11389 "Truncate didn't shrink phi?");
11390
11391 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11392 BasicBlock *Pred = PN->getIncomingBlock(i);
11393 Value *&PredVal = PredValues[Pred];
11394
11395 // If we already have a value for this predecessor, reuse it.
11396 if (PredVal) {
11397 EltPHI->addIncoming(PredVal, Pred);
11398 continue;
11399 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011400
Chris Lattner073c12c2009-11-09 01:38:00 +000011401 // Handle the PHI self-reuse case.
11402 Value *InVal = PN->getIncomingValue(i);
11403 if (InVal == PN) {
11404 PredVal = EltPHI;
11405 EltPHI->addIncoming(PredVal, Pred);
11406 continue;
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011407 }
11408
11409 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattner073c12c2009-11-09 01:38:00 +000011410 // If the incoming value was a PHI, and if it was one of the PHIs we
11411 // already rewrote it, just use the lowered value.
11412 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11413 PredVal = Res;
11414 EltPHI->addIncoming(PredVal, Pred);
11415 continue;
11416 }
11417 }
11418
11419 // Otherwise, do an extract in the predecessor.
11420 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11421 Value *Res = InVal;
11422 if (Offset)
11423 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11424 Offset), "extract");
11425 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11426 PredVal = Res;
11427 EltPHI->addIncoming(Res, Pred);
11428
11429 // If the incoming value was a PHI, and if it was one of the PHIs we are
11430 // rewriting, we will ultimately delete the code we inserted. This
11431 // means we need to revisit that PHI to make sure we extract out the
11432 // needed piece.
11433 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11434 if (PHIsInspected.count(OldInVal)) {
11435 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11436 OldInVal)-PHIsToSlice.begin();
11437 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11438 cast<Instruction>(Res)));
11439 ++UserE;
11440 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011441 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011442 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011443
Chris Lattner073c12c2009-11-09 01:38:00 +000011444 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11445 << *EltPHI << '\n');
11446 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011447 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011448
Chris Lattner073c12c2009-11-09 01:38:00 +000011449 // Replace the use of this piece with the PHI node.
11450 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011451 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011452
11453 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11454 // with undefs.
11455 Value *Undef = UndefValue::get(FirstPhi.getType());
11456 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11457 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11458 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011459}
11460
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011461// PHINode simplification
11462//
11463Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11464 // If LCSSA is around, don't mess with Phi nodes
11465 if (MustPreserveLCSSA) return 0;
11466
11467 if (Value *V = PN.hasConstantValue())
11468 return ReplaceInstUsesWith(PN, V);
11469
11470 // If all PHI operands are the same operation, pull them through the PHI,
11471 // reducing code size.
11472 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000011473 isa<Instruction>(PN.getIncomingValue(1)) &&
11474 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11475 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11476 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11477 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011478 PN.getIncomingValue(0)->hasOneUse())
11479 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11480 return Result;
11481
11482 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11483 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11484 // PHI)... break the cycle.
11485 if (PN.hasOneUse()) {
11486 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11487 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11488 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11489 PotentiallyDeadPHIs.insert(&PN);
11490 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011491 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011492 }
11493
11494 // If this phi has a single use, and if that use just computes a value for
11495 // the next iteration of a loop, delete the phi. This occurs with unused
11496 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11497 // common case here is good because the only other things that catch this
11498 // are induction variable analysis (sometimes) and ADCE, which is only run
11499 // late.
11500 if (PHIUser->hasOneUse() &&
11501 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11502 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011503 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011504 }
11505 }
11506
Chris Lattner27b695d2007-11-06 21:52:06 +000011507 // We sometimes end up with phi cycles that non-obviously end up being the
11508 // same value, for example:
11509 // z = some value; x = phi (y, z); y = phi (x, z)
11510 // where the phi nodes don't necessarily need to be in the same block. Do a
11511 // quick check to see if the PHI node only contains a single non-phi value, if
11512 // so, scan to see if the phi cycle is actually equal to that value.
11513 {
11514 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11515 // Scan for the first non-phi operand.
11516 while (InValNo != NumOperandVals &&
11517 isa<PHINode>(PN.getIncomingValue(InValNo)))
11518 ++InValNo;
11519
11520 if (InValNo != NumOperandVals) {
11521 Value *NonPhiInVal = PN.getOperand(InValNo);
11522
11523 // Scan the rest of the operands to see if there are any conflicts, if so
11524 // there is no need to recursively scan other phis.
11525 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11526 Value *OpVal = PN.getIncomingValue(InValNo);
11527 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11528 break;
11529 }
11530
11531 // If we scanned over all operands, then we have one unique value plus
11532 // phi values. Scan PHI nodes to see if they all merge in each other or
11533 // the value.
11534 if (InValNo == NumOperandVals) {
11535 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11536 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11537 return ReplaceInstUsesWith(PN, NonPhiInVal);
11538 }
11539 }
11540 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011541
Dan Gohman2cc8e842009-10-31 14:22:52 +000011542 // If there are multiple PHIs, sort their operands so that they all list
11543 // the blocks in the same order. This will help identical PHIs be eliminated
11544 // by other passes. Other passes shouldn't depend on this for correctness
11545 // however.
11546 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11547 if (&PN != FirstPN)
11548 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +000011549 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +000011550 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11551 if (BBA != BBB) {
11552 Value *VA = PN.getIncomingValue(i);
11553 unsigned j = PN.getBasicBlockIndex(BBB);
11554 Value *VB = PN.getIncomingValue(j);
11555 PN.setIncomingBlock(i, BBB);
11556 PN.setIncomingValue(i, VB);
11557 PN.setIncomingBlock(j, BBA);
11558 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +000011559 // NOTE: Instcombine normally would want us to "return &PN" if we
11560 // modified any of the operands of an instruction. However, since we
11561 // aren't adding or removing uses (just rearranging them) we don't do
11562 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +000011563 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011564 }
11565
Chris Lattner1cd526b2009-11-08 19:23:30 +000011566 // If this is an integer PHI and we know that it has an illegal type, see if
11567 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11568 // PHI into the various pieces being extracted. This sort of thing is
11569 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +000011570 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +000011571 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11572 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11573 return Res;
11574
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011575 return 0;
11576}
11577
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011578Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +000011579 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11580
11581 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11582 return ReplaceInstUsesWith(GEP, V);
11583
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011584 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011585
11586 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011587 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011588
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011589 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011590 if (TD) {
11591 bool MadeChange = false;
11592 unsigned PtrSize = TD->getPointerSizeInBits();
11593
11594 gep_type_iterator GTI = gep_type_begin(GEP);
11595 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11596 I != E; ++I, ++GTI) {
11597 if (!isa<SequentialType>(*GTI)) continue;
11598
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011599 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011600 // to what we need. If narrower, sign-extend it to what we need. This
11601 // explicit cast can make subsequent optimizations more obvious.
11602 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011603 if (OpBits == PtrSize)
11604 continue;
11605
Chris Lattnerd6164c22009-08-30 20:01:10 +000011606 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011607 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011608 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011609 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011610 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011611
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011612 // Combine Indices - If the source pointer to this getelementptr instruction
11613 // is a getelementptr instruction, combine the indices of the two
11614 // getelementptr instructions into a single instruction.
11615 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011616 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011617 // Note that if our source is a gep chain itself that we wait for that
11618 // chain to be resolved before we perform this transformation. This
11619 // avoids us creating a TON of code in some cases.
11620 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011621 if (GetElementPtrInst *SrcGEP =
11622 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11623 if (SrcGEP->getNumOperands() == 2)
11624 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011625
11626 SmallVector<Value*, 8> Indices;
11627
11628 // Find out whether the last index in the source GEP is a sequential idx.
11629 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000011630 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11631 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011632 EndsWithSequential = !isa<StructType>(*I);
11633
11634 // Can we combine the two pointer arithmetics offsets?
11635 if (EndsWithSequential) {
11636 // Replace: gep (gep %P, long B), long A, ...
11637 // With: T = long A+B; gep %P, T, ...
11638 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011639 Value *Sum;
11640 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11641 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011642 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011643 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011644 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011645 Sum = SO1;
11646 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000011647 // If they aren't the same type, then the input hasn't been processed
11648 // by the loop above yet (which canonicalizes sequential index types to
11649 // intptr_t). Just avoid transforming this until the input has been
11650 // normalized.
11651 if (SO1->getType() != GO1->getType())
11652 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000011653 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011654 }
11655
Chris Lattner1c641fc2009-08-30 05:30:55 +000011656 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011657 if (Src->getNumOperands() == 2) {
11658 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011659 GEP.setOperand(1, Sum);
11660 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011661 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011662 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011663 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011664 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011665 } else if (isa<Constant>(*GEP.idx_begin()) &&
11666 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011667 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011668 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011669 Indices.append(Src->op_begin()+1, Src->op_end());
11670 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011671 }
11672
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011673 if (!Indices.empty())
11674 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11675 Src->isInBounds()) ?
11676 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11677 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011678 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011679 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011680 }
11681
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011682 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11683 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011684 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011685
Chris Lattner83288fa2009-08-30 20:38:21 +000011686 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11687 // want to change the gep until the bitcasts are eliminated.
11688 if (getBitCastOperand(X)) {
11689 Worklist.AddValue(PtrOp);
11690 return 0;
11691 }
11692
Chris Lattner5594a482009-11-27 00:29:05 +000011693 bool HasZeroPointerIndex = false;
11694 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11695 HasZeroPointerIndex = C->isZero();
11696
Chris Lattnerf3a23592009-08-30 20:36:46 +000011697 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11698 // into : GEP [10 x i8]* X, i32 0, ...
11699 //
11700 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11701 // into : GEP i8* X, ...
11702 //
11703 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011704 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011705 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11706 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011707 if (const ArrayType *CATy =
11708 dyn_cast<ArrayType>(CPTy->getElementType())) {
11709 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11710 if (CATy->getElementType() == XTy->getElementType()) {
11711 // -> GEP i8* X, ...
11712 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011713 return cast<GEPOperator>(&GEP)->isInBounds() ?
11714 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11715 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011716 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11717 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011718 }
11719
11720 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011721 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011722 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011723 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011724 // At this point, we know that the cast source type is a pointer
11725 // to an array of the same type as the destination pointer
11726 // array. Because the array type is never stepped over (there
11727 // is a leading zero) we can fold the cast into this GEP.
11728 GEP.setOperand(0, X);
11729 return &GEP;
11730 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011731 }
11732 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011733 } else if (GEP.getNumOperands() == 2) {
11734 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011735 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11736 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011737 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11738 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011739 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011740 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11741 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011742 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011743 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011744 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011745 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11746 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011747 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011748 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011749 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011750 }
11751
11752 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011753 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011754 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011755 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011756
Owen Anderson35b47072009-08-13 21:58:54 +000011757 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011758 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011759 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011760
11761 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11762 // allow either a mul, shift, or constant here.
11763 Value *NewIdx = 0;
11764 ConstantInt *Scale = 0;
11765 if (ArrayEltSize == 1) {
11766 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011767 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011768 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011769 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011770 Scale = CI;
11771 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11772 if (Inst->getOpcode() == Instruction::Shl &&
11773 isa<ConstantInt>(Inst->getOperand(1))) {
11774 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11775 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011776 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011777 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011778 NewIdx = Inst->getOperand(0);
11779 } else if (Inst->getOpcode() == Instruction::Mul &&
11780 isa<ConstantInt>(Inst->getOperand(1))) {
11781 Scale = cast<ConstantInt>(Inst->getOperand(1));
11782 NewIdx = Inst->getOperand(0);
11783 }
11784 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011785
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011786 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011787 // out, perform the transformation. Note, we don't know whether Scale is
11788 // signed or not. We'll use unsigned version of division/modulo
11789 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011790 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011791 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011792 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011793 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011794 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011795 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11796 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011797 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011798 }
11799
11800 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011801 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011802 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011803 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011804 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11805 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11806 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011807 // The NewGEP must be pointer typed, so must the old one -> BitCast
11808 return new BitCastInst(NewGEP, GEP.getType());
11809 }
11810 }
11811 }
11812 }
Chris Lattner111ea772009-01-09 04:53:57 +000011813
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011814 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011815 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011816 /// Y = gep X, <...constant indices...>
11817 /// into a gep of the original struct. This is important for SROA and alias
11818 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011819 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011820 if (TD &&
11821 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011822 // Determine how much the GEP moves the pointer. We are guaranteed to get
11823 // a constant back from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +000011824 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011825 int64_t Offset = OffsetV->getSExtValue();
11826
11827 // If this GEP instruction doesn't move the pointer, just replace the GEP
11828 // with a bitcast of the real input to the dest type.
11829 if (Offset == 0) {
11830 // If the bitcast is of an allocation, and the allocation will be
11831 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000011832 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000011833 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011834 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11835 if (Instruction *I = visitBitCast(*BCI)) {
11836 if (I != BCI) {
11837 I->takeName(BCI);
11838 BCI->getParent()->getInstList().insert(BCI, I);
11839 ReplaceInstUsesWith(*BCI, I);
11840 }
11841 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011842 }
Chris Lattner111ea772009-01-09 04:53:57 +000011843 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011844 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011845 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011846
11847 // Otherwise, if the offset is non-zero, we need to find out if there is a
11848 // field at Offset in 'A's type. If so, we can pull the cast through the
11849 // GEP.
11850 SmallVector<Value*, 8> NewIndices;
11851 const Type *InTy =
11852 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011853 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011854 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11855 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11856 NewIndices.end()) :
11857 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11858 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011859
11860 if (NGEP->getType() == GEP.getType())
11861 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011862 NGEP->takeName(&GEP);
11863 return new BitCastInst(NGEP, GEP.getType());
11864 }
Chris Lattner111ea772009-01-09 04:53:57 +000011865 }
11866 }
11867
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011868 return 0;
11869}
11870
Victor Hernandezb1687302009-10-23 21:09:37 +000011871Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +000011872 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011873 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011874 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11875 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011876 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000011877 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000011878 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011879 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011880
11881 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011882 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011883 //
11884 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000011885 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011886
11887 // Now that I is pointing to the first non-allocation-inst in the block,
11888 // insert our getelementptr instruction...
11889 //
Owen Anderson35b47072009-08-13 21:58:54 +000011890 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011891 Value *Idx[2];
11892 Idx[0] = NullIdx;
11893 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011894 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11895 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011896
11897 // Now make everything use the getelementptr instead of the original
11898 // allocation.
11899 return ReplaceInstUsesWith(AI, V);
11900 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011901 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011902 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011903 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011904
Dan Gohmana80e2712009-07-21 23:21:54 +000011905 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011906 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011907 // Note that we only do this for alloca's, because malloc should allocate
11908 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011909 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011910 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011911
11912 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11913 if (AI.getAlignment() == 0)
11914 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11915 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011916
11917 return 0;
11918}
11919
Victor Hernandez93946082009-10-24 04:23:03 +000011920Instruction *InstCombiner::visitFree(Instruction &FI) {
11921 Value *Op = FI.getOperand(1);
11922
11923 // free undef -> unreachable.
11924 if (isa<UndefValue>(Op)) {
11925 // Insert a new store to null because we cannot modify the CFG here.
11926 new StoreInst(ConstantInt::getTrue(*Context),
11927 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11928 return EraseInstFromFunction(FI);
11929 }
11930
11931 // If we have 'free null' delete the instruction. This can happen in stl code
11932 // when lots of inlining happens.
11933 if (isa<ConstantPointerNull>(Op))
11934 return EraseInstFromFunction(FI);
11935
Victor Hernandezf9a7a332009-10-26 23:43:48 +000011936 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +000011937 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +000011938 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11939 if (Op->hasOneUse() && CI->hasOneUse()) {
11940 EraseInstFromFunction(FI);
11941 EraseInstFromFunction(*CI);
11942 return EraseInstFromFunction(*cast<Instruction>(Op));
11943 }
11944 } else {
11945 // Op is a call to malloc
11946 if (Op->hasOneUse()) {
11947 EraseInstFromFunction(FI);
11948 return EraseInstFromFunction(*cast<Instruction>(Op));
11949 }
11950 }
Dan Gohman1674ea52009-10-27 00:11:02 +000011951 }
Victor Hernandez93946082009-10-24 04:23:03 +000011952
11953 return 0;
11954}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011955
11956/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011957static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011958 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011959 User *CI = cast<User>(LI.getOperand(0));
11960 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011961 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011962
Mon P Wangbd05ed82009-02-07 22:19:29 +000011963 const PointerType *DestTy = cast<PointerType>(CI->getType());
11964 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011965 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011966
11967 // If the address spaces don't match, don't eliminate the cast.
11968 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11969 return 0;
11970
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011971 const Type *SrcPTy = SrcTy->getElementType();
11972
11973 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11974 isa<VectorType>(DestPTy)) {
11975 // If the source is an array, the code below will not succeed. Check to
11976 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11977 // constants.
11978 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11979 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11980 if (ASrcTy->getNumElements() != 0) {
11981 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000011982 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11983 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000011984 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011985 SrcTy = cast<PointerType>(CastOp->getType());
11986 SrcPTy = SrcTy->getElementType();
11987 }
11988
Dan Gohmana80e2712009-07-21 23:21:54 +000011989 if (IC.getTargetData() &&
11990 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011991 isa<VectorType>(SrcPTy)) &&
11992 // Do not allow turning this into a load of an integer, which is then
11993 // casted to a pointer, this pessimizes pointer analysis a lot.
11994 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011995 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11996 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011997
11998 // Okay, we are casting from one integer or pointer type to another of
11999 // the same size. Instead of casting the pointer before the load, cast
12000 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000012001 Value *NewLoad =
12002 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012003 // Now cast the result of the load.
12004 return new BitCastInst(NewLoad, LI.getType());
12005 }
12006 }
12007 }
12008 return 0;
12009}
12010
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012011Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12012 Value *Op = LI.getOperand(0);
12013
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012014 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012015 if (TD) {
12016 unsigned KnownAlign =
12017 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12018 if (KnownAlign >
12019 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12020 LI.getAlignment()))
12021 LI.setAlignment(KnownAlign);
12022 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012023
Chris Lattnerf3a23592009-08-30 20:36:46 +000012024 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012025 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000012026 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012027 return Res;
12028
12029 // None of the following transforms are legal for volatile loads.
12030 if (LI.isVolatile()) return 0;
12031
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012032 // Do really simple store-to-load forwarding and load CSE, to catch cases
12033 // where there are several consequtive memory accesses to the same location,
12034 // separated by a few arithmetic operations.
12035 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000012036 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12037 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012038
Chris Lattner05274832009-10-22 06:25:11 +000012039 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000012040 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12041 const Value *GEPI0 = GEPI->getOperand(0);
12042 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000012043 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012044 // Insert a new store to null instruction before the load to indicate
12045 // that this code is not reachable. We do this instead of inserting
12046 // an unreachable instruction directly because we cannot modify the
12047 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012048 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000012049 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012050 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012051 }
Christopher Lamb2c175392007-12-29 07:56:53 +000012052 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012053
Chris Lattner05274832009-10-22 06:25:11 +000012054 // load null/undef -> unreachable
12055 // TODO: Consider a target hook for valid address spaces for this xform.
12056 if (isa<UndefValue>(Op) ||
12057 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12058 // Insert a new store to null instruction before the load to indicate that
12059 // this code is not reachable. We do this instead of inserting an
12060 // unreachable instruction directly because we cannot modify the CFG.
12061 new StoreInst(UndefValue::get(LI.getType()),
12062 Constant::getNullValue(Op->getType()), &LI);
12063 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012064 }
Chris Lattner05274832009-10-22 06:25:11 +000012065
12066 // Instcombine load (constantexpr_cast global) -> cast (load global)
12067 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12068 if (CE->isCast())
12069 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12070 return Res;
12071
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012072 if (Op->hasOneUse()) {
12073 // Change select and PHI nodes to select values instead of addresses: this
12074 // helps alias analysis out a lot, allows many others simplifications, and
12075 // exposes redundancy in the code.
12076 //
12077 // Note that we cannot do the transformation unless we know that the
12078 // introduced loads cannot trap! Something like this is valid as long as
12079 // the condition is always false: load (select bool %C, int* null, int* %G),
12080 // but it would not be valid if we transformed it to load from null
12081 // unconditionally.
12082 //
12083 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12084 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
12085 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12086 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000012087 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12088 SI->getOperand(1)->getName()+".val");
12089 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12090 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000012091 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012092 }
12093
12094 // load (select (cond, null, P)) -> load P
12095 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12096 if (C->isNullValue()) {
12097 LI.setOperand(0, SI->getOperand(2));
12098 return &LI;
12099 }
12100
12101 // load (select (cond, P, null)) -> load P
12102 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12103 if (C->isNullValue()) {
12104 LI.setOperand(0, SI->getOperand(1));
12105 return &LI;
12106 }
12107 }
12108 }
12109 return 0;
12110}
12111
12112/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000012113/// when possible. This makes it generally easy to do alias analysis and/or
12114/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012115static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12116 User *CI = cast<User>(SI.getOperand(1));
12117 Value *CastOp = CI->getOperand(0);
12118
12119 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000012120 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12121 if (SrcTy == 0) return 0;
12122
12123 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012124
Chris Lattnera032c0e2009-01-16 20:08:59 +000012125 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12126 return 0;
12127
Chris Lattner54dddc72009-01-24 01:00:13 +000012128 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12129 /// to its first element. This allows us to handle things like:
12130 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12131 /// on 32-bit hosts.
12132 SmallVector<Value*, 4> NewGEPIndices;
12133
Chris Lattnera032c0e2009-01-16 20:08:59 +000012134 // If the source is an array, the code below will not succeed. Check to
12135 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12136 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000012137 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12138 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000012139 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000012140 NewGEPIndices.push_back(Zero);
12141
12142 while (1) {
12143 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000012144 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000012145 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000012146 NewGEPIndices.push_back(Zero);
12147 SrcPTy = STy->getElementType(0);
12148 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12149 NewGEPIndices.push_back(Zero);
12150 SrcPTy = ATy->getElementType();
12151 } else {
12152 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012153 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012154 }
12155
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012156 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000012157 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000012158
12159 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12160 return 0;
12161
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012162 // If the pointers point into different address spaces or if they point to
12163 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000012164 if (!IC.getTargetData() ||
12165 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012166 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000012167 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12168 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000012169 return 0;
12170
12171 // Okay, we are casting from one integer or pointer type to another of
12172 // the same size. Instead of casting the pointer before
12173 // the store, cast the value to be stored.
12174 Value *NewCast;
12175 Value *SIOp0 = SI.getOperand(0);
12176 Instruction::CastOps opcode = Instruction::BitCast;
12177 const Type* CastSrcTy = SIOp0->getType();
12178 const Type* CastDstTy = SrcPTy;
12179 if (isa<PointerType>(CastDstTy)) {
12180 if (CastSrcTy->isInteger())
12181 opcode = Instruction::IntToPtr;
12182 } else if (isa<IntegerType>(CastDstTy)) {
12183 if (isa<PointerType>(SIOp0->getType()))
12184 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012185 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012186
12187 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12188 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012189 if (!NewGEPIndices.empty())
12190 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12191 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000012192
Chris Lattnerad7516a2009-08-30 18:50:58 +000012193 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12194 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000012195 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012196}
12197
Chris Lattner6fd8c802008-11-27 08:56:30 +000012198/// equivalentAddressValues - Test if A and B will obviously have the same
12199/// value. This includes recognizing that %t0 and %t1 will have the same
12200/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000012201/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012202/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000012203/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012204/// %t2 = load i32* %t1
12205///
12206static bool equivalentAddressValues(Value *A, Value *B) {
12207 // Test if the values are trivially equivalent.
12208 if (A == B) return true;
12209
12210 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012211 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12212 // its only used to compare two uses within the same basic block, which
12213 // means that they'll always either have the same value or one of them
12214 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000012215 if (isa<BinaryOperator>(A) ||
12216 isa<CastInst>(A) ||
12217 isa<PHINode>(A) ||
12218 isa<GetElementPtrInst>(A))
12219 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012220 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000012221 return true;
12222
12223 // Otherwise they may not be equivalent.
12224 return false;
12225}
12226
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012227// If this instruction has two uses, one of which is a llvm.dbg.declare,
12228// return the llvm.dbg.declare.
12229DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12230 if (!V->hasNUses(2))
12231 return 0;
12232 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12233 UI != E; ++UI) {
12234 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12235 return DI;
12236 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12237 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12238 return DI;
12239 }
12240 }
12241 return 0;
12242}
12243
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012244Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12245 Value *Val = SI.getOperand(0);
12246 Value *Ptr = SI.getOperand(1);
12247
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012248 // If the RHS is an alloca with a single use, zapify the store, making the
12249 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012250 // If the RHS is an alloca with a two uses, the other one being a
12251 // llvm.dbg.declare, zapify the store and the declare, making the
12252 // alloca dead. We must do this to prevent declare's from affecting
12253 // codegen.
12254 if (!SI.isVolatile()) {
12255 if (Ptr->hasOneUse()) {
12256 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012257 EraseInstFromFunction(SI);
12258 ++NumCombined;
12259 return 0;
12260 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012261 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12262 if (isa<AllocaInst>(GEP->getOperand(0))) {
12263 if (GEP->getOperand(0)->hasOneUse()) {
12264 EraseInstFromFunction(SI);
12265 ++NumCombined;
12266 return 0;
12267 }
12268 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12269 EraseInstFromFunction(*DI);
12270 EraseInstFromFunction(SI);
12271 ++NumCombined;
12272 return 0;
12273 }
12274 }
12275 }
12276 }
12277 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12278 EraseInstFromFunction(*DI);
12279 EraseInstFromFunction(SI);
12280 ++NumCombined;
12281 return 0;
12282 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012283 }
12284
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012285 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012286 if (TD) {
12287 unsigned KnownAlign =
12288 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12289 if (KnownAlign >
12290 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12291 SI.getAlignment()))
12292 SI.setAlignment(KnownAlign);
12293 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012294
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012295 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012296 // stores to the same location, separated by a few arithmetic operations. This
12297 // situation often occurs with bitfield accesses.
12298 BasicBlock::iterator BBI = &SI;
12299 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12300 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000012301 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000012302 // Don't count debug info directives, lest they affect codegen,
12303 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12304 // It is necessary for correctness to skip those that feed into a
12305 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000012306 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000012307 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012308 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012309 continue;
12310 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012311
12312 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12313 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000012314 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12315 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012316 ++NumDeadStore;
12317 ++BBI;
12318 EraseInstFromFunction(*PrevSI);
12319 continue;
12320 }
12321 break;
12322 }
12323
12324 // If this is a load, we have to stop. However, if the loaded value is from
12325 // the pointer we're loading and is producing the pointer we're storing,
12326 // then *this* store is dead (X = load P; store X -> P).
12327 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012328 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12329 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012330 EraseInstFromFunction(SI);
12331 ++NumCombined;
12332 return 0;
12333 }
12334 // Otherwise, this is a load from some other location. Stores before it
12335 // may not be dead.
12336 break;
12337 }
12338
12339 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000012340 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012341 break;
12342 }
12343
12344
12345 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12346
12347 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000012348 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012349 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012350 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012351 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000012352 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012353 ++NumCombined;
12354 }
12355 return 0; // Do not modify these!
12356 }
12357
12358 // store undef, Ptr -> noop
12359 if (isa<UndefValue>(Val)) {
12360 EraseInstFromFunction(SI);
12361 ++NumCombined;
12362 return 0;
12363 }
12364
12365 // If the pointer destination is a cast, see if we can fold the cast into the
12366 // source instead.
12367 if (isa<CastInst>(Ptr))
12368 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12369 return Res;
12370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12371 if (CE->isCast())
12372 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12373 return Res;
12374
12375
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012376 // If this store is the last instruction in the basic block (possibly
12377 // excepting debug info instructions and the pointer bitcasts that feed
12378 // into them), and if the block ends with an unconditional branch, try
12379 // to move it to the successor block.
12380 BBI = &SI;
12381 do {
12382 ++BBI;
12383 } while (isa<DbgInfoIntrinsic>(BBI) ||
12384 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012385 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12386 if (BI->isUnconditional())
12387 if (SimplifyStoreAtEndOfBlock(SI))
12388 return 0; // xform done!
12389
12390 return 0;
12391}
12392
12393/// SimplifyStoreAtEndOfBlock - Turn things like:
12394/// if () { *P = v1; } else { *P = v2 }
12395/// into a phi node with a store in the successor.
12396///
12397/// Simplify things like:
12398/// *P = v1; if () { *P = v2; }
12399/// into a phi node with a store in the successor.
12400///
12401bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12402 BasicBlock *StoreBB = SI.getParent();
12403
12404 // Check to see if the successor block has exactly two incoming edges. If
12405 // so, see if the other predecessor contains a store to the same location.
12406 // if so, insert a PHI node (if needed) and move the stores down.
12407 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12408
12409 // Determine whether Dest has exactly two predecessors and, if so, compute
12410 // the other predecessor.
12411 pred_iterator PI = pred_begin(DestBB);
12412 BasicBlock *OtherBB = 0;
12413 if (*PI != StoreBB)
12414 OtherBB = *PI;
12415 ++PI;
12416 if (PI == pred_end(DestBB))
12417 return false;
12418
12419 if (*PI != StoreBB) {
12420 if (OtherBB)
12421 return false;
12422 OtherBB = *PI;
12423 }
12424 if (++PI != pred_end(DestBB))
12425 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012426
12427 // Bail out if all the relevant blocks aren't distinct (this can happen,
12428 // for example, if SI is in an infinite loop)
12429 if (StoreBB == DestBB || OtherBB == DestBB)
12430 return false;
12431
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012432 // Verify that the other block ends in a branch and is not otherwise empty.
12433 BasicBlock::iterator BBI = OtherBB->getTerminator();
12434 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12435 if (!OtherBr || BBI == OtherBB->begin())
12436 return false;
12437
12438 // If the other block ends in an unconditional branch, check for the 'if then
12439 // else' case. there is an instruction before the branch.
12440 StoreInst *OtherStore = 0;
12441 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012442 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012443 // Skip over debugging info.
12444 while (isa<DbgInfoIntrinsic>(BBI) ||
12445 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12446 if (BBI==OtherBB->begin())
12447 return false;
12448 --BBI;
12449 }
Chris Lattner69fa3f52009-11-02 02:06:37 +000012450 // If this isn't a store, isn't a store to the same location, or if the
12451 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012452 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +000012453 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12454 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012455 return false;
12456 } else {
12457 // Otherwise, the other block ended with a conditional branch. If one of the
12458 // destinations is StoreBB, then we have the if/then case.
12459 if (OtherBr->getSuccessor(0) != StoreBB &&
12460 OtherBr->getSuccessor(1) != StoreBB)
12461 return false;
12462
12463 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12464 // if/then triangle. See if there is a store to the same ptr as SI that
12465 // lives in OtherBB.
12466 for (;; --BBI) {
12467 // Check to see if we find the matching store.
12468 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +000012469 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12470 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012471 return false;
12472 break;
12473 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012474 // If we find something that may be using or overwriting the stored
12475 // value, or if we run out of instructions, we can't do the xform.
12476 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012477 BBI == OtherBB->begin())
12478 return false;
12479 }
12480
12481 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012482 // make sure nothing reads or overwrites the stored value in
12483 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012484 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12485 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012486 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012487 return false;
12488 }
12489 }
12490
12491 // Insert a PHI node now if we need it.
12492 Value *MergedVal = OtherStore->getOperand(0);
12493 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012494 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012495 PN->reserveOperandSpace(2);
12496 PN->addIncoming(SI.getOperand(0), SI.getParent());
12497 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12498 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12499 }
12500
12501 // Advance to a place where it is safe to insert the new store and
12502 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012503 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012504 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +000012505 OtherStore->isVolatile(),
12506 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012507
12508 // Nuke the old stores.
12509 EraseInstFromFunction(SI);
12510 EraseInstFromFunction(*OtherStore);
12511 ++NumCombined;
12512 return true;
12513}
12514
12515
12516Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12517 // Change br (not X), label True, label False to: br X, label False, True
12518 Value *X = 0;
12519 BasicBlock *TrueDest;
12520 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012521 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012522 !isa<Constant>(X)) {
12523 // Swap Destinations and condition...
12524 BI.setCondition(X);
12525 BI.setSuccessor(0, FalseDest);
12526 BI.setSuccessor(1, TrueDest);
12527 return &BI;
12528 }
12529
12530 // Cannonicalize fcmp_one -> fcmp_oeq
12531 FCmpInst::Predicate FPred; Value *Y;
12532 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012533 TrueDest, FalseDest)) &&
12534 BI.getCondition()->hasOneUse())
12535 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12536 FPred == FCmpInst::FCMP_OGE) {
12537 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12538 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12539
12540 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012541 BI.setSuccessor(0, FalseDest);
12542 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012543 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012544 return &BI;
12545 }
12546
12547 // Cannonicalize icmp_ne -> icmp_eq
12548 ICmpInst::Predicate IPred;
12549 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012550 TrueDest, FalseDest)) &&
12551 BI.getCondition()->hasOneUse())
12552 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12553 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12554 IPred == ICmpInst::ICMP_SGE) {
12555 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12556 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12557 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012558 BI.setSuccessor(0, FalseDest);
12559 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012560 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012561 return &BI;
12562 }
12563
12564 return 0;
12565}
12566
12567Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12568 Value *Cond = SI.getCondition();
12569 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12570 if (I->getOpcode() == Instruction::Add)
12571 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12572 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12573 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012574 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012575 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012576 AddRHS));
12577 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012578 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012579 return &SI;
12580 }
12581 }
12582 return 0;
12583}
12584
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012585Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012586 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012587
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012588 if (!EV.hasIndices())
12589 return ReplaceInstUsesWith(EV, Agg);
12590
12591 if (Constant *C = dyn_cast<Constant>(Agg)) {
12592 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012593 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012594
12595 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012596 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012597
12598 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12599 // Extract the element indexed by the first index out of the constant
12600 Value *V = C->getOperand(*EV.idx_begin());
12601 if (EV.getNumIndices() > 1)
12602 // Extract the remaining indices out of the constant indexed by the
12603 // first index
12604 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12605 else
12606 return ReplaceInstUsesWith(EV, V);
12607 }
12608 return 0; // Can't handle other constants
12609 }
12610 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12611 // We're extracting from an insertvalue instruction, compare the indices
12612 const unsigned *exti, *exte, *insi, *inse;
12613 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12614 exte = EV.idx_end(), inse = IV->idx_end();
12615 exti != exte && insi != inse;
12616 ++exti, ++insi) {
12617 if (*insi != *exti)
12618 // The insert and extract both reference distinctly different elements.
12619 // This means the extract is not influenced by the insert, and we can
12620 // replace the aggregate operand of the extract with the aggregate
12621 // operand of the insert. i.e., replace
12622 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12623 // %E = extractvalue { i32, { i32 } } %I, 0
12624 // with
12625 // %E = extractvalue { i32, { i32 } } %A, 0
12626 return ExtractValueInst::Create(IV->getAggregateOperand(),
12627 EV.idx_begin(), EV.idx_end());
12628 }
12629 if (exti == exte && insi == inse)
12630 // Both iterators are at the end: Index lists are identical. Replace
12631 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12632 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12633 // with "i32 42"
12634 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12635 if (exti == exte) {
12636 // The extract list is a prefix of the insert list. i.e. replace
12637 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12638 // %E = extractvalue { i32, { i32 } } %I, 1
12639 // with
12640 // %X = extractvalue { i32, { i32 } } %A, 1
12641 // %E = insertvalue { i32 } %X, i32 42, 0
12642 // by switching the order of the insert and extract (though the
12643 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012644 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12645 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012646 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12647 insi, inse);
12648 }
12649 if (insi == inse)
12650 // The insert list is a prefix of the extract list
12651 // We can simply remove the common indices from the extract and make it
12652 // operate on the inserted value instead of the insertvalue result.
12653 // i.e., replace
12654 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12655 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12656 // with
12657 // %E extractvalue { i32 } { i32 42 }, 0
12658 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12659 exti, exte);
12660 }
Chris Lattner69a70752009-11-09 07:07:56 +000012661 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12662 // We're extracting from an intrinsic, see if we're the only user, which
12663 // allows us to simplify multiple result intrinsics to simpler things that
12664 // just get one value..
12665 if (II->hasOneUse()) {
12666 // Check if we're grabbing the overflow bit or the result of a 'with
12667 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12668 // and replace it with a traditional binary instruction.
12669 switch (II->getIntrinsicID()) {
12670 case Intrinsic::uadd_with_overflow:
12671 case Intrinsic::sadd_with_overflow:
12672 if (*EV.idx_begin() == 0) { // Normal result.
12673 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12674 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12675 EraseInstFromFunction(*II);
12676 return BinaryOperator::CreateAdd(LHS, RHS);
12677 }
12678 break;
12679 case Intrinsic::usub_with_overflow:
12680 case Intrinsic::ssub_with_overflow:
12681 if (*EV.idx_begin() == 0) { // Normal result.
12682 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12683 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12684 EraseInstFromFunction(*II);
12685 return BinaryOperator::CreateSub(LHS, RHS);
12686 }
12687 break;
12688 case Intrinsic::umul_with_overflow:
12689 case Intrinsic::smul_with_overflow:
12690 if (*EV.idx_begin() == 0) { // Normal result.
12691 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12692 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12693 EraseInstFromFunction(*II);
12694 return BinaryOperator::CreateMul(LHS, RHS);
12695 }
12696 break;
12697 default:
12698 break;
12699 }
12700 }
12701 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012702 // Can't simplify extracts from other values. Note that nested extracts are
12703 // already simplified implicitely by the above (extract ( extract (insert) )
12704 // will be translated into extract ( insert ( extract ) ) first and then just
12705 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012706 return 0;
12707}
12708
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012709/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12710/// is to leave as a vector operation.
12711static bool CheapToScalarize(Value *V, bool isConstant) {
12712 if (isa<ConstantAggregateZero>(V))
12713 return true;
12714 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12715 if (isConstant) return true;
12716 // If all elts are the same, we can extract.
12717 Constant *Op0 = C->getOperand(0);
12718 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12719 if (C->getOperand(i) != Op0)
12720 return false;
12721 return true;
12722 }
12723 Instruction *I = dyn_cast<Instruction>(V);
12724 if (!I) return false;
12725
12726 // Insert element gets simplified to the inserted element or is deleted if
12727 // this is constant idx extract element and its a constant idx insertelt.
12728 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12729 isa<ConstantInt>(I->getOperand(2)))
12730 return true;
12731 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12732 return true;
12733 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12734 if (BO->hasOneUse() &&
12735 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12736 CheapToScalarize(BO->getOperand(1), isConstant)))
12737 return true;
12738 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12739 if (CI->hasOneUse() &&
12740 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12741 CheapToScalarize(CI->getOperand(1), isConstant)))
12742 return true;
12743
12744 return false;
12745}
12746
12747/// Read and decode a shufflevector mask.
12748///
12749/// It turns undef elements into values that are larger than the number of
12750/// elements in the input.
12751static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12752 unsigned NElts = SVI->getType()->getNumElements();
12753 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12754 return std::vector<unsigned>(NElts, 0);
12755 if (isa<UndefValue>(SVI->getOperand(2)))
12756 return std::vector<unsigned>(NElts, 2*NElts);
12757
12758 std::vector<unsigned> Result;
12759 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012760 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12761 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012762 Result.push_back(NElts*2); // undef -> 8
12763 else
Gabor Greif17396002008-06-12 21:37:33 +000012764 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012765 return Result;
12766}
12767
12768/// FindScalarElement - Given a vector and an element number, see if the scalar
12769/// value is already around as a register, for example if it were inserted then
12770/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012771static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012772 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012773 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12774 const VectorType *PTy = cast<VectorType>(V->getType());
12775 unsigned Width = PTy->getNumElements();
12776 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012777 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012778
12779 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012780 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012781 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012782 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012783 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12784 return CP->getOperand(EltNo);
12785 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12786 // If this is an insert to a variable element, we don't know what it is.
12787 if (!isa<ConstantInt>(III->getOperand(2)))
12788 return 0;
12789 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12790
12791 // If this is an insert to the element we are looking for, return the
12792 // inserted value.
12793 if (EltNo == IIElt)
12794 return III->getOperand(1);
12795
12796 // Otherwise, the insertelement doesn't modify the value, recurse on its
12797 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012798 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012799 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012800 unsigned LHSWidth =
12801 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012802 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012803 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012804 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012805 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012806 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012807 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012808 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012809 }
12810
12811 // Otherwise, we don't know.
12812 return 0;
12813}
12814
12815Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012816 // If vector val is undef, replace extract with scalar undef.
12817 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012818 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012819
12820 // If vector val is constant 0, replace extract with scalar 0.
12821 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012822 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012823
12824 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012825 // If vector val is constant with all elements the same, replace EI with
12826 // that element. When the elements are not identical, we cannot replace yet
12827 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012828 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012829 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012830 if (C->getOperand(i) != op0) {
12831 op0 = 0;
12832 break;
12833 }
12834 if (op0)
12835 return ReplaceInstUsesWith(EI, op0);
12836 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012837
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012838 // If extracting a specified index from the vector, see if we can recursively
12839 // find a previously computed scalar that was inserted into the vector.
12840 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12841 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012842 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012843
12844 // If this is extracting an invalid index, turn this into undef, to avoid
12845 // crashing the code below.
12846 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012847 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012848
12849 // This instruction only demands the single element from the input vector.
12850 // If the input vector has a single use, simplify it based on this use
12851 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012852 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012853 APInt UndefElts(VectorWidth, 0);
12854 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012855 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012856 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012857 EI.setOperand(0, V);
12858 return &EI;
12859 }
12860 }
12861
Owen Anderson24be4c12009-07-03 00:17:18 +000012862 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012863 return ReplaceInstUsesWith(EI, Elt);
12864
12865 // If the this extractelement is directly using a bitcast from a vector of
12866 // the same number of elements, see if we can find the source element from
12867 // it. In this case, we will end up needing to bitcast the scalars.
12868 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12869 if (const VectorType *VT =
12870 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12871 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012872 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12873 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012874 return new BitCastInst(Elt, EI.getType());
12875 }
12876 }
12877
12878 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012879 // Push extractelement into predecessor operation if legal and
12880 // profitable to do so
12881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12882 if (I->hasOneUse() &&
12883 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12884 Value *newEI0 =
12885 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12886 EI.getName()+".lhs");
12887 Value *newEI1 =
12888 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12889 EI.getName()+".rhs");
12890 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012891 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012892 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012893 // Extracting the inserted element?
12894 if (IE->getOperand(2) == EI.getOperand(1))
12895 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12896 // If the inserted and extracted elements are constants, they must not
12897 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012898 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012899 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012900 EI.setOperand(0, IE->getOperand(0));
12901 return &EI;
12902 }
12903 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12904 // If this is extracting an element from a shufflevector, figure out where
12905 // it came from and extract from the appropriate input element instead.
12906 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12907 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12908 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012909 unsigned LHSWidth =
12910 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12911
12912 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012913 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012914 else if (SrcIdx < LHSWidth*2) {
12915 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012916 Src = SVI->getOperand(1);
12917 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012918 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012919 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012920 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012921 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12922 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012923 }
12924 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012925 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012926 }
12927 return 0;
12928}
12929
12930/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12931/// elements from either LHS or RHS, return the shuffle mask and true.
12932/// Otherwise, return false.
12933static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012934 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012935 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012936 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12937 "Invalid CollectSingleShuffleElements");
12938 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12939
12940 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012941 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012942 return true;
12943 } else if (V == LHS) {
12944 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012945 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012946 return true;
12947 } else if (V == RHS) {
12948 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012949 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012950 return true;
12951 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12952 // If this is an insert of an extract from some other vector, include it.
12953 Value *VecOp = IEI->getOperand(0);
12954 Value *ScalarOp = IEI->getOperand(1);
12955 Value *IdxOp = IEI->getOperand(2);
12956
12957 if (!isa<ConstantInt>(IdxOp))
12958 return false;
12959 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12960
12961 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12962 // Okay, we can handle this if the vector we are insertinting into is
12963 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012964 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012965 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012966 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012967 return true;
12968 }
12969 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12970 if (isa<ConstantInt>(EI->getOperand(1)) &&
12971 EI->getOperand(0)->getType() == V->getType()) {
12972 unsigned ExtractedIdx =
12973 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12974
12975 // This must be extracting from either LHS or RHS.
12976 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12977 // Okay, we can handle this if the vector we are insertinting into is
12978 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012979 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012980 // If so, update the mask to reflect the inserted value.
12981 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012982 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012983 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012984 } else {
12985 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012986 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012987 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012988
12989 }
12990 return true;
12991 }
12992 }
12993 }
12994 }
12995 }
12996 // TODO: Handle shufflevector here!
12997
12998 return false;
12999}
13000
13001/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13002/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13003/// that computes V and the LHS value of the shuffle.
13004static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013005 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013006 assert(isa<VectorType>(V->getType()) &&
13007 (RHS == 0 || V->getType() == RHS->getType()) &&
13008 "Invalid shuffle!");
13009 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13010
13011 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013012 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013013 return V;
13014 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013015 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013016 return V;
13017 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13018 // If this is an insert of an extract from some other vector, include it.
13019 Value *VecOp = IEI->getOperand(0);
13020 Value *ScalarOp = IEI->getOperand(1);
13021 Value *IdxOp = IEI->getOperand(2);
13022
13023 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13024 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13025 EI->getOperand(0)->getType() == V->getType()) {
13026 unsigned ExtractedIdx =
13027 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13028 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13029
13030 // Either the extracted from or inserted into vector must be RHSVec,
13031 // otherwise we'd end up with a shuffle of three inputs.
13032 if (EI->getOperand(0) == RHS || RHS == 0) {
13033 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000013034 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013035 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013036 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013037 return V;
13038 }
13039
13040 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000013041 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13042 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013043 // Everything but the extracted element is replaced with the RHS.
13044 for (unsigned i = 0; i != NumElts; ++i) {
13045 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000013046 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013047 }
13048 return V;
13049 }
13050
13051 // If this insertelement is a chain that comes from exactly these two
13052 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000013053 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13054 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013055 return EI->getOperand(0);
13056
13057 }
13058 }
13059 }
13060 // TODO: Handle shufflevector here!
13061
13062 // Otherwise, can't do anything fancy. Return an identity vector.
13063 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013064 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013065 return V;
13066}
13067
13068Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13069 Value *VecOp = IE.getOperand(0);
13070 Value *ScalarOp = IE.getOperand(1);
13071 Value *IdxOp = IE.getOperand(2);
13072
13073 // Inserting an undef or into an undefined place, remove this.
13074 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13075 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000013076
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013077 // If the inserted element was extracted from some other vector, and if the
13078 // indexes are constant, try to turn this into a shufflevector operation.
13079 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13080 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13081 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000013082 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013083 unsigned ExtractedIdx =
13084 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13085 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13086
13087 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13088 return ReplaceInstUsesWith(IE, VecOp);
13089
13090 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000013091 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013092
13093 // If we are extracting a value from a vector, then inserting it right
13094 // back into the same place, just use the input vector.
13095 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13096 return ReplaceInstUsesWith(IE, VecOp);
13097
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013098 // If this insertelement isn't used by some other insertelement, turn it
13099 // (and any insertelements it points to), into one big shuffle.
13100 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13101 std::vector<Constant*> Mask;
13102 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000013103 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000013104 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013105 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000013106 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000013107 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013108 }
13109 }
13110 }
13111
Eli Friedmanbefee262009-06-06 20:08:03 +000013112 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13113 APInt UndefElts(VWidth, 0);
13114 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13115 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13116 return &IE;
13117
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013118 return 0;
13119}
13120
13121
13122Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13123 Value *LHS = SVI.getOperand(0);
13124 Value *RHS = SVI.getOperand(1);
13125 std::vector<unsigned> Mask = getShuffleMask(&SVI);
13126
13127 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013128
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013129 // Undefined shuffle mask -> undefined value.
13130 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013131 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013132
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013133 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013134
13135 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13136 return 0;
13137
Evan Cheng63295ab2009-02-03 10:05:09 +000013138 APInt UndefElts(VWidth, 0);
13139 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13140 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000013141 LHS = SVI.getOperand(0);
13142 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013143 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000013144 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013145
13146 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13147 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13148 if (LHS == RHS || isa<UndefValue>(LHS)) {
13149 if (isa<UndefValue>(LHS) && LHS == RHS) {
13150 // shuffle(undef,undef,mask) -> undef.
13151 return ReplaceInstUsesWith(SVI, LHS);
13152 }
13153
13154 // Remap any references to RHS to use LHS.
13155 std::vector<Constant*> Elts;
13156 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13157 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000013158 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013159 else {
13160 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000013161 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013162 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013163 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013164 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013165 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000013166 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013167 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013168 }
13169 }
13170 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000013171 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000013172 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013173 LHS = SVI.getOperand(0);
13174 RHS = SVI.getOperand(1);
13175 MadeChange = true;
13176 }
13177
13178 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13179 bool isLHSID = true, isRHSID = true;
13180
13181 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13182 if (Mask[i] >= e*2) continue; // Ignore undef values.
13183 // Is this an identity shuffle of the LHS value?
13184 isLHSID &= (Mask[i] == i);
13185
13186 // Is this an identity shuffle of the RHS value?
13187 isRHSID &= (Mask[i]-e == i);
13188 }
13189
13190 // Eliminate identity shuffles.
13191 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13192 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13193
13194 // If the LHS is a shufflevector itself, see if we can combine it with this
13195 // one without producing an unusual shuffle. Here we are really conservative:
13196 // we are absolutely afraid of producing a shuffle mask not in the input
13197 // program, because the code gen may not be smart enough to turn a merged
13198 // shuffle into two specific shuffles: it may produce worse code. As such,
13199 // we only merge two shuffles if the result is one of the two input shuffle
13200 // masks. In this case, merging the shuffles just removes one instruction,
13201 // which we know is safe. This is good for things like turning:
13202 // (splat(splat)) -> splat.
13203 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13204 if (isa<UndefValue>(RHS)) {
13205 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13206
David Greeneb736b5d2009-11-16 21:52:23 +000013207 if (LHSMask.size() == Mask.size()) {
13208 std::vector<unsigned> NewMask;
13209 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sandse7f89b02009-11-20 13:19:51 +000013210 if (Mask[i] >= e)
David Greeneb736b5d2009-11-16 21:52:23 +000013211 NewMask.push_back(2*e);
13212 else
13213 NewMask.push_back(LHSMask[Mask[i]]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013214
David Greeneb736b5d2009-11-16 21:52:23 +000013215 // If the result mask is equal to the src shuffle or this
13216 // shuffle mask, do the replacement.
13217 if (NewMask == LHSMask || NewMask == Mask) {
13218 unsigned LHSInNElts =
13219 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13220 getNumElements();
13221 std::vector<Constant*> Elts;
13222 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13223 if (NewMask[i] >= LHSInNElts*2) {
13224 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13225 } else {
13226 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13227 NewMask[i]));
13228 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013229 }
David Greeneb736b5d2009-11-16 21:52:23 +000013230 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13231 LHSSVI->getOperand(1),
13232 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013233 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013234 }
13235 }
13236 }
13237
13238 return MadeChange ? &SVI : 0;
13239}
13240
13241
13242
13243
13244/// TryToSinkInstruction - Try to move the specified instruction from its
13245/// current block into the beginning of DestBlock, which can only happen if it's
13246/// safe to move the instruction past all of the instructions between it and the
13247/// end of its block.
13248static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13249 assert(I->hasOneUse() && "Invariants didn't hold!");
13250
13251 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000013252 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000013253 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013254
13255 // Do not sink alloca instructions out of the entry block.
13256 if (isa<AllocaInst>(I) && I->getParent() ==
13257 &DestBlock->getParent()->getEntryBlock())
13258 return false;
13259
13260 // We can only sink load instructions if there is nothing between the load and
13261 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000013262 if (I->mayReadFromMemory()) {
13263 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013264 Scan != E; ++Scan)
13265 if (Scan->mayWriteToMemory())
13266 return false;
13267 }
13268
Dan Gohman514277c2008-05-23 21:05:58 +000013269 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013270
Dale Johannesen24339f12009-03-03 01:09:07 +000013271 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013272 I->moveBefore(InsertPos);
13273 ++NumSunkInst;
13274 return true;
13275}
13276
13277
13278/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13279/// all reachable code to the worklist.
13280///
13281/// This has a couple of tricks to make the code faster and more powerful. In
13282/// particular, we constant fold and DCE instructions as we go, to avoid adding
13283/// them to the worklist (this significantly speeds up instcombine on code where
13284/// many instructions are dead or constant). Additionally, if we find a branch
13285/// whose condition is a known constant, we only visit the reachable successors.
13286///
Chris Lattnerc4269e52009-10-15 04:59:28 +000013287static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013288 SmallPtrSet<BasicBlock*, 64> &Visited,
13289 InstCombiner &IC,
13290 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000013291 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000013292 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013293 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000013294
13295 std::vector<Instruction*> InstrsForInstCombineWorklist;
13296 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013297
Chris Lattnerc4269e52009-10-15 04:59:28 +000013298 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13299
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013300 while (!Worklist.empty()) {
13301 BB = Worklist.back();
13302 Worklist.pop_back();
13303
13304 // We have now visited this block! If we've already been here, ignore it.
13305 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000013306
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013307 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13308 Instruction *Inst = BBI++;
13309
13310 // DCE instruction if trivially dead.
13311 if (isInstructionTriviallyDead(Inst)) {
13312 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000013313 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013314 Inst->eraseFromParent();
13315 continue;
13316 }
13317
13318 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000013319 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013320 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013321 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13322 << *Inst << '\n');
13323 Inst->replaceAllUsesWith(C);
13324 ++NumConstProp;
13325 Inst->eraseFromParent();
13326 continue;
13327 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000013328
13329
13330
13331 if (TD) {
13332 // See if we can constant fold its operands.
13333 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13334 i != e; ++i) {
13335 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13336 if (CE == 0) continue;
13337
13338 // If we already folded this constant, don't try again.
13339 if (!FoldedConstants.insert(CE))
13340 continue;
13341
Chris Lattner6070c012009-11-06 04:27:31 +000013342 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +000013343 if (NewC && NewC != CE) {
13344 *i = NewC;
13345 MadeIRChange = true;
13346 }
13347 }
13348 }
13349
Devang Patel794140c2008-11-19 18:56:50 +000013350
Chris Lattnerb5663c72009-10-12 03:58:40 +000013351 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013352 }
13353
13354 // Recursively visit successors. If this is a branch or switch on a
13355 // constant, only visit the reachable successor.
13356 TerminatorInst *TI = BB->getTerminator();
13357 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13358 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13359 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013360 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013361 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013362 continue;
13363 }
13364 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13365 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13366 // See if this is an explicit destination.
13367 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13368 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013369 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013370 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013371 continue;
13372 }
13373
13374 // Otherwise it is the default destination.
13375 Worklist.push_back(SI->getSuccessor(0));
13376 continue;
13377 }
13378 }
13379
13380 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13381 Worklist.push_back(TI->getSuccessor(i));
13382 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000013383
13384 // Once we've found all of the instructions to add to instcombine's worklist,
13385 // add them in reverse order. This way instcombine will visit from the top
13386 // of the function down. This jives well with the way that it adds all uses
13387 // of instructions to the worklist after doing a transformation, thus avoiding
13388 // some N^2 behavior in pathological cases.
13389 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13390 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000013391
13392 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013393}
13394
13395bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000013396 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013397
Daniel Dunbar005975c2009-07-25 00:23:56 +000013398 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13399 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013400
13401 {
13402 // Do a depth-first traversal of the function, populate the worklist with
13403 // the reachable instructions. Ignore blocks that are not reachable. Keep
13404 // track of which blocks we visit.
13405 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000013406 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013407
13408 // Do a quick scan over the function. If we find any blocks that are
13409 // unreachable, remove any instructions inside of them. This prevents
13410 // the instcombine code from having to deal with some bad special cases.
13411 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13412 if (!Visited.count(BB)) {
13413 Instruction *Term = BB->getTerminator();
13414 while (Term != BB->begin()) { // Remove instrs bottom-up
13415 BasicBlock::iterator I = Term; --I;
13416
Chris Lattner8a6411c2009-08-23 04:37:46 +000013417 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013418 // A debug intrinsic shouldn't force another iteration if we weren't
13419 // going to do one without it.
13420 if (!isa<DbgInfoIntrinsic>(I)) {
13421 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013422 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000013423 }
Devang Patele3829c82009-10-13 22:56:32 +000013424
Devang Patele3829c82009-10-13 22:56:32 +000013425 // If I is not void type then replaceAllUsesWith undef.
13426 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000013427 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000013428 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013429 I->eraseFromParent();
13430 }
13431 }
13432 }
13433
Chris Lattner5119c702009-08-30 05:55:36 +000013434 while (!Worklist.isEmpty()) {
13435 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013436 if (I == 0) continue; // skip null values.
13437
13438 // Check to see if we can DCE the instruction.
13439 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013440 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000013441 EraseInstFromFunction(*I);
13442 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013443 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013444 continue;
13445 }
13446
13447 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000013448 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013449 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013450 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013451
Chris Lattneree5839b2009-10-15 04:13:44 +000013452 // Add operands to the worklist.
13453 ReplaceInstUsesWith(*I, C);
13454 ++NumConstProp;
13455 EraseInstFromFunction(*I);
13456 MadeIRChange = true;
13457 continue;
13458 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013459
13460 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013461 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013462 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000013463 Instruction *UserInst = cast<Instruction>(I->use_back());
13464 BasicBlock *UserParent;
13465
13466 // Get the block the use occurs in.
13467 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13468 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13469 else
13470 UserParent = UserInst->getParent();
13471
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013472 if (UserParent != BB) {
13473 bool UserIsSuccessor = false;
13474 // See if the user is one of our successors.
13475 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13476 if (*SI == UserParent) {
13477 UserIsSuccessor = true;
13478 break;
13479 }
13480
13481 // If the user is one of our immediate successors, and if that successor
13482 // only has us as a predecessors (we'd have to split the critical edge
13483 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000013484 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013485 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000013486 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013487 }
13488 }
13489
Chris Lattnerc7694852009-08-30 07:44:24 +000013490 // Now that we have an instruction, try combining it to simplify it.
13491 Builder->SetInsertPoint(I->getParent(), I);
13492
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013493#ifndef NDEBUG
13494 std::string OrigI;
13495#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013496 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000013497 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13498
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013499 if (Instruction *Result = visit(*I)) {
13500 ++NumCombined;
13501 // Should we replace the old instruction with a new one?
13502 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013503 DEBUG(errs() << "IC: Old = " << *I << '\n'
13504 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013505
13506 // Everything uses the new instruction now.
13507 I->replaceAllUsesWith(Result);
13508
13509 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000013510 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000013511 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013512
13513 // Move the name to the new instruction first.
13514 Result->takeName(I);
13515
13516 // Insert the new instruction into the basic block...
13517 BasicBlock *InstParent = I->getParent();
13518 BasicBlock::iterator InsertPos = I;
13519
13520 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13521 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13522 ++InsertPos;
13523
13524 InstParent->getInstList().insert(InsertPos, Result);
13525
Chris Lattner3183fb62009-08-30 06:13:40 +000013526 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013527 } else {
13528#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013529 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13530 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013531#endif
13532
13533 // If the instruction was modified, it's possible that it is now dead.
13534 // if so, remove it.
13535 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000013536 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013537 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000013538 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000013539 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013540 }
13541 }
Chris Lattner21d79e22009-08-31 06:57:37 +000013542 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013543 }
13544 }
13545
Chris Lattner5119c702009-08-30 05:55:36 +000013546 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000013547 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013548}
13549
13550
13551bool InstCombiner::runOnFunction(Function &F) {
13552 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013553 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000013554 TD = getAnalysisIfAvailable<TargetData>();
13555
Chris Lattnerc7694852009-08-30 07:44:24 +000013556
13557 /// Builder - This is an IRBuilder that automatically inserts new
13558 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000013559 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000013560 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000013561 InstCombineIRInserter(Worklist));
13562 Builder = &TheBuilder;
13563
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013564 bool EverMadeChange = false;
13565
13566 // Iterate while there is work to do.
13567 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013568 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013569 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000013570
13571 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013572 return EverMadeChange;
13573}
13574
13575FunctionPass *llvm::createInstructionCombiningPass() {
13576 return new InstCombiner();
13577}