blob: 9033877b454cfc4e9e4903f7ee8d30b8504b14e9 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(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");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattner0e5f4992006-12-19 21:40:18 +000078namespace {
Chris Lattner873ff012009-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 Yasskin43069632009-10-08 00:12:24 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000097 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000098 }
Chris Lattner873ff012009-08-30 05:55:36 +000099 }
100
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
103 Add(I);
104 }
105
Chris Lattner67f7d542009-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 Lattner7a1e9242009-08-30 06:13:40 +0000120 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-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 Lattnere5ecdb52009-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 Lattner873ff012009-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 Lattner74381062009-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 Lattner3e8b6632009-09-02 06:11:42 +0000180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000182 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000183 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000184 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000185 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000186 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000187 InstCombineWorklist Worklist;
188
Chris Lattner74381062009-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 Lattnere2cc1ad2009-10-15 04:13:44 +0000191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000192 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000193
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000194 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000196
Owen Andersone922c022009-07-22 00:24:57 +0000197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000199
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000200 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000201 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000202
203 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000204
Chris Lattner97e52e42002-04-28 21:27:06 +0000205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000206 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000207 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000208 }
209
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000210 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000211
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
214 // Return Value:
215 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000216 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000217 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000218 //
Chris Lattner7e708292002-06-25 16:13:24 +0000219 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000220 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000225 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000232 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 Lattner29cd5ba2008-11-16 05:06:21 +0000237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000243 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *LHS,
257 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000260 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000261 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000262 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000263 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000264 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000265 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000266 Instruction *commonCastTransforms(CastInst &CI);
267 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000268 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000269 Instruction *visitTrunc(TruncInst &CI);
270 Instruction *visitZExt(ZExtInst &CI);
271 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000272 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000273 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000274 Instruction *visitFPToUI(FPToUIInst &FI);
275 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000276 Instruction *visitUIToFP(CastInst &CI);
277 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000278 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000279 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000280 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000281 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
282 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000283 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000284 Instruction *visitSelectInst(SelectInst &SI);
285 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000286 Instruction *visitCallInst(CallInst &CI);
287 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000288
289 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000290 Instruction *visitPHINode(PHINode &PN);
291 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000292 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000293 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000294 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000295 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000296 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000297 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000298 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000299 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000300 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000301 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000302
303 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000304 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000305
Chris Lattner9fe38862003-06-19 17:00:31 +0000306 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000307 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000308 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000309 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000310 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
311 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000312 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000313 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
314
Chris Lattner9fe38862003-06-19 17:00:31 +0000315
Chris Lattner28977af2004-04-05 01:30:19 +0000316 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000317 // InsertNewInstBefore - insert an instruction New before instruction Old
318 // in the program. Add the new instruction to the worklist.
319 //
Chris Lattner955f3312004-09-28 21:48:02 +0000320 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000321 assert(New && New->getParent() == 0 &&
322 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000323 BasicBlock *BB = Old.getParent();
324 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000325 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000326 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000327 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000328
Chris Lattner8b170942002-08-09 23:47:40 +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 Lattnere5ecdb52009-08-30 06:22:51 +0000336 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-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;
Chris Lattner8b170942002-08-09 23:47:40 +0000345 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000346
347 // 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 Hernandez83d63912009-09-18 22:35:49 +0000352 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000353
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000354 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000355 // Make sure that we reprocess all operands now that we reduced their
356 // use counts.
Chris Lattner3c4e38e2009-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 Lattner7a1e9242009-08-30 06:13:40 +0000362 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000363 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000364 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000365 return 0; // Don't do anything with FI
366 }
Chris Lattner173234a2008-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 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000380
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000381 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000382
Reid Spencere4d87aa2006-12-23 06:05:41 +0000383 /// SimplifyCommutative - This performs a few simplifications for
384 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000385 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000386
Chris Lattner886ab6c2009-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,
Reid Spencer8cb68342007-03-12 17:25:59 +0000393 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-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 Cheng388df622009-02-03 10:05:09 +0000401 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000403
Chris Lattner5d1704d2009-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 Lattner213cd612009-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);
Chris Lattner4e998b22004-09-29 05:07:12 +0000413
Chris Lattnerbac32862004-11-14 19:13:23 +0000414 // 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);
Chris Lattner7da52b22006-11-01 04:51:18 +0000418 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000419 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000420 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000421
Chris Lattner7da52b22006-11-01 04:51:18 +0000422
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000423 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
424 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000425
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000426 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000427 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000428 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000429 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000430 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000431 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000432 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000433 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000434 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000435
Chris Lattnerafe91a52006-06-15 19:07:26 +0000436
Reid Spencerc55b2432006-12-13 18:21:21 +0000437 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000438
Dan Gohman6de29f82009-06-15 22:12:54 +0000439 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000440 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000441 unsigned GetOrEnforceKnownAlignment(Value *V,
442 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000443
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000444 };
Chris Lattner873ff012009-08-30 05:55:36 +0000445} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000446
Dan Gohman844731a2008-05-13 00:00:25 +0000447char InstCombiner::ID = 0;
448static RegisterPass<InstCombiner>
449X("instcombine", "Combine redundant instructions");
450
Chris Lattner4f98c562003-03-10 21:43:22 +0000451// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000452// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000453static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000454 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000455 if (BinaryOperator::isNeg(V) ||
456 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000457 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000458 return 3;
459 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000460 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000461 if (isa<Argument>(V)) return 3;
462 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000463}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000464
Chris Lattnerc8802d22003-03-11 00:12:48 +0000465// isOnlyUse - Return true if this instruction will be deleted if we stop using
466// it.
467static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000468 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000469}
470
Chris Lattner4cb170c2004-02-23 06:38:22 +0000471// 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) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000474 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
475 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000476 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000477 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000478 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000479}
480
Chris Lattnerc22d4d12009-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 Kooijman7e6d9b92008-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.
Reid Spencer3da59db2006-11-27 01:05:10 +0000512static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-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 Kooijman7e6d9b92008-10-13 15:17:01 +0000519 }
Chris Lattnereed48272005-09-13 00:40:14 +0000520 return 0;
521}
522
Reid Spencer3da59db2006-11-27 01:05:10 +0000523/// This function is a wrapper around CastInst::isEliminableCastPair. It
524/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000525static 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 Gohmance9fe9f2009-07-21 23:21:54 +0000532
Reid Spencer3da59db2006-11-27 01:05:10 +0000533 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
534 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000535
Reid Spencer3da59db2006-11-27 01:05:10 +0000536 // Get the opcodes of the two Cast instructions
537 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
538 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000539
Chris Lattnera0e69692009-03-24 18:35:40 +0000540 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000541 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000542 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-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 Anderson1d0be152009-08-13 21:58:54 +0000546 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000547 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000548 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000549 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000550 Res = 0;
551
552 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +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.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000558static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
559 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000560 if (V->getType() == Ty || isa<Constant>(V)) return false;
561
Chris Lattner01575b72006-05-25 23:24:33 +0000562 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000563 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000564 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000565 return false;
566 return true;
567}
568
Chris Lattner4f98c562003-03-10 21:43:22 +0000569// SimplifyCommutative - This performs a few simplifications for commutative
570// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000571//
Chris Lattner4f98c562003-03-10 21:43:22 +0000572// 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//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576// 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))
Chris Lattner4f98c562003-03-10 21:43:22 +0000578//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000580 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000581 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000582 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000583
Chris Lattner4f98c562003-03-10 21:43:22 +0000584 if (!I.isAssociative()) return Changed;
585 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000586 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 Andersonbaf3c402009-07-29 18:55:55 +0000589 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000590 cast<Constant>(I.getOperand(1)),
591 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000592 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 Andersonbaf3c402009-07-29 18:55:55 +0000602 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000603 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000604 Op1->getOperand(0),
605 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000606 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607 I.setOperand(0, New);
608 I.setOperand(1, Folded);
609 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000610 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000611 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000612 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000613}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000614
Chris Lattner8d969642003-03-10 23:06:50 +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).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000617//
Dan Gohman186a6362009-08-12 16:04:34 +0000618static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000619 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000620 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000621
Chris Lattner0ce85802004-12-14 20:08:06 +0000622 // Constants can be considered to be negated values if they can be folded.
623 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000624 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000625
626 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000628 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000629
Chris Lattner8d969642003-03-10 23:06:50 +0000630 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000631}
632
Dan Gohmanae3a0be2009-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 Gohman186a6362009-08-12 16:04:34 +0000637static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000638 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-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 Andersonbaf3c402009-07-29 18:55:55 +0000643 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000644
645 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
646 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000647 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000648
649 return 0;
650}
651
Chris Lattner48b59ec2009-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 Cheng85def162009-10-26 03:51:32 +0000656 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-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 }
Chris Lattner8d969642003-03-10 23:06:50 +0000678
679 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000680 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000681 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000682 return 0;
683}
684
Chris Lattner48b59ec2009-10-26 15:40:07 +0000685
686
Chris Lattnerc8802d22003-03-11 00:12:48 +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
Chris Lattner50af16a2004-11-13 19:50:12 +0000689// non-constant operand of the multiply, and set CST to point to the multiplier.
690// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000691//
Dan Gohman186a6362009-08-12 16:04:34 +0000692static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000693 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000694 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000695 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000696 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000697 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000698 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000699 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000700 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000701 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000702 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000703 CST = ConstantInt::get(V->getType()->getContext(),
704 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000705 return I->getOperand(0);
706 }
707 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000708 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000709}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000710
Reid Spencer7177c3a2007-03-25 05:33:51 +0000711/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000712static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000713 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000714 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000715}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000716/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000717static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000718 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000719 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000720}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000721/// MultiplyOverflows - True if the multiply can not be expressed in an int
722/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000723static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-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}
Chris Lattner955f3312004-09-28 21:48:02 +0000743
Reid Spencere7816b52007-03-08 01:52:58 +0000744
Chris Lattner255d8912006-02-11 09:31:47 +0000745/// 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 Gohman186a6362009-08-12 16:04:34 +0000750 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +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 Gohman186a6362009-08-12 16:04:34 +0000765 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000766 return true;
767}
768
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000769// 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 Gohman1c8491e2009-04-25 17:12:48 +0000773static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000774 const APInt& KnownOne,
775 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-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.");
Reid Spencer2f549172007-03-25 04:26:16 +0000780 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000781
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000782 // 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 Gohman1c8491e2009-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);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000790 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000791}
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 Gohman1c8491e2009-04-25 17:12:48 +0000797static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000798 const APInt &KnownOne,
799 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000800 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
801 KnownZero.getBitWidth() == Min.getBitWidth() &&
802 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000803 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000804 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000805
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}
Chris Lattner255d8912006-02-11 09:31:47 +0000811
Chris Lattner886ab6c2009-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 Gohman6de29f82009-06-15 22:12:54 +0000816 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-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 Gohmane41a1152009-10-05 16:31:55 +0000837 U = NewVal;
Chris Lattner886ab6c2009-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
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +0000849/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-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) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000866 assert(V != 0 && "Null pointer of Value???");
867 assert(Depth <= 6 && "Limit Search Depth");
868 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-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 Gohman6de29f82009-06-15 22:12:54 +0000872 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
873 (!VTy->isIntOrIntVector() ||
874 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000875 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000876 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000877 "Value *V, DemandedMask, KnownZero and KnownOne "
878 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +0000883 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000884 }
Dan Gohman1c8491e2009-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 Lattner08d2cc72009-01-31 07:26:06 +0000892 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000893 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000894 if (DemandedMask == 0) { // Not demanding any bits from V.
895 if (isa<UndefValue>(V))
896 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000897 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000898 }
899
Chris Lattner4598c942009-01-31 08:24:16 +0000900 if (Depth == 6) // Limit search depth.
901 return 0;
902
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000903 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
904 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
905
Dan Gohman1c8491e2009-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 Lattner4598c942009-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 Lattnerd1b5e3f2009-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 Andersona7235ea2009-07-31 20:28:14 +0000939 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-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 Lattner4598c942009-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
Reid Spencer8cb68342007-03-12 17:25:59 +0000983 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000984 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000986 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 case Instruction::And:
988 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
990 RHSKnownZero, RHSKnownOne, Depth+1) ||
991 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000992 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-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?");
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001001 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001002 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1003 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001005
1006 // If all of the demanded bits in the inputs are known zeros, return zero.
1007 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001008 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001009
1010 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001011 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001021 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1022 RHSKnownZero, RHSKnownOne, Depth+1) ||
1023 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-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?");
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001033 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001034 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1035 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001042 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1044 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
1047 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001057 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1058 RHSKnownZero, RHSKnownOne, Depth+1) ||
1059 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001060 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-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?");
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001068 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001070 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner95afdfe2009-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 }
Reid Spencer8cb68342007-03-12 17:25:59 +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 Gohman43ee5f72009-08-03 22:07:33 +00001096 Constant *AndC = Constant::getIntegerValue(VTy,
1097 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001098 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001099 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +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 Gohman186a6362009-08-12 16:04:34 +00001106 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108
Chris Lattnerd0883142009-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
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 RHSKnownZero = KnownZeroOut;
1137 RHSKnownOne = KnownOneOut;
1138 break;
1139 }
1140 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001141 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1) ||
1143 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001144 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-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?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001148
1149 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001150 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1151 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001152 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +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 Gohman6de29f82009-06-15 22:12:54 +00001159 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001160 DemandedMask.zext(truncBf);
1161 RHSKnownZero.zext(truncBf);
1162 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001164 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001165 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 DemandedMask.trunc(BitWidth);
1167 RHSKnownZero.trunc(BitWidth);
1168 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001170 break;
1171 }
1172 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001173 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-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 Lattner886ab6c2009-01-31 08:15:18 +00001189 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return I;
1192 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 break;
1194 case Instruction::ZExt: {
1195 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001196 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001197
Zhou Shengd48653a2007-03-29 04:45:55 +00001198 DemandedMask.trunc(SrcBitWidth);
1199 RHSKnownZero.trunc(SrcBitWidth);
1200 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001201 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001202 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001203 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 DemandedMask.zext(BitWidth);
1205 RHSKnownZero.zext(BitWidth);
1206 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001207 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001208 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001209 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 break;
1211 }
1212 case Instruction::SExt: {
1213 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001214 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001215
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001217 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001220 // If any of the sign extended bits are demanded, we know that the sign
1221 // bit is demanded.
1222 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001223 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001224
Zhou Shengd48653a2007-03-29 04:45:55 +00001225 InputDemandedBits.trunc(SrcBitWidth);
1226 RHSKnownZero.trunc(SrcBitWidth);
1227 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001229 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001230 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 InputDemandedBits.zext(BitWidth);
1232 RHSKnownZero.zext(BitWidth);
1233 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001234 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001241 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1244 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001245 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 }
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 Lattner886ab6c2009-01-31 08:15:18 +00001254 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +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.
Zhou Sheng01542f32007-03-29 02:26:30 +00001266 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001267
1268 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001272
1273 // If the RHS of the add has bits set that can't affect the input, reduce
1274 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001275 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001276 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +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 Greif7cbd8a32008-05-16 19:29:10 +00001285 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001287 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +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 Lattner886ab6c2009-01-31 08:15:18 +00001299 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001300 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
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.
Zhou Sheng01542f32007-03-29 02:26:30 +00001315 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 // Right fill the mask of bits for this ADD to demand the most
1317 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001318 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1320 LHSKnownZero, LHSKnownOne, Depth+1) ||
1321 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +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.
Zhou Sheng01542f32007-03-29 02:26:30 +00001331 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 // Right fill the mask of bits for this SUB to demand the most
1333 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001334 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001335 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1337 LHSKnownZero, LHSKnownOne, Depth+1) ||
1338 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001341 }
Dan Gohman23e8b712008-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);
Reid Spencer8cb68342007-03-12 17:25:59 +00001345 break;
1346 case Instruction::Shl:
1347 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001348 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001349 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 return I;
1353 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 RHSKnownZero <<= ShiftAmt;
1355 RHSKnownOne <<= ShiftAmt;
1356 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001357 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001358 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001359 }
1360 break;
1361 case Instruction::LShr:
1362 // For a logical shift right
1363 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001364 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001365
Reid Spencer8cb68342007-03-12 17:25:59 +00001366 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001367 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001368 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001369 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001370 return I;
1371 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1373 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001374 if (ShiftAmt) {
1375 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001376 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001377 RHSKnownZero |= HighBits; // high bits known zero.
1378 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 }
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 Lattner886ab6c2009-01-31 08:15:18 +00001388 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001389 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001390 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001391 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001392
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 Lattner886ab6c2009-01-31 08:15:18 +00001396 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001397
1398 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001399 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001400
Reid Spencer8cb68342007-03-12 17:25:59 +00001401 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001402 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001403 // 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 Lattner886ab6c2009-01-31 08:15:18 +00001407 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001409 return I;
1410 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001412 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001413 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 Shengcc419402008-06-06 08:32:05 +00001423 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001424 (HighBits & ~DemandedMask) == HighBits) {
1425 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001426 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001427 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001428 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001429 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1430 RHSKnownOne |= HighBits;
1431 }
1432 }
1433 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001434 case Instruction::SRem:
1435 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001436 APInt RA = Rem->getValue().abs();
1437 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001438 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001439 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001440
Nick Lewycky8e394322008-11-02 02:41:50 +00001441 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001442 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001443 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001444 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001445 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001446
1447 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1448 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001449
1450 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001451
Chris Lattner886ab6c2009-01-31 08:15:18 +00001452 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001453 }
1454 }
1455 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001456 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001457 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1458 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001459 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1460 KnownZero2, KnownOne2, Depth+1) ||
1461 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001462 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001463 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001464
Chris Lattner455e9ab2009-01-21 18:09:24 +00001465 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001466 Leaders = std::max(Leaders,
1467 KnownZero2.countLeadingOnes());
1468 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001469 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001470 }
Chris Lattner0521e3c2008-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 Andersoneed707b2009-07-24 23:12:02 +00001496 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001497 else
1498 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001499 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001500 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001501 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-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 Lattner6c3bfba2008-06-18 18:11:55 +00001509 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001510 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001511 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001512
1513 // If the client is only demanding bits that we know, return the known
1514 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001515 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1516 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001517 return false;
1518}
1519
Chris Lattner867b99f2006-10-05 06:55:50 +00001520
Mon P Wangaeb06d22008-11-10 04:46:22 +00001521/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001522/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +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 Cheng388df622009-02-03 10:05:09 +00001529Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1530 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001532 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001533 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001534 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +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 Anderson9e9a0d52009-07-30 23:03:37 +00001542 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001544
Chris Lattner867b99f2006-10-05 06:55:50 +00001545 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001546 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1547 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001548 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001549
1550 std::vector<Constant*> Elts;
1551 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001552 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001553 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001554 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001555 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1556 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001557 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 } else { // Otherwise, defined.
1559 Elts.push_back(CP->getOperand(i));
1560 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001561
Chris Lattner867b99f2006-10-05 06:55:50 +00001562 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001563 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001564 return NewCP != CP ? NewCP : 0;
1565 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001566 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 // set to undef.
Mon P Wange0b436a2008-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
Reid Spencer9d6565a2007-02-15 02:26:10 +00001574 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001575 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001576 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001577 std::vector<Constant*> Elts;
Evan Cheng388df622009-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 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001582 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001583 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001584 }
1585
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 // Limit search depth.
1587 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001588 return 0;
Dan Gohman488fbfc2008-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)
Chris Lattner867b99f2006-10-05 06:55:50 +00001598 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001599 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600
1601 // Conservatively assume that all elements are needed.
1602 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001603 }
1604
1605 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001606 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001607
1608 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001609 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +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.
Reid Spencerb83eb642006-10-20 07:07:24 +00001617 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001618 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.
Reid Spencerb83eb642006-10-20 07:07:24 +00001629 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001630 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1631 Worklist.Add(I);
1632 return I->getOperand(0);
1633 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001634
1635 // Otherwise, the element inserted overwrites whatever was there, so the
1636 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001637 APInt DemandedElts2 = DemandedElts;
1638 DemandedElts2.clear(IdxNo);
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001640 UndefElts, Depth+1);
1641 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1642
1643 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001644 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001645 break;
1646 }
1647 case Instruction::ShuffleVector: {
1648 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001649 uint64_t LHSVWidth =
1650 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001651 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001653 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001654 unsigned MaskVal = Shuffle->getMaskValue(i);
1655 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001656 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001658 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001659 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001660 else
Evan Cheng388df622009-02-03 10:05:09 +00001661 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001662 }
1663 }
1664 }
1665
Nate Begeman7b254672009-02-11 22:36:25 +00001666 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001667 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001668 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001669 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670
Nate Begeman7b254672009-02-11 22:36:25 +00001671 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-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 Gohmancb893092008-09-10 01:09:32 +00001679 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001680 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001681 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001682 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001683 NewUndefElts = true;
1684 UndefElts.set(i);
1685 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001686 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001687 if (UndefElts3[MaskVal - LHSVWidth]) {
1688 NewUndefElts = true;
1689 UndefElts.set(i);
1690 }
Dan Gohman488fbfc2008-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 Cheng388df622009-02-03 10:05:09 +00001698 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001699 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001700 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001701 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001702 Shuffle->getMaskValue(i)));
1703 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001704 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001705 MadeChange = true;
1706 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001707 break;
1708 }
Chris Lattner69878332007-04-14 22:29:23 +00001709 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001710 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001711 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1712 if (!VTy) break;
1713 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001714 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001715 unsigned Ratio;
1716
1717 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001718 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001719 // 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 Cheng388df622009-02-03 10:05:09 +00001731 if (DemandedElts[OutIdx])
1732 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +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 Cheng388df622009-02-03 10:05:09 +00001743 if (DemandedElts[InIdx/Ratio])
1744 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001745 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001746
Chris Lattner69878332007-04-14 22:29:23 +00001747 // 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) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001757 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +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 Cheng388df622009-02-03 10:05:09 +00001762 if (UndefElts2[OutIdx/Ratio])
1763 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001764 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001765 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +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 Cheng388df622009-02-03 10:05:09 +00001771 if (!UndefElts2[InIdx]) // Not undef?
1772 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001773 }
1774 break;
1775 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001776 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 Christophera3500da2009-07-25 02:28:41 +00001831 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001832 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001833 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001834 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001835
1836 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001837 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001838 case Intrinsic::x86_sse_sub_ss:
1839 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001840 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001841 II->getName()), *II);
1842 break;
1843 case Intrinsic::x86_sse_mul_ss:
1844 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001845 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001846 II->getName()), *II);
1847 break;
1848 }
1849
1850 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001851 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001852 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001853 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001854 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +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 Gohman45b4e482008-05-19 22:14:15 +00001870
Chris Lattner564a7272003-08-13 19:01:45 +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 Gohman186a6362009-08-12 16:04:34 +00001880static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +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);
Chris Lattnerfd059242003-10-15 16:48:29 +00001890 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001891 // 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) {
Chris Lattner564a7272003-08-13 19:01:45 +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);
Chris Lattner65725312004-04-16 18:08:07 +00001912 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001913 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001914 return 0;
1915 }
Chris Lattner65725312004-04-16 18:08:07 +00001916 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001917 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001918 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001919 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001920 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001921
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));
Chris Lattner65725312004-04-16 18:08:07 +00001926 // Move the instruction to immediately before the chain we are
1927 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001928 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001929 ARI = NextLHSI;
1930
Chris Lattner564a7272003-08-13 19:01:45 +00001931 Value *NextOp = NextLHSI->getOperand(1);
1932 NextLHSI->setOperand(1, ExtraOperand);
1933 TmpLHSI = NextLHSI;
1934 ExtraOperand = NextOp;
1935 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001936
Chris Lattner564a7272003-08-13 19:01:45 +00001937 // Now that the instructions are reassociated, have the functor perform
1938 // the transformation...
1939 return F.apply(Root);
1940 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001941
Chris Lattner564a7272003-08-13 19:01:45 +00001942 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1943 }
1944 return 0;
1945}
1946
Dan Gohman844731a2008-05-13 00:00:25 +00001947namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001948
Nick Lewycky02d639f2008-05-23 04:34:58 +00001949// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001950struct AddRHS {
1951 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001952 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001953 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1954 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001955 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001956 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +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 Gohman4ae51262009-08-12 16:23:25 +00001964 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001965 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001966 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001967 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001968 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001969 }
1970 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001971 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001972 }
1973};
1974
Dan Gohman844731a2008-05-13 00:00:25 +00001975}
1976
Chris Lattner6e7ba452005-01-01 16:22:27 +00001977static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001978 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001979 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001980 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001981
Chris Lattner2eefe512004-04-09 19:05:30 +00001982 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001983 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1984 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001985
Chris Lattner2eefe512004-04-09 19:05:30 +00001986 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1987 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001988 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1989 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001990 }
1991
1992 Value *Op0 = SO, *Op1 = ConstOperand;
1993 if (!ConstIsRHS)
1994 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001995
Chris Lattner6e7ba452005-01-01 16:22:27 +00001996 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-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!");
Chris Lattner6e7ba452005-01-01 16:22:27 +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)) {
Chris Lattner956db272005-04-21 05:43:13 +00002020 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002021 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002022
Chris Lattner6e7ba452005-01-01 16:22:27 +00002023 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2024 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2025
Gabor Greif051a9502008-04-06 20:25:17 +00002026 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2027 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002028 }
2029 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002030}
2031
Chris Lattner4e998b22004-09-29 05:07:12 +00002032
Chris Lattner5d1704d2009-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 Lattner213cd612009-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;
Chris Lattner4e998b22004-09-29 05:07:12 +00002043 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002044 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-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 Lattner5d1704d2009-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 Lattnerc6df8f42009-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.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002057 BasicBlock *NonConstBB = 0;
2058 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002059 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2060 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002061 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002062 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002063 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 Lattner213cd612009-09-27 20:46:36 +00002075 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002076 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2077 if (!BI || !BI->isUnconditional()) return 0;
2078 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002079
2080 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002081 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002082 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002083 InsertNewInstBefore(NewPN, *PN);
2084 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002085
2086 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-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 Lattnerc6df8f42009-09-27 20:18:49 +00002090 Value *TrueV = SI->getTrueValue();
2091 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002092 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002093 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002094 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002095 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2096 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002097 Value *InV = 0;
2098 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002099 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002100 } else {
2101 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002102 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2103 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002104 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002105 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002106 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002107 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002108 }
2109 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002110 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002111 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002112 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002113 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002114 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002115 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002116 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002117 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002118 } else {
2119 assert(PN->getIncomingBlock(i) == NonConstBB);
2120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002121 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002122 PN->getIncomingValue(i), C, "phitmp",
2123 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002124 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002125 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002126 CI->getPredicate(),
2127 PN->getIncomingValue(i), C, "phitmp",
2128 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002129 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002130 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002131
2132 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002133 }
2134 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002135 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002136 } else {
2137 CastInst *CI = cast<CastInst>(&I);
2138 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002139 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002140 Value *InV;
2141 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002142 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002143 } else {
2144 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002145 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002146 I.getType(), "phitmp",
2147 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002148 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002149 }
2150 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002151 }
2152 }
2153 return ReplaceInstUsesWith(I, NewPN);
2154}
2155
Chris Lattner2454a2e2008-01-29 06:52:45 +00002156
Chris Lattner3d28b1b2008-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 Lattner8aee8ef2009-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 Lattner3d28b1b2008-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 Lattner2454a2e2008-01-29 06:52:45 +00002183
Chris Lattner7e708292002-06-25 16:13:24 +00002184Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002185 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002186 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002187
Chris Lattner8aee8ef2009-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
Chris Lattner66331a42004-04-10 22:01:55 +00002193 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002194 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002195 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002196 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002197 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002198 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002199 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002200
2201 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2202 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002203 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002204 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002205
Eli Friedman709b33d2009-07-13 22:27:52 +00002206 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002207 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002208 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002209 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002210 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002211
2212 if (isa<PHINode>(LHS))
2213 if (Instruction *NV = FoldOpIntoPhi(I))
2214 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002215
Chris Lattner4f637d42006-01-06 17:59:59 +00002216 ConstantInt *XorRHS = 0;
2217 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002218 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002219 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002220 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002221 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002222
Zhou Sheng4351c642007-04-02 08:20:41 +00002223 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002224 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2225 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002226 do {
2227 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002228 // 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.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002230 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2231 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002232 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002233 if (!MaskedValueIsZero(XorLHS,
2234 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002235 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002236 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002237 }
2238 }
2239 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002240 C0080Val = APIntOps::lshr(C0080Val, Size);
2241 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2242 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002243
Reid Spencer35c38852007-03-28 01:36:16 +00002244 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-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.
Reid Spencer35c38852007-03-28 01:36:16 +00002248 const Type *MiddleType = 0;
2249 switch (Size) {
2250 default: break;
Owen Anderson1d0be152009-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;
Reid Spencer35c38852007-03-28 01:36:16 +00002254 }
2255 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002256 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002257 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002258 }
2259 }
Chris Lattner66331a42004-04-10 22:01:55 +00002260 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002261
Owen Anderson1d0be152009-08-13 21:58:54 +00002262 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002263 return BinaryOperator::CreateXor(LHS, RHS);
2264
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002265 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002266 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002267 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002268 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +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 }
Robert Bocchino71698282004-07-27 21:02:21 +00002280 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002281
Chris Lattner5c4afb92002-05-08 22:46:53 +00002282 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002283 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002284 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002285 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002286 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002287 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002288 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002289 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002290 }
2291
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002292 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002293 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002294
2295 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002296 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002297 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002298 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002299
Misha Brukmanfd939082005-04-21 23:48:37 +00002300
Chris Lattner50af16a2004-11-13 19:50:12 +00002301 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002302 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002303 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002304 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002305
2306 // X*C1 + X*C2 --> X * (C1+C2)
2307 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002308 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002309 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002310 }
2311
2312 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002313 if (dyn_castFoldableMul(RHS, C2) == LHS)
2314 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002315
Chris Lattnere617c9e2007-01-05 02:17:46 +00002316 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002317 if (dyn_castNotVal(LHS) == RHS ||
2318 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002319 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002320
Chris Lattnerad3448c2003-02-18 19:57:07 +00002321
Chris Lattner564a7272003-08-13 19:01:45 +00002322 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002323 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2324 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002325 return R;
Chris Lattner5e0d7182008-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 Lattner9d60ba92008-05-19 20:03:53 +00002339 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002340 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002341 }
2342 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002343
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002344 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002345 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002346 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-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 Lewyckyb6eabff2008-02-03 07:42:09 +00002349 if (W != Y) {
2350 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002351 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002352 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002353 std::swap(W, X);
2354 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002355 std::swap(Y, Z);
2356 std::swap(W, X);
2357 }
2358 }
2359
2360 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002361 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002362 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002363 }
2364 }
2365 }
2366
Chris Lattner6b032052003-10-02 15:11:26 +00002367 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002368 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002369 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002370 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002371
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002372 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002373 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002374 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002375 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +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.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002379 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002380
2381 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002382 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002383
2384 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002385 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002386
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002387 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2388 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002389 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002391 }
2392 }
2393 }
2394
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002395 // Try to fold constant add into select arguments.
2396 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002397 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002398 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002399 }
2400
Chris Lattner42790482007-12-20 01:56:58 +00002401 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002402 {
2403 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002404 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002405 if (!SI) {
2406 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002407 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002408 }
Chris Lattner42790482007-12-20 01:56:58 +00002409 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002410 Value *TV = SI->getTrueValue();
2411 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002412 Value *N;
Christopher Lamb30f017a2007-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 Gohman4ae51262009-08-12 16:23:25 +00002416 if (match(FV, m_Zero()) &&
2417 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002418 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002419 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002420 if (match(TV, m_Zero()) &&
2421 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002422 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002423 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002424 }
2425 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002426
Chris Lattner3d28b1b2008-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 Andersonbaf3c402009-07-29 18:55:55 +00002433 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002434 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002435 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002436 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002438 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2439 CI, "addconv");
Chris Lattner3d28b1b2008-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 Gohmanfe359552009-10-26 22:14:22 +00002454 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2455 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002456 return new SExtInst(NewAdd, I.getType());
2457 }
2458 }
2459 }
Dan Gohmanae3a0be2009-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 Anderson6f83c9c2009-07-27 20:59:43 +00002471 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-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 Gohman186a6362009-08-12 16:04:34 +00002483 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002484 return BinaryOperator::CreateFSub(RHS, LHSV);
2485
2486 // A + -B --> A - B
2487 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002488 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-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 Lattner3d28b1b2008-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 Andersonbaf3c402009-07-29 18:55:55 +00002506 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002507 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002508 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002509 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2510 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002511 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2512 CI, "addconv");
Chris Lattner3d28b1b2008-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 Gohmanfe359552009-10-26 22:14:22 +00002527 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002528 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002529 return new SIToFPInst(NewAdd, I.getType());
2530 }
2531 }
2532 }
2533
Chris Lattner7e708292002-06-25 16:13:24 +00002534 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002535}
2536
Chris Lattner092543c2009-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
Chris Lattner7e708292002-06-25 16:13:24 +00002734Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002736
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002737 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002738 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002739
Chris Lattner3bf68152009-12-21 04:04:05 +00002740 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2741 if (Value *V = dyn_castNegVal(Op1)) {
2742 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2743 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2744 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2745 return Res;
2746 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002747
Chris Lattnere87597f2004-10-16 18:11:37 +00002748 if (isa<UndefValue>(Op0))
2749 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2750 if (isa<UndefValue>(Op1))
2751 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002752 if (I.getType() == Type::getInt1Ty(*Context))
2753 return BinaryOperator::CreateXor(Op0, Op1);
2754
Chris Lattnerd65460f2003-11-05 01:06:05 +00002755 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002756 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002757 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002758 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002759
Chris Lattnerd65460f2003-11-05 01:06:05 +00002760 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002761 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002762 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002763 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002764
Chris Lattner76b7a062007-01-15 07:02:54 +00002765 // -(X >>u 31) -> (X >>s 31)
2766 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002767 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002768 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002769 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002770 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002771 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002772 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002773 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002774 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002775 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002776 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002777 }
2778 }
Chris Lattner092543c2009-11-04 08:05:20 +00002779 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002780 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2781 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002782 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002783 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002784 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002786 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002787 }
2788 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002789 }
2790 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002791 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002792
2793 // Try to fold constant sub into select arguments.
2794 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002795 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002796 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002797
2798 // C - zext(bool) -> bool ? C - 1 : C
2799 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002800 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002801 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002802 }
2803
Chris Lattner43d84d62005-04-07 16:15:25 +00002804 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002805 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002806 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002807 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002808 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002809 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002810 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002811 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002812 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2813 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2814 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002815 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002816 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002817 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002818 }
2819
Chris Lattnerfd059242003-10-15 16:48:29 +00002820 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002821 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2822 // is not used by anyone else...
2823 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002824 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002825 // Swap the two operands of the subexpr...
2826 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2827 Op1I->setOperand(0, IIOp1);
2828 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002829
Chris Lattnera2881962003-02-18 19:28:33 +00002830 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002831 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002832 }
2833
2834 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2835 //
2836 if (Op1I->getOpcode() == Instruction::And &&
2837 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2838 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2839
Chris Lattner74381062009-08-30 07:44:24 +00002840 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002841 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002842 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002843
Reid Spencerac5209e2006-10-16 23:08:08 +00002844 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002845 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002846 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002847 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002848 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002849 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002850 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002851
Chris Lattnerad3448c2003-02-18 19:57:07 +00002852 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002853 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002854 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002855 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002856 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002857 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002858 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002859 }
Chris Lattner40371712002-05-09 01:29:19 +00002860 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002861 }
Chris Lattnera2881962003-02-18 19:28:33 +00002862
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002863 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2864 if (Op0I->getOpcode() == Instruction::Add) {
2865 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2866 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2867 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2868 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2869 } else if (Op0I->getOpcode() == Instruction::Sub) {
2870 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002871 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002872 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002873 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002874 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002875
Chris Lattner50af16a2004-11-13 19:50:12 +00002876 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002877 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002878 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002879 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002880
Chris Lattner50af16a2004-11-13 19:50:12 +00002881 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002882 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002883 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002884 }
Chris Lattner092543c2009-11-04 08:05:20 +00002885
2886 // Optimize pointer differences into the same array into a size. Consider:
2887 // &A[10] - &A[0]: we should compile this to "10".
2888 if (TD) {
2889 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2890 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2891 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2892 RHS->getOperand(0),
2893 I.getType()))
2894 return ReplaceInstUsesWith(I, Res);
2895
2896 // trunc(p)-trunc(q) -> trunc(p-q)
2897 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2898 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2899 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2900 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2901 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2902 RHS->getOperand(0),
2903 I.getType()))
2904 return ReplaceInstUsesWith(I, Res);
2905 }
2906
Chris Lattner3f5b8772002-05-06 16:14:14 +00002907 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002908}
2909
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002910Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2911 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912
2913 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002914 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002915 return BinaryOperator::CreateFAdd(Op0, V);
2916
2917 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2918 if (Op1I->getOpcode() == Instruction::FAdd) {
2919 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002920 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002921 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002922 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002923 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002924 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002925 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926 }
2927
2928 return 0;
2929}
2930
Chris Lattnera0141b92007-07-15 20:42:37 +00002931/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2932/// comparison only checks the sign bit. If it only checks the sign bit, set
2933/// TrueIfSigned if the result of the comparison is true when the input value is
2934/// signed.
2935static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2936 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002937 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002938 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2939 TrueIfSigned = true;
2940 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002941 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2942 TrueIfSigned = true;
2943 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002944 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2945 TrueIfSigned = false;
2946 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002947 case ICmpInst::ICMP_UGT:
2948 // True if LHS u> RHS and RHS == high-bit-mask - 1
2949 TrueIfSigned = true;
2950 return RHS->getValue() ==
2951 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2952 case ICmpInst::ICMP_UGE:
2953 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2954 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002955 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002956 default:
2957 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002958 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002959}
2960
Chris Lattner7e708292002-06-25 16:13:24 +00002961Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002962 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002964
Chris Lattnera2498472009-10-11 21:36:10 +00002965 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002967
Chris Lattner8af304a2009-10-11 07:53:15 +00002968 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002969 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2970 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002971
2972 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002973 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002974 if (SI->getOpcode() == Instruction::Shl)
2975 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002976 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002977 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002978
Zhou Sheng843f07672007-04-19 05:39:12 +00002979 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002980 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002981 if (CI->equalsInt(1)) // X * 1 == X
2982 return ReplaceInstUsesWith(I, Op0);
2983 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002984 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002985
Zhou Sheng97b52c22007-03-29 01:57:21 +00002986 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002987 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002988 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002989 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002990 }
Chris Lattnera2498472009-10-11 21:36:10 +00002991 } else if (isa<VectorType>(Op1C->getType())) {
2992 if (Op1C->isNullValue())
2993 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002994
Chris Lattnera2498472009-10-11 21:36:10 +00002995 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002996 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002997 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002998
2999 // As above, vector X*splat(1.0) -> X in all defined cases.
3000 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003001 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3002 if (CI->equalsInt(1))
3003 return ReplaceInstUsesWith(I, Op0);
3004 }
3005 }
Chris Lattnera2881962003-02-18 19:28:33 +00003006 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003007
3008 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3009 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003010 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003011 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003012 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3013 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003014 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003015
3016 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003017
3018 // Try to fold constant mul into select arguments.
3019 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003020 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003021 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003022
3023 if (isa<PHINode>(Op0))
3024 if (Instruction *NV = FoldOpIntoPhi(I))
3025 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003026 }
3027
Dan Gohman186a6362009-08-12 16:04:34 +00003028 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003029 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003031
Nick Lewycky0c730792008-11-21 07:33:58 +00003032 // (X / Y) * Y = X - (X % Y)
3033 // (X / Y) * -Y = (X % Y) - X
3034 {
Chris Lattnera2498472009-10-11 21:36:10 +00003035 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003036 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3037 if (!BO ||
3038 (BO->getOpcode() != Instruction::UDiv &&
3039 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003040 Op1C = Op0;
3041 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003042 }
Chris Lattnera2498472009-10-11 21:36:10 +00003043 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003044 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003045 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003046 (BO->getOpcode() == Instruction::UDiv ||
3047 BO->getOpcode() == Instruction::SDiv)) {
3048 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3049
Dan Gohmanfa94b942009-08-12 16:33:09 +00003050 // If the division is exact, X % Y is zero.
3051 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3052 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003053 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003054 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003055 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003056 }
3057
Chris Lattner74381062009-08-30 07:44:24 +00003058 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003059 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003060 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003061 else
Chris Lattner74381062009-08-30 07:44:24 +00003062 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003063 Rem->takeName(BO);
3064
Chris Lattnera2498472009-10-11 21:36:10 +00003065 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003066 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003067 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003068 }
3069 }
3070
Chris Lattner8af304a2009-10-11 07:53:15 +00003071 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003072 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003073 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003074
Chris Lattner8af304a2009-10-11 07:53:15 +00003075 // X*(1 << Y) --> X << Y
3076 // (1 << Y)*X --> X << Y
3077 {
3078 Value *Y;
3079 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003080 return BinaryOperator::CreateShl(Op1, Y);
3081 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003082 return BinaryOperator::CreateShl(Op0, Y);
3083 }
3084
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003085 // If one of the operands of the multiply is a cast from a boolean value, then
3086 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003087 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3088 if (!isa<VectorType>(I.getType())) {
3089 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003090 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003091
Chris Lattnerd2c58362009-10-11 21:29:45 +00003092 Value *BoolCast = 0, *OtherOp = 0;
3093 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003094 BoolCast = Op0, OtherOp = Op1;
3095 else if (MaskedValueIsZero(Op1, Negative2))
3096 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003097
Chris Lattner0036e3a2009-10-11 21:22:21 +00003098 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003099 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3100 BoolCast, "tmp");
3101 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003102 }
3103 }
3104
Chris Lattner7e708292002-06-25 16:13:24 +00003105 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003106}
3107
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003108Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3109 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003111
3112 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003113 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3114 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003115 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3116 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3117 if (Op1F->isExactlyValue(1.0))
3118 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003119 } else if (isa<VectorType>(Op1C->getType())) {
3120 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003121 // As above, vector X*splat(1.0) -> X in all defined cases.
3122 if (Constant *Splat = Op1V->getSplatValue()) {
3123 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3124 if (F->isExactlyValue(1.0))
3125 return ReplaceInstUsesWith(I, Op0);
3126 }
3127 }
3128 }
3129
3130 // Try to fold constant mul into select arguments.
3131 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3132 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3133 return R;
3134
3135 if (isa<PHINode>(Op0))
3136 if (Instruction *NV = FoldOpIntoPhi(I))
3137 return NV;
3138 }
3139
Dan Gohman186a6362009-08-12 16:04:34 +00003140 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003141 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003142 return BinaryOperator::CreateFMul(Op0v, Op1v);
3143
3144 return Changed ? &I : 0;
3145}
3146
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003147/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3148/// instruction.
3149bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3150 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3151
3152 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3153 int NonNullOperand = -1;
3154 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3155 if (ST->isNullValue())
3156 NonNullOperand = 2;
3157 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3158 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3159 if (ST->isNullValue())
3160 NonNullOperand = 1;
3161
3162 if (NonNullOperand == -1)
3163 return false;
3164
3165 Value *SelectCond = SI->getOperand(0);
3166
3167 // Change the div/rem to use 'Y' instead of the select.
3168 I.setOperand(1, SI->getOperand(NonNullOperand));
3169
3170 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3171 // problem. However, the select, or the condition of the select may have
3172 // multiple uses. Based on our knowledge that the operand must be non-zero,
3173 // propagate the known value for the select into other uses of it, and
3174 // propagate a known value of the condition into its other users.
3175
3176 // If the select and condition only have a single use, don't bother with this,
3177 // early exit.
3178 if (SI->use_empty() && SelectCond->hasOneUse())
3179 return true;
3180
3181 // Scan the current block backward, looking for other uses of SI.
3182 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3183
3184 while (BBI != BBFront) {
3185 --BBI;
3186 // If we found a call to a function, we can't assume it will return, so
3187 // information from below it cannot be propagated above it.
3188 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3189 break;
3190
3191 // Replace uses of the select or its condition with the known values.
3192 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3193 I != E; ++I) {
3194 if (*I == SI) {
3195 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003196 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003197 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003198 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3199 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003200 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003201 }
3202 }
3203
3204 // If we past the instruction, quit looking for it.
3205 if (&*BBI == SI)
3206 SI = 0;
3207 if (&*BBI == SelectCond)
3208 SelectCond = 0;
3209
3210 // If we ran out of things to eliminate, break out of the loop.
3211 if (SelectCond == 0 && SI == 0)
3212 break;
3213
3214 }
3215 return true;
3216}
3217
3218
Reid Spencer1628cec2006-10-26 06:15:43 +00003219/// This function implements the transforms on div instructions that work
3220/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3221/// used by the visitors to those instructions.
3222/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003223Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003224 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003225
Chris Lattner50b2ca42008-02-19 06:12:18 +00003226 // undef / X -> 0 for integer.
3227 // undef / X -> undef for FP (the undef could be a snan).
3228 if (isa<UndefValue>(Op0)) {
3229 if (Op0->getType()->isFPOrFPVector())
3230 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003231 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003232 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003233
3234 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003235 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003236 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003237
Reid Spencer1628cec2006-10-26 06:15:43 +00003238 return 0;
3239}
Misha Brukmanfd939082005-04-21 23:48:37 +00003240
Reid Spencer1628cec2006-10-26 06:15:43 +00003241/// This function implements the transforms common to both integer division
3242/// instructions (udiv and sdiv). It is called by the visitors to those integer
3243/// division instructions.
3244/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003245Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3247
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003248 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003249 if (Op0 == Op1) {
3250 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003251 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003252 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003253 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003254 }
3255
Owen Andersoneed707b2009-07-24 23:12:02 +00003256 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003257 return ReplaceInstUsesWith(I, CI);
3258 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003259
Reid Spencer1628cec2006-10-26 06:15:43 +00003260 if (Instruction *Common = commonDivTransforms(I))
3261 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003262
3263 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3264 // This does not apply for fdiv.
3265 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3266 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003267
3268 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3269 // div X, 1 == X
3270 if (RHS->equalsInt(1))
3271 return ReplaceInstUsesWith(I, Op0);
3272
3273 // (X / C1) / C2 -> X / (C1*C2)
3274 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3275 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3276 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003277 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003278 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003279 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003280 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003281 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003282 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003283 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003284
Reid Spencerbca0e382007-03-23 20:05:17 +00003285 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003286 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3287 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3288 return R;
3289 if (isa<PHINode>(Op0))
3290 if (Instruction *NV = FoldOpIntoPhi(I))
3291 return NV;
3292 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003293 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003294
Chris Lattnera2881962003-02-18 19:28:33 +00003295 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003296 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003297 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003298 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003299
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003300 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003301 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003302 return ReplaceInstUsesWith(I, Op0);
3303
Nick Lewycky895f0852008-11-27 20:21:08 +00003304 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3305 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3306 // div X, 1 == X
3307 if (X->isOne())
3308 return ReplaceInstUsesWith(I, Op0);
3309 }
3310
Reid Spencer1628cec2006-10-26 06:15:43 +00003311 return 0;
3312}
3313
3314Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3315 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3316
3317 // Handle the integer div common cases
3318 if (Instruction *Common = commonIDivTransforms(I))
3319 return Common;
3320
Reid Spencer1628cec2006-10-26 06:15:43 +00003321 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003322 // X udiv C^2 -> X >> C
3323 // Check to see if this is an unsigned division with an exact power of 2,
3324 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003325 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003326 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003327 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003328
3329 // X udiv C, where C >= signbit
3330 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003331 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003332 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003333 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003334 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003335 }
3336
3337 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003338 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003339 if (RHSI->getOpcode() == Instruction::Shl &&
3340 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003341 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003342 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003343 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003344 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003345 if (uint32_t C2 = C1.logBase2())
3346 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003347 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003348 }
3349 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003350 }
3351
Reid Spencer1628cec2006-10-26 06:15:43 +00003352 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3353 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003354 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003355 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003356 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003357 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003358 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003359 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003360 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003361 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003362 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003363 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003364
3365 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003366 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003367 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003368
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003369 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003370 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003371 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003373 return 0;
3374}
3375
Reid Spencer1628cec2006-10-26 06:15:43 +00003376Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3378
3379 // Handle the integer div common cases
3380 if (Instruction *Common = commonIDivTransforms(I))
3381 return Common;
3382
3383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3384 // sdiv X, -1 == -X
3385 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003386 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003387
Dan Gohmanfa94b942009-08-12 16:33:09 +00003388 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003389 if (cast<SDivOperator>(&I)->isExact() &&
3390 RHS->getValue().isNonNegative() &&
3391 RHS->getValue().isPowerOf2()) {
3392 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3393 RHS->getValue().exactLogBase2());
3394 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3395 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003396
3397 // -X/C --> X/-C provided the negation doesn't overflow.
3398 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3399 if (isa<Constant>(Sub->getOperand(0)) &&
3400 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003401 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003402 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3403 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003404 }
3405
3406 // If the sign bits of both operands are zero (i.e. we can prove they are
3407 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003408 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003409 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003410 if (MaskedValueIsZero(Op0, Mask)) {
3411 if (MaskedValueIsZero(Op1, Mask)) {
3412 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3413 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3414 }
3415 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003416 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003417 ShiftedInt->getValue().isPowerOf2()) {
3418 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3419 // Safe because the only negative value (1 << Y) can take on is
3420 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3421 // the sign bit set.
3422 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3423 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003424 }
Eli Friedman8be17392009-07-18 09:53:21 +00003425 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003426
3427 return 0;
3428}
3429
3430Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3431 return commonDivTransforms(I);
3432}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003433
Reid Spencer0a783f72006-11-02 01:53:59 +00003434/// This function implements the transforms on rem instructions that work
3435/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3436/// is used by the visitors to those instructions.
3437/// @brief Transforms common to all three rem instructions
3438Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003440
Chris Lattner50b2ca42008-02-19 06:12:18 +00003441 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3442 if (I.getType()->isFPOrFPVector())
3443 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003444 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003445 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003446 if (isa<UndefValue>(Op1))
3447 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003448
3449 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003450 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3451 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003452
Reid Spencer0a783f72006-11-02 01:53:59 +00003453 return 0;
3454}
3455
3456/// This function implements the transforms common to both integer remainder
3457/// instructions (urem and srem). It is called by the visitors to those integer
3458/// remainder instructions.
3459/// @brief Common integer remainder transforms
3460Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3462
3463 if (Instruction *common = commonRemTransforms(I))
3464 return common;
3465
Dale Johannesened6af242009-01-21 00:35:19 +00003466 // 0 % X == 0 for integer, we don't need to preserve faults!
3467 if (Constant *LHS = dyn_cast<Constant>(Op0))
3468 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003470
Chris Lattner857e8cd2004-12-12 21:48:58 +00003471 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003472 // X % 0 == undef, we don't need to preserve faults!
3473 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003474 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003475
Chris Lattnera2881962003-02-18 19:28:33 +00003476 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003477 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003478
Chris Lattner97943922006-02-28 05:49:21 +00003479 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3480 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3482 return R;
3483 } else if (isa<PHINode>(Op0I)) {
3484 if (Instruction *NV = FoldOpIntoPhi(I))
3485 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003486 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003487
3488 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003489 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003490 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003491 }
Chris Lattnera2881962003-02-18 19:28:33 +00003492 }
3493
Reid Spencer0a783f72006-11-02 01:53:59 +00003494 return 0;
3495}
3496
3497Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3498 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3499
3500 if (Instruction *common = commonIRemTransforms(I))
3501 return common;
3502
3503 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3504 // X urem C^2 -> X and C
3505 // Check to see if this is an unsigned remainder with an exact power of 2,
3506 // if so, convert to a bitwise and.
3507 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003508 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003509 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003510 }
3511
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003512 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003513 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3514 if (RHSI->getOpcode() == Instruction::Shl &&
3515 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003516 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003517 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003518 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003519 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003520 }
3521 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003522 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003523
Reid Spencer0a783f72006-11-02 01:53:59 +00003524 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3525 // where C1&C2 are powers of two.
3526 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3527 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3528 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3529 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003530 if ((STO->getValue().isPowerOf2()) &&
3531 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003532 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3533 SI->getName()+".t");
3534 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3535 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003536 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003537 }
3538 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003539 }
3540
Chris Lattner3f5b8772002-05-06 16:14:14 +00003541 return 0;
3542}
3543
Reid Spencer0a783f72006-11-02 01:53:59 +00003544Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3546
Dan Gohmancff55092007-11-05 23:16:33 +00003547 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003548 if (Instruction *Common = commonIRemTransforms(I))
3549 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003550
Dan Gohman186a6362009-08-12 16:04:34 +00003551 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003552 if (!isa<Constant>(RHSNeg) ||
3553 (isa<ConstantInt>(RHSNeg) &&
3554 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003555 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003556 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003557 I.setOperand(1, RHSNeg);
3558 return &I;
3559 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003560
Dan Gohmancff55092007-11-05 23:16:33 +00003561 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003562 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003563 if (I.getType()->isInteger()) {
3564 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3565 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3566 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003567 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003568 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003569 }
3570
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003571 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003572 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3573 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003574
Nick Lewycky9dce8732008-12-20 16:48:00 +00003575 bool hasNegative = false;
3576 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3577 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3578 if (RHS->getValue().isNegative())
3579 hasNegative = true;
3580
3581 if (hasNegative) {
3582 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003583 for (unsigned i = 0; i != VWidth; ++i) {
3584 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3585 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003586 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003587 else
3588 Elts[i] = RHS;
3589 }
3590 }
3591
Owen Andersonaf7ec972009-07-28 21:19:26 +00003592 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003593 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003594 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003595 I.setOperand(1, NewRHSV);
3596 return &I;
3597 }
3598 }
3599 }
3600
Reid Spencer0a783f72006-11-02 01:53:59 +00003601 return 0;
3602}
3603
3604Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003605 return commonRemTransforms(I);
3606}
3607
Chris Lattner457dd822004-06-09 07:59:58 +00003608// isOneBitSet - Return true if there is exactly one bit set in the specified
3609// constant.
3610static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003611 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003612}
3613
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003614// isHighOnes - Return true if the constant is of the form 1+0+.
3615// This is the same as lowones(~X).
3616static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003617 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003618}
3619
Reid Spencere4d87aa2006-12-23 06:05:41 +00003620/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003621/// are carefully arranged to allow folding of expressions such as:
3622///
3623/// (A < B) | (A > B) --> (A != B)
3624///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625/// Note that this is only valid if the first and second predicates have the
3626/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003627///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003628/// Three bits are used to represent the condition, as follows:
3629/// 0 A > B
3630/// 1 A == B
3631/// 2 A < B
3632///
3633/// <=> Value Definition
3634/// 000 0 Always false
3635/// 001 1 A > B
3636/// 010 2 A == B
3637/// 011 3 A >= B
3638/// 100 4 A < B
3639/// 101 5 A != B
3640/// 110 6 A <= B
3641/// 111 7 Always true
3642///
3643static unsigned getICmpCode(const ICmpInst *ICI) {
3644 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003645 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 case ICmpInst::ICMP_UGT: return 1; // 001
3647 case ICmpInst::ICMP_SGT: return 1; // 001
3648 case ICmpInst::ICMP_EQ: return 2; // 010
3649 case ICmpInst::ICMP_UGE: return 3; // 011
3650 case ICmpInst::ICMP_SGE: return 3; // 011
3651 case ICmpInst::ICMP_ULT: return 4; // 100
3652 case ICmpInst::ICMP_SLT: return 4; // 100
3653 case ICmpInst::ICMP_NE: return 5; // 101
3654 case ICmpInst::ICMP_ULE: return 6; // 110
3655 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003656 // True -> 7
3657 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003658 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003659 return 0;
3660 }
3661}
3662
Evan Cheng8db90722008-10-14 17:15:11 +00003663/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3664/// predicate into a three bit mask. It also returns whether it is an ordered
3665/// predicate by reference.
3666static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3667 isOrdered = false;
3668 switch (CC) {
3669 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3670 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003671 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3672 case FCmpInst::FCMP_UGT: return 1; // 001
3673 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3674 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003675 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3676 case FCmpInst::FCMP_UGE: return 3; // 011
3677 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3678 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003679 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3680 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003681 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3682 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003683 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003684 default:
3685 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003686 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003687 return 0;
3688 }
3689}
3690
Reid Spencere4d87aa2006-12-23 06:05:41 +00003691/// getICmpValue - This is the complement of getICmpCode, which turns an
3692/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003693/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003694/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003695static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003696 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003698 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003699 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003700 case 1:
3701 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003702 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003703 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003704 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3705 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 case 3:
3707 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003708 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003710 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003711 case 4:
3712 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003713 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003714 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003715 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3716 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 case 6:
3718 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003719 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003720 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003721 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003722 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003723 }
3724}
3725
Evan Cheng8db90722008-10-14 17:15:11 +00003726/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3727/// opcode and two operands into either a FCmp instruction. isordered is passed
3728/// in to determine which kind of predicate to use in the new fcmp instruction.
3729static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003730 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003731 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003732 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003733 case 0:
3734 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003736 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003738 case 1:
3739 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003740 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003741 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003742 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003743 case 2:
3744 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003745 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003746 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003747 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003748 case 3:
3749 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003750 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003751 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003752 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003753 case 4:
3754 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003755 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003756 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003757 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003758 case 5:
3759 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003760 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003761 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003762 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003763 case 6:
3764 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003765 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003766 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003767 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003768 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003769 }
3770}
3771
Chris Lattnerb9553d62008-11-16 04:55:20 +00003772/// PredicatesFoldable - Return true if both predicates match sign or if at
3773/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003774static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003775 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3776 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3777 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003778}
3779
3780namespace {
3781// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3782struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003783 InstCombiner &IC;
3784 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 ICmpInst::Predicate pred;
3786 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3787 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3788 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003789 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3791 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003792 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3793 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003794 return false;
3795 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003796 Instruction *apply(Instruction &Log) const {
3797 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3798 if (ICI->getOperand(0) != LHS) {
3799 assert(ICI->getOperand(1) == LHS);
3800 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003801 }
3802
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003803 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003804 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003805 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003806 unsigned Code;
3807 switch (Log.getOpcode()) {
3808 case Instruction::And: Code = LHSCode & RHSCode; break;
3809 case Instruction::Or: Code = LHSCode | RHSCode; break;
3810 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003811 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003812 }
3813
Nick Lewycky4a134af2009-10-25 05:20:17 +00003814 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003815 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003816 if (Instruction *I = dyn_cast<Instruction>(RV))
3817 return I;
3818 // Otherwise, it's a constant boolean value...
3819 return IC.ReplaceInstUsesWith(Log, RV);
3820 }
3821};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003822} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003823
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003824// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3825// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003826// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003827Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003828 ConstantInt *OpRHS,
3829 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003830 BinaryOperator &TheAnd) {
3831 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003832 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003833 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003834 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003835
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003836 switch (Op->getOpcode()) {
3837 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003838 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003839 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003840 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003841 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003842 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003843 }
3844 break;
3845 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003846 if (Together == AndRHS) // (X | C) & C --> C
3847 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003848
Chris Lattner6e7ba452005-01-01 16:22:27 +00003849 if (Op->hasOneUse() && Together != OpRHS) {
3850 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003851 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003852 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003853 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003854 }
3855 break;
3856 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003857 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003858 // Adding a one to a single bit bit-field should be turned into an XOR
3859 // of the bit. First thing to check is to see if this AND is with a
3860 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003861 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003862
3863 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003864 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003865 // Ok, at this point, we know that we are masking the result of the
3866 // ADD down to exactly one bit. If the constant we are adding has
3867 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003868 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003869
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003870 // Check to see if any bits below the one bit set in AndRHSV are set.
3871 if ((AddRHS & (AndRHSV-1)) == 0) {
3872 // If not, the only thing that can effect the output of the AND is
3873 // the bit specified by AndRHSV. If that bit is set, the effect of
3874 // the XOR is to toggle the bit. If it is clear, then the ADD has
3875 // no effect.
3876 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3877 TheAnd.setOperand(0, X);
3878 return &TheAnd;
3879 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003880 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003881 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003882 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003883 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003884 }
3885 }
3886 }
3887 }
3888 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003889
3890 case Instruction::Shl: {
3891 // We know that the AND will not produce any of the bits shifted in, so if
3892 // the anded constant includes them, clear them now!
3893 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003894 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003895 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003896 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003897 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003898
Zhou Sheng290bec52007-03-29 08:15:12 +00003899 if (CI->getValue() == ShlMask) {
3900 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003901 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3902 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003903 TheAnd.setOperand(1, CI);
3904 return &TheAnd;
3905 }
3906 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003907 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003908 case Instruction::LShr:
3909 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003910 // We know that the AND will not produce any of the bits shifted in, so if
3911 // the anded constant includes them, clear them now! This only applies to
3912 // unsigned shifts, because a signed shr may bring in set bits!
3913 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003914 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003915 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003916 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003917 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003918
Zhou Sheng290bec52007-03-29 08:15:12 +00003919 if (CI->getValue() == ShrMask) {
3920 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003921 return ReplaceInstUsesWith(TheAnd, Op);
3922 } else if (CI != AndRHS) {
3923 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3924 return &TheAnd;
3925 }
3926 break;
3927 }
3928 case Instruction::AShr:
3929 // Signed shr.
3930 // See if this is shifting in some sign extension, then masking it out
3931 // with an and.
3932 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003933 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003934 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003935 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003936 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003937 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003938 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003939 // Make the argument unsigned.
3940 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003941 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003942 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003943 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003944 }
3945 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003946 }
3947 return 0;
3948}
3949
Chris Lattner8b170942002-08-09 23:47:40 +00003950
Chris Lattnera96879a2004-09-29 17:40:11 +00003951/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3952/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003953/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3954/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003955/// insert new instructions.
3956Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003957 bool isSigned, bool Inside,
3958 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003959 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003960 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003961 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003962
Chris Lattnera96879a2004-09-29 17:40:11 +00003963 if (Inside) {
3964 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003965 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003966
Reid Spencere4d87aa2006-12-23 06:05:41 +00003967 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003968 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003969 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003970 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003971 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003972 }
3973
3974 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003975 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003976 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003977 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003978 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003979 }
3980
3981 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003982 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003983
Reid Spencere4e40032007-03-21 23:19:50 +00003984 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003985 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003986 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003987 ICmpInst::Predicate pred = (isSigned ?
3988 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003989 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003990 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003991
Reid Spencere4e40032007-03-21 23:19:50 +00003992 // Emit V-Lo >u Hi-1-Lo
3993 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003994 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003995 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003996 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003997 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003998}
3999
Chris Lattner7203e152005-09-18 07:22:02 +00004000// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4001// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4002// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4003// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004004static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004005 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004006 uint32_t BitWidth = Val->getType()->getBitWidth();
4007 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004008
4009 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004010 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004011 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004012 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004013 return true;
4014}
4015
Chris Lattner7203e152005-09-18 07:22:02 +00004016/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4017/// where isSub determines whether the operator is a sub. If we can fold one of
4018/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004019///
4020/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4021/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4022/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4023///
4024/// return (A +/- B).
4025///
4026Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004027 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004028 Instruction &I) {
4029 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4030 if (!LHSI || LHSI->getNumOperands() != 2 ||
4031 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4032
4033 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4034
4035 switch (LHSI->getOpcode()) {
4036 default: return 0;
4037 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004038 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004039 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004040 if ((Mask->getValue().countLeadingZeros() +
4041 Mask->getValue().countPopulation()) ==
4042 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004043 break;
4044
4045 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4046 // part, we don't need any explicit masks to take them out of A. If that
4047 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004048 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004049 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004050 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004051 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004052 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004053 break;
4054 }
4055 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004056 return 0;
4057 case Instruction::Or:
4058 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004059 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004060 if ((Mask->getValue().countLeadingZeros() +
4061 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004062 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004063 break;
4064 return 0;
4065 }
4066
Chris Lattnerc8e77562005-09-18 04:24:45 +00004067 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004068 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4069 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004070}
4071
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004072/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4073Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4074 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004075 // (icmp eq A, null) & (icmp eq B, null) -->
4076 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4077 if (TD &&
4078 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4079 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4080 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4081 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4082 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4083 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4084 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4085 Value *NewOr = Builder->CreateOr(A, B);
4086 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4087 Constant::getNullValue(IntPtrTy));
4088 }
4089
Chris Lattnerea065fb2008-11-16 05:10:52 +00004090 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004091 ConstantInt *LHSCst, *RHSCst;
4092 ICmpInst::Predicate LHSCC, RHSCC;
4093
Chris Lattnerea065fb2008-11-16 05:10:52 +00004094 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004095 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004096 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004097 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004098 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004099 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004100
Chris Lattner3f40e232009-11-29 00:51:17 +00004101 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4102 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4103 // where C is a power of 2
4104 if (LHSCC == ICmpInst::ICMP_ULT &&
4105 LHSCst->getValue().isPowerOf2()) {
4106 Value *NewOr = Builder->CreateOr(Val, Val2);
4107 return new ICmpInst(LHSCC, NewOr, LHSCst);
4108 }
4109
4110 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4111 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4112 Value *NewOr = Builder->CreateOr(Val, Val2);
4113 return new ICmpInst(LHSCC, NewOr, LHSCst);
4114 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004115 }
4116
4117 // From here on, we only handle:
4118 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4119 if (Val != Val2) return 0;
4120
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004121 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4122 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4123 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4124 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4125 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4126 return 0;
4127
4128 // We can't fold (ugt x, C) & (sgt x, C2).
4129 if (!PredicatesFoldable(LHSCC, RHSCC))
4130 return 0;
4131
4132 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004133 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004134 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004135 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004136 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004137 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004138 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004139 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4140
4141 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004142 std::swap(LHS, RHS);
4143 std::swap(LHSCst, RHSCst);
4144 std::swap(LHSCC, RHSCC);
4145 }
4146
4147 // At this point, we know we have have two icmp instructions
4148 // comparing a value against two constants and and'ing the result
4149 // together. Because of the above check, we know that we only have
4150 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4151 // (from the FoldICmpLogical check above), that the two constants
4152 // are not equal and that the larger constant is on the RHS
4153 assert(LHSCst != RHSCst && "Compares not folded above?");
4154
4155 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004156 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004157 case ICmpInst::ICMP_EQ:
4158 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004159 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004160 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4161 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4162 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004163 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004164 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4165 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4166 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4167 return ReplaceInstUsesWith(I, LHS);
4168 }
4169 case ICmpInst::ICMP_NE:
4170 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004171 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004172 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004173 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004174 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004175 break; // (X != 13 & X u< 15) -> no change
4176 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004177 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004178 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004179 break; // (X != 13 & X s< 15) -> no change
4180 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4181 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4182 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4183 return ReplaceInstUsesWith(I, RHS);
4184 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004185 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004186 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004187 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004188 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004189 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004190 }
4191 break; // (X != 13 & X != 15) -> no change
4192 }
4193 break;
4194 case ICmpInst::ICMP_ULT:
4195 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004196 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004197 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4198 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004200 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4201 break;
4202 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4203 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4204 return ReplaceInstUsesWith(I, LHS);
4205 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4206 break;
4207 }
4208 break;
4209 case ICmpInst::ICMP_SLT:
4210 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004211 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004212 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4213 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004214 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004215 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4216 break;
4217 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4218 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4219 return ReplaceInstUsesWith(I, LHS);
4220 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4221 break;
4222 }
4223 break;
4224 case ICmpInst::ICMP_UGT:
4225 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004226 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004227 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4228 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4229 return ReplaceInstUsesWith(I, RHS);
4230 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4231 break;
4232 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004233 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004234 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004235 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004236 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004237 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004238 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004239 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4240 break;
4241 }
4242 break;
4243 case ICmpInst::ICMP_SGT:
4244 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004245 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004246 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4247 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4248 return ReplaceInstUsesWith(I, RHS);
4249 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4250 break;
4251 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004252 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004253 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004254 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004255 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004256 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004257 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004258 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4259 break;
4260 }
4261 break;
4262 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004263
4264 return 0;
4265}
4266
Chris Lattner42d1be02009-07-23 05:14:02 +00004267Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4268 FCmpInst *RHS) {
4269
4270 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4271 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4272 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4273 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4274 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4275 // If either of the constants are nans, then the whole thing returns
4276 // false.
4277 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004278 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004279 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004280 LHS->getOperand(0), RHS->getOperand(0));
4281 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004282
4283 // Handle vector zeros. This occurs because the canonical form of
4284 // "fcmp ord x,x" is "fcmp ord x, 0".
4285 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4286 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004287 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004288 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004289 return 0;
4290 }
4291
4292 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4293 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4294 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4295
4296
4297 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4298 // Swap RHS operands to match LHS.
4299 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4300 std::swap(Op1LHS, Op1RHS);
4301 }
4302
4303 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4304 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4305 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004306 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004307
4308 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004309 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004310 if (Op0CC == FCmpInst::FCMP_TRUE)
4311 return ReplaceInstUsesWith(I, RHS);
4312 if (Op1CC == FCmpInst::FCMP_TRUE)
4313 return ReplaceInstUsesWith(I, LHS);
4314
4315 bool Op0Ordered;
4316 bool Op1Ordered;
4317 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4318 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4319 if (Op1Pred == 0) {
4320 std::swap(LHS, RHS);
4321 std::swap(Op0Pred, Op1Pred);
4322 std::swap(Op0Ordered, Op1Ordered);
4323 }
4324 if (Op0Pred == 0) {
4325 // uno && ueq -> uno && (uno || eq) -> ueq
4326 // ord && olt -> ord && (ord && lt) -> olt
4327 if (Op0Ordered == Op1Ordered)
4328 return ReplaceInstUsesWith(I, RHS);
4329
4330 // uno && oeq -> uno && (ord && eq) -> false
4331 // uno && ord -> false
4332 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004333 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004334 // ord && ueq -> ord && (uno || eq) -> oeq
4335 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4336 Op0LHS, Op0RHS, Context));
4337 }
4338 }
4339
4340 return 0;
4341}
4342
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004343
Chris Lattner7e708292002-06-25 16:13:24 +00004344Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004345 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004346 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004347
Chris Lattnerd06094f2009-11-10 00:55:12 +00004348 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4349 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004350
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004351 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004352 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004353 if (SimplifyDemandedInstructionBits(I))
4354 return &I;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004355
Dan Gohman6de29f82009-06-15 22:12:54 +00004356
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004357 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004358 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004359 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004360
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004361 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004362 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004363 Value *Op0LHS = Op0I->getOperand(0);
4364 Value *Op0RHS = Op0I->getOperand(1);
4365 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004366 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004367 case Instruction::Xor:
4368 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004369 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004370 if (!Op0I->hasOneUse()) break;
4371
4372 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4373 // Not masking anything out for the LHS, move to RHS.
4374 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4375 Op0RHS->getName()+".masked");
4376 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4377 }
4378 if (!isa<Constant>(Op0RHS) &&
4379 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4380 // Not masking anything out for the RHS, move to LHS.
4381 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4382 Op0LHS->getName()+".masked");
4383 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004384 }
4385
Chris Lattner6e7ba452005-01-01 16:22:27 +00004386 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004387 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004388 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4389 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4390 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4391 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004392 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004393 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004394 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004395 break;
4396
4397 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004398 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4399 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4400 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4401 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004402 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004403
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004404 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4405 // has 1's for all bits that the subtraction with A might affect.
4406 if (Op0I->hasOneUse()) {
4407 uint32_t BitWidth = AndRHSMask.getBitWidth();
4408 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4409 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4410
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004411 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004412 if (!(A && A->isZero()) && // avoid infinite recursion.
4413 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004414 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004415 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4416 }
4417 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004418 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004419
4420 case Instruction::Shl:
4421 case Instruction::LShr:
4422 // (1 << x) & 1 --> zext(x == 0)
4423 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004424 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004425 Value *NewICmp =
4426 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004427 return new ZExtInst(NewICmp, I.getType());
4428 }
4429 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004430 }
4431
Chris Lattner58403262003-07-23 19:25:52 +00004432 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004433 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004434 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004435 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004436 // If this is an integer truncation or change from signed-to-unsigned, and
4437 // if the source is an and/or with immediate, transform it. This
4438 // frequently occurs for bitfield accesses.
4439 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004440 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004441 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004442 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004443 if (CastOp->getOpcode() == Instruction::And) {
4444 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004445 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4446 // This will fold the two constants together, which may allow
4447 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004448 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004449 CastOp->getOperand(0), I.getType(),
4450 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004451 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004452 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004453 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004454 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004455 } else if (CastOp->getOpcode() == Instruction::Or) {
4456 // Change: and (cast (or X, C1) to T), C2
4457 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004458 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004459 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004460 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004461 return ReplaceInstUsesWith(I, AndRHS);
4462 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004463 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004464 }
Chris Lattner06782f82003-07-23 19:36:21 +00004465 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004466
4467 // Try to fold constant and into select arguments.
4468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004470 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004471 if (isa<PHINode>(Op0))
4472 if (Instruction *NV = FoldOpIntoPhi(I))
4473 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004474 }
4475
Chris Lattner5b62aa72004-06-18 06:07:51 +00004476
Misha Brukmancb6267b2004-07-30 12:50:08 +00004477 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004478 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4479 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4480 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4481 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4482 I.getName()+".demorgan");
4483 return BinaryOperator::CreateNot(Or);
4484 }
4485
Chris Lattner2082ad92006-02-13 23:07:23 +00004486 {
Chris Lattner003b6202007-06-15 05:58:24 +00004487 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004488 // (A|B) & ~(A&B) -> A^B
4489 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4490 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4491 ((A == C && B == D) || (A == D && B == C)))
4492 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004493
Chris Lattnerd06094f2009-11-10 00:55:12 +00004494 // ~(A&B) & (A|B) -> A^B
4495 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4496 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4497 ((A == C && B == D) || (A == D && B == C)))
4498 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004499
4500 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004501 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004502 if (A == Op1) { // (A^B)&A -> A&(A^B)
4503 I.swapOperands(); // Simplify below
4504 std::swap(Op0, Op1);
4505 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4506 cast<BinaryOperator>(Op0)->swapOperands();
4507 I.swapOperands(); // Simplify below
4508 std::swap(Op0, Op1);
4509 }
4510 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004511
Chris Lattner64daab52006-04-01 08:03:55 +00004512 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004513 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004514 if (B == Op0) { // B&(A^B) -> B&(B^A)
4515 cast<BinaryOperator>(Op1)->swapOperands();
4516 std::swap(A, B);
4517 }
Chris Lattner74381062009-08-30 07:44:24 +00004518 if (A == Op0) // A&(A^B) -> A & ~B
4519 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004520 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004521
4522 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004523 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4524 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004525 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004526 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4527 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004528 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004529 }
4530
Reid Spencere4d87aa2006-12-23 06:05:41 +00004531 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4532 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004533 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004534 return R;
4535
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004536 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4537 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4538 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004539 }
4540
Chris Lattner6fc205f2006-05-05 06:39:07 +00004541 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004542 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4543 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4544 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4545 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004546 if (SrcTy == Op1C->getOperand(0)->getType() &&
4547 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004548 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004549 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4550 I.getType(), TD) &&
4551 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4552 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004553 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4554 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004555 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004556 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004557 }
Chris Lattnere511b742006-11-14 07:46:50 +00004558
4559 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004560 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4561 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4562 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004563 SI0->getOperand(1) == SI1->getOperand(1) &&
4564 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004565 Value *NewOp =
4566 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4567 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004568 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004569 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004570 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004571 }
4572
Evan Cheng8db90722008-10-14 17:15:11 +00004573 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004574 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004575 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4576 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4577 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004578 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004579
Chris Lattner7e708292002-06-25 16:13:24 +00004580 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004581}
4582
Chris Lattner8c34cd22008-10-05 02:13:19 +00004583/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4584/// capable of providing pieces of a bswap. The subexpression provides pieces
4585/// of a bswap if it is proven that each of the non-zero bytes in the output of
4586/// the expression came from the corresponding "byte swapped" byte in some other
4587/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4588/// we know that the expression deposits the low byte of %X into the high byte
4589/// of the bswap result and that all other bytes are zero. This expression is
4590/// accepted, the high byte of ByteValues is set to X to indicate a correct
4591/// match.
4592///
4593/// This function returns true if the match was unsuccessful and false if so.
4594/// On entry to the function the "OverallLeftShift" is a signed integer value
4595/// indicating the number of bytes that the subexpression is later shifted. For
4596/// example, if the expression is later right shifted by 16 bits, the
4597/// OverallLeftShift value would be -2 on entry. This is used to specify which
4598/// byte of ByteValues is actually being set.
4599///
4600/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4601/// byte is masked to zero by a user. For example, in (X & 255), X will be
4602/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4603/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4604/// always in the local (OverallLeftShift) coordinate space.
4605///
4606static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4607 SmallVector<Value*, 8> &ByteValues) {
4608 if (Instruction *I = dyn_cast<Instruction>(V)) {
4609 // If this is an or instruction, it may be an inner node of the bswap.
4610 if (I->getOpcode() == Instruction::Or) {
4611 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4612 ByteValues) ||
4613 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4614 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004615 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004616
4617 // If this is a logical shift by a constant multiple of 8, recurse with
4618 // OverallLeftShift and ByteMask adjusted.
4619 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4620 unsigned ShAmt =
4621 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4622 // Ensure the shift amount is defined and of a byte value.
4623 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4624 return true;
4625
4626 unsigned ByteShift = ShAmt >> 3;
4627 if (I->getOpcode() == Instruction::Shl) {
4628 // X << 2 -> collect(X, +2)
4629 OverallLeftShift += ByteShift;
4630 ByteMask >>= ByteShift;
4631 } else {
4632 // X >>u 2 -> collect(X, -2)
4633 OverallLeftShift -= ByteShift;
4634 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004635 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004636 }
4637
4638 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4639 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4640
4641 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4642 ByteValues);
4643 }
4644
4645 // If this is a logical 'and' with a mask that clears bytes, clear the
4646 // corresponding bytes in ByteMask.
4647 if (I->getOpcode() == Instruction::And &&
4648 isa<ConstantInt>(I->getOperand(1))) {
4649 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4650 unsigned NumBytes = ByteValues.size();
4651 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4652 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4653
4654 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4655 // If this byte is masked out by a later operation, we don't care what
4656 // the and mask is.
4657 if ((ByteMask & (1 << i)) == 0)
4658 continue;
4659
4660 // If the AndMask is all zeros for this byte, clear the bit.
4661 APInt MaskB = AndMask & Byte;
4662 if (MaskB == 0) {
4663 ByteMask &= ~(1U << i);
4664 continue;
4665 }
4666
4667 // If the AndMask is not all ones for this byte, it's not a bytezap.
4668 if (MaskB != Byte)
4669 return true;
4670
4671 // Otherwise, this byte is kept.
4672 }
4673
4674 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4675 ByteValues);
4676 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004677 }
4678
Chris Lattner8c34cd22008-10-05 02:13:19 +00004679 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4680 // the input value to the bswap. Some observations: 1) if more than one byte
4681 // is demanded from this input, then it could not be successfully assembled
4682 // into a byteswap. At least one of the two bytes would not be aligned with
4683 // their ultimate destination.
4684 if (!isPowerOf2_32(ByteMask)) return true;
4685 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004686
Chris Lattner8c34cd22008-10-05 02:13:19 +00004687 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4688 // is demanded, it needs to go into byte 0 of the result. This means that the
4689 // byte needs to be shifted until it lands in the right byte bucket. The
4690 // shift amount depends on the position: if the byte is coming from the high
4691 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4692 // low part, it must be shifted left.
4693 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4694 if (InputByteNo < ByteValues.size()/2) {
4695 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4696 return true;
4697 } else {
4698 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4699 return true;
4700 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004701
4702 // If the destination byte value is already defined, the values are or'd
4703 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004704 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004705 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004706 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004707 return false;
4708}
4709
4710/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4711/// If so, insert the new bswap intrinsic and return it.
4712Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004713 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004714 if (!ITy || ITy->getBitWidth() % 16 ||
4715 // ByteMask only allows up to 32-byte values.
4716 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004717 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004718
4719 /// ByteValues - For each byte of the result, we keep track of which value
4720 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004721 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004722 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004723
4724 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004725 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4726 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004727 return 0;
4728
4729 // Check to see if all of the bytes come from the same value.
4730 Value *V = ByteValues[0];
4731 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4732
4733 // Check to make sure that all of the bytes come from the same value.
4734 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4735 if (ByteValues[i] != V)
4736 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004737 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004738 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004739 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004740 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004741}
4742
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004743/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4744/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4745/// we can simplify this expression to "cond ? C : D or B".
4746static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004747 Value *C, Value *D,
4748 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004749 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004750 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004751 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004752 return 0;
4753
Chris Lattnera6a474d2008-11-16 04:26:55 +00004754 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004755 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004756 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004757 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004758 return SelectInst::Create(Cond, C, B);
4759 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004760 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004761 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004762 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004763 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004764 return 0;
4765}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004766
Chris Lattner69d4ced2008-11-16 05:20:07 +00004767/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4768Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4769 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004770 // (icmp ne A, null) | (icmp ne B, null) -->
4771 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4772 if (TD &&
4773 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4774 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4775 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4776 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4777 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4778 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4779 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4780 Value *NewOr = Builder->CreateOr(A, B);
4781 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4782 Constant::getNullValue(IntPtrTy));
4783 }
4784
Chris Lattner69d4ced2008-11-16 05:20:07 +00004785 Value *Val, *Val2;
4786 ConstantInt *LHSCst, *RHSCst;
4787 ICmpInst::Predicate LHSCC, RHSCC;
4788
4789 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004790 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4791 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004792 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004793
4794
4795 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4796 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4797 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4798 Value *NewOr = Builder->CreateOr(Val, Val2);
4799 return new ICmpInst(LHSCC, NewOr, LHSCst);
4800 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004801
4802 // From here on, we only handle:
4803 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4804 if (Val != Val2) return 0;
4805
4806 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4807 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4808 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4809 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4810 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4811 return 0;
4812
4813 // We can't fold (ugt x, C) | (sgt x, C2).
4814 if (!PredicatesFoldable(LHSCC, RHSCC))
4815 return 0;
4816
4817 // Ensure that the larger constant is on the RHS.
4818 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004819 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004820 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004821 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004822 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4823 else
4824 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4825
4826 if (ShouldSwap) {
4827 std::swap(LHS, RHS);
4828 std::swap(LHSCst, RHSCst);
4829 std::swap(LHSCC, RHSCC);
4830 }
4831
4832 // At this point, we know we have have two icmp instructions
4833 // comparing a value against two constants and or'ing the result
4834 // together. Because of the above check, we know that we only have
4835 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4836 // FoldICmpLogical check above), that the two constants are not
4837 // equal.
4838 assert(LHSCst != RHSCst && "Compares not folded above?");
4839
4840 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004841 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004842 case ICmpInst::ICMP_EQ:
4843 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004844 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004845 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004846 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004847 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004848 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004849 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004850 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004851 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004852 }
4853 break; // (X == 13 | X == 15) -> no change
4854 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4855 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4856 break;
4857 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4858 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4859 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4860 return ReplaceInstUsesWith(I, RHS);
4861 }
4862 break;
4863 case ICmpInst::ICMP_NE:
4864 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004865 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004866 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4867 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4868 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4869 return ReplaceInstUsesWith(I, LHS);
4870 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4871 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4872 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004873 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004874 }
4875 break;
4876 case ICmpInst::ICMP_ULT:
4877 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004878 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004879 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4880 break;
4881 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4882 // If RHSCst is [us]MAXINT, it is always false. Not handling
4883 // this can cause overflow.
4884 if (RHSCst->isMaxValue(false))
4885 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004886 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004887 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004888 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4889 break;
4890 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4891 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4892 return ReplaceInstUsesWith(I, RHS);
4893 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4894 break;
4895 }
4896 break;
4897 case ICmpInst::ICMP_SLT:
4898 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004899 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004900 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4901 break;
4902 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4903 // If RHSCst is [us]MAXINT, it is always false. Not handling
4904 // this can cause overflow.
4905 if (RHSCst->isMaxValue(true))
4906 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004907 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004908 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004909 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4910 break;
4911 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4912 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4913 return ReplaceInstUsesWith(I, RHS);
4914 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4915 break;
4916 }
4917 break;
4918 case ICmpInst::ICMP_UGT:
4919 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004920 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004921 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4922 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4923 return ReplaceInstUsesWith(I, LHS);
4924 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4925 break;
4926 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4927 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004928 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004929 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4930 break;
4931 }
4932 break;
4933 case ICmpInst::ICMP_SGT:
4934 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004935 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004936 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4937 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4938 return ReplaceInstUsesWith(I, LHS);
4939 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4940 break;
4941 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4942 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004943 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004944 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4945 break;
4946 }
4947 break;
4948 }
4949 return 0;
4950}
4951
Chris Lattner5414cc52009-07-23 05:46:22 +00004952Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4953 FCmpInst *RHS) {
4954 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4955 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4956 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4957 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4958 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4959 // If either of the constants are nans, then the whole thing returns
4960 // true.
4961 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004962 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004963
4964 // Otherwise, no need to compare the two constants, compare the
4965 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004966 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004967 LHS->getOperand(0), RHS->getOperand(0));
4968 }
4969
4970 // Handle vector zeros. This occurs because the canonical form of
4971 // "fcmp uno x,x" is "fcmp uno x, 0".
4972 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4973 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004974 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004975 LHS->getOperand(0), RHS->getOperand(0));
4976
4977 return 0;
4978 }
4979
4980 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4981 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4982 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4983
4984 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4985 // Swap RHS operands to match LHS.
4986 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4987 std::swap(Op1LHS, Op1RHS);
4988 }
4989 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4990 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4991 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004992 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004993 Op0LHS, Op0RHS);
4994 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004995 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004996 if (Op0CC == FCmpInst::FCMP_FALSE)
4997 return ReplaceInstUsesWith(I, RHS);
4998 if (Op1CC == FCmpInst::FCMP_FALSE)
4999 return ReplaceInstUsesWith(I, LHS);
5000 bool Op0Ordered;
5001 bool Op1Ordered;
5002 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5003 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5004 if (Op0Ordered == Op1Ordered) {
5005 // If both are ordered or unordered, return a new fcmp with
5006 // or'ed predicates.
5007 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5008 Op0LHS, Op0RHS, Context);
5009 if (Instruction *I = dyn_cast<Instruction>(RV))
5010 return I;
5011 // Otherwise, it's a constant boolean value...
5012 return ReplaceInstUsesWith(I, RV);
5013 }
5014 }
5015 return 0;
5016}
5017
Bill Wendlinga698a472008-12-01 08:23:25 +00005018/// FoldOrWithConstants - This helper function folds:
5019///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005020/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005021///
5022/// into:
5023///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005024/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005025///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005026/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005027Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005028 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005029 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5030 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005031
Bill Wendling286a0542008-12-02 06:24:20 +00005032 Value *V1 = 0;
5033 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005034 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005035
Bill Wendling29976b92008-12-02 06:18:11 +00005036 APInt Xor = CI1->getValue() ^ CI2->getValue();
5037 if (!Xor.isAllOnesValue()) return 0;
5038
Bill Wendling286a0542008-12-02 06:24:20 +00005039 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005040 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005041 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005042 }
5043
5044 return 0;
5045}
5046
Chris Lattner7e708292002-06-25 16:13:24 +00005047Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005048 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005050
Chris Lattnerd06094f2009-11-10 00:55:12 +00005051 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5052 return ReplaceInstUsesWith(I, V);
5053
5054
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005055 // See if we can simplify any instructions used by the instruction whose sole
5056 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005057 if (SimplifyDemandedInstructionBits(I))
5058 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005059
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005060 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005061 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005062 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005063 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005064 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005065 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005066 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005067 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005068 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005069 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005070
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005071 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005072 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005073 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005074 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005075 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005076 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005077 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005078 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005079
5080 // Try to fold constant and into select arguments.
5081 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005082 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005083 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005084 if (isa<PHINode>(Op0))
5085 if (Instruction *NV = FoldOpIntoPhi(I))
5086 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005087 }
5088
Chris Lattner4f637d42006-01-06 17:59:59 +00005089 Value *A = 0, *B = 0;
5090 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005091
Chris Lattner6423d4c2006-07-10 20:25:24 +00005092 // (A | B) | C and A | (B | C) -> bswap if possible.
5093 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005094 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5095 match(Op1, m_Or(m_Value(), m_Value())) ||
5096 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5097 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005098 if (Instruction *BSwap = MatchBSwap(I))
5099 return BSwap;
5100 }
5101
Chris Lattner6e4c6492005-05-09 04:58:36 +00005102 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005103 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005104 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005105 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005106 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005107 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005108 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005109 }
5110
5111 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005112 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005113 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005114 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005115 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005116 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005117 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005118 }
5119
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005120 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005121 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005122 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5123 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005124 Value *V1 = 0, *V2 = 0, *V3 = 0;
5125 C1 = dyn_cast<ConstantInt>(C);
5126 C2 = dyn_cast<ConstantInt>(D);
5127 if (C1 && C2) { // (A & C1)|(B & C2)
5128 // If we have: ((V + N) & C1) | (V & C2)
5129 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5130 // replace with V+N.
5131 if (C1->getValue() == ~C2->getValue()) {
5132 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005133 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005134 // Add commutes, try both ways.
5135 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5136 return ReplaceInstUsesWith(I, A);
5137 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5138 return ReplaceInstUsesWith(I, A);
5139 }
5140 // Or commutes, try both ways.
5141 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005142 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005143 // Add commutes, try both ways.
5144 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5145 return ReplaceInstUsesWith(I, B);
5146 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5147 return ReplaceInstUsesWith(I, B);
5148 }
5149 }
Chris Lattner044e5332007-04-08 08:01:49 +00005150 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005151 }
5152
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005153 // Check to see if we have any common things being and'ed. If so, find the
5154 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005155 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5156 if (A == B) // (A & C)|(A & D) == A & (C|D)
5157 V1 = A, V2 = C, V3 = D;
5158 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5159 V1 = A, V2 = B, V3 = C;
5160 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5161 V1 = C, V2 = A, V3 = D;
5162 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5163 V1 = C, V2 = A, V3 = B;
5164
5165 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005166 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005167 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005168 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005169 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005170
Dan Gohman1975d032008-10-30 20:40:10 +00005171 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005172 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005173 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005174 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005175 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005176 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005177 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005178 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005179 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005180
Bill Wendlingb01865c2008-11-30 13:52:49 +00005181 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005182 if ((match(C, m_Not(m_Specific(D))) &&
5183 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005184 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005185 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005186 if ((match(A, m_Not(m_Specific(D))) &&
5187 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005188 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005189 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005190 if ((match(C, m_Not(m_Specific(B))) &&
5191 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005192 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005193 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005194 if ((match(A, m_Not(m_Specific(B))) &&
5195 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005196 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005197 }
Chris Lattnere511b742006-11-14 07:46:50 +00005198
5199 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005200 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5201 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5202 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005203 SI0->getOperand(1) == SI1->getOperand(1) &&
5204 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005205 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5206 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005208 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005209 }
5210 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005211
Bill Wendlingb3833d12008-12-01 01:07:11 +00005212 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005213 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5214 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005215 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005216 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005217 }
5218 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005219 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5220 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005221 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005222 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005223 }
5224
Chris Lattnerd06094f2009-11-10 00:55:12 +00005225 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5226 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5227 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5228 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5229 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5230 I.getName()+".demorgan");
5231 return BinaryOperator::CreateNot(And);
5232 }
Chris Lattnera2881962003-02-18 19:28:33 +00005233
Reid Spencere4d87aa2006-12-23 06:05:41 +00005234 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5235 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005236 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005237 return R;
5238
Chris Lattner69d4ced2008-11-16 05:20:07 +00005239 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5240 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5241 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005242 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005243
5244 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005245 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005246 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005247 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005248 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5249 !isa<ICmpInst>(Op1C->getOperand(0))) {
5250 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005251 if (SrcTy == Op1C->getOperand(0)->getType() &&
5252 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005253 // Only do this if the casts both really cause code to be
5254 // generated.
5255 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5256 I.getType(), TD) &&
5257 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5258 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005259 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5260 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005261 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005262 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005263 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005264 }
Chris Lattner99c65742007-10-24 05:38:08 +00005265 }
5266
5267
5268 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5269 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005270 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5271 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5272 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005273 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005274
Chris Lattner7e708292002-06-25 16:13:24 +00005275 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005276}
5277
Dan Gohman844731a2008-05-13 00:00:25 +00005278namespace {
5279
Chris Lattnerc317d392004-02-16 01:20:27 +00005280// XorSelf - Implements: X ^ X --> 0
5281struct XorSelf {
5282 Value *RHS;
5283 XorSelf(Value *rhs) : RHS(rhs) {}
5284 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5285 Instruction *apply(BinaryOperator &Xor) const {
5286 return &Xor;
5287 }
5288};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005289
Dan Gohman844731a2008-05-13 00:00:25 +00005290}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005291
Chris Lattner7e708292002-06-25 16:13:24 +00005292Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005293 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005294 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005295
Evan Chengd34af782008-03-25 20:07:13 +00005296 if (isa<UndefValue>(Op1)) {
5297 if (isa<UndefValue>(Op0))
5298 // Handle undef ^ undef -> 0 special case. This is a common
5299 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005300 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005301 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005302 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005303
Chris Lattnerc317d392004-02-16 01:20:27 +00005304 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005305 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005306 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005308 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005309
5310 // See if we can simplify any instructions used by the instruction whose sole
5311 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005312 if (SimplifyDemandedInstructionBits(I))
5313 return &I;
5314 if (isa<VectorType>(I.getType()))
5315 if (isa<ConstantAggregateZero>(Op1))
5316 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005317
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005318 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005319 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005320 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5321 if (Op0I->getOpcode() == Instruction::And ||
5322 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005323 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5324 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5325 if (dyn_castNotVal(Op0I->getOperand(1)))
5326 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005327 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005328 Value *NotY =
5329 Builder->CreateNot(Op0I->getOperand(1),
5330 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005331 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005332 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005333 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005334 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005335
5336 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5337 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5338 if (isFreeToInvert(Op0I->getOperand(0)) &&
5339 isFreeToInvert(Op0I->getOperand(1))) {
5340 Value *NotX =
5341 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5342 Value *NotY =
5343 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5344 if (Op0I->getOpcode() == Instruction::And)
5345 return BinaryOperator::CreateOr(NotX, NotY);
5346 return BinaryOperator::CreateAnd(NotX, NotY);
5347 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005348 }
5349 }
5350 }
5351
5352
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005353 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005354 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005355 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005356 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005357 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005358 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005359
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005360 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005361 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005362 FCI->getOperand(0), FCI->getOperand(1));
5363 }
5364
Nick Lewycky517e1f52008-05-31 19:01:33 +00005365 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5366 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5367 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5368 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5369 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005370 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5371 (RHS == ConstantExpr::getCast(Opcode,
5372 ConstantInt::getTrue(*Context),
5373 Op0C->getDestTy()))) {
5374 CI->setPredicate(CI->getInversePredicate());
5375 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005376 }
5377 }
5378 }
5379 }
5380
Reid Spencere4d87aa2006-12-23 06:05:41 +00005381 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005382 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005383 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5384 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005385 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5386 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005387 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005388 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005389 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005390
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005391 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005392 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005393 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005394 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005395 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005396 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005397 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005398 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005399 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005400 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005401 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005402 Constant *C = ConstantInt::get(*Context,
5403 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005404 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005405
Chris Lattner7c4049c2004-01-12 19:35:11 +00005406 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005407 } else if (Op0I->getOpcode() == Instruction::Or) {
5408 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005409 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005410 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005411 // Anything in both C1 and C2 is known to be zero, remove it from
5412 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005413 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5414 NewRHS = ConstantExpr::getAnd(NewRHS,
5415 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005416 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005417 I.setOperand(0, Op0I->getOperand(0));
5418 I.setOperand(1, NewRHS);
5419 return &I;
5420 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005421 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005422 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005423 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005424
5425 // Try to fold constant and into select arguments.
5426 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005427 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005428 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005429 if (isa<PHINode>(Op0))
5430 if (Instruction *NV = FoldOpIntoPhi(I))
5431 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005432 }
5433
Dan Gohman186a6362009-08-12 16:04:34 +00005434 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005435 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005436 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005437
Dan Gohman186a6362009-08-12 16:04:34 +00005438 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005439 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005440 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005441
Chris Lattner318bf792007-03-18 22:51:34 +00005442
5443 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5444 if (Op1I) {
5445 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005446 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005447 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005448 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005449 I.swapOperands();
5450 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005451 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005452 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005453 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005454 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005455 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005456 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005457 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005458 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005459 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005460 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005461 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005462 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005463 std::swap(A, B);
5464 }
Chris Lattner318bf792007-03-18 22:51:34 +00005465 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005466 I.swapOperands(); // Simplified below.
5467 std::swap(Op0, Op1);
5468 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005469 }
Chris Lattner318bf792007-03-18 22:51:34 +00005470 }
5471
5472 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5473 if (Op0I) {
5474 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005475 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005476 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005477 if (A == Op1) // (B|A)^B == (A|B)^B
5478 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005479 if (B == Op1) // (A|B)^B == A & ~B
5480 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005481 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005482 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005483 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005484 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005485 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005486 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005487 if (A == Op1) // (A&B)^A -> (B&A)^A
5488 std::swap(A, B);
5489 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005490 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005491 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005492 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005493 }
Chris Lattner318bf792007-03-18 22:51:34 +00005494 }
5495
5496 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5497 if (Op0I && Op1I && Op0I->isShift() &&
5498 Op0I->getOpcode() == Op1I->getOpcode() &&
5499 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5500 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005501 Value *NewOp =
5502 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5503 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005504 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005505 Op1I->getOperand(1));
5506 }
5507
5508 if (Op0I && Op1I) {
5509 Value *A, *B, *C, *D;
5510 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005511 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5512 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005513 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005514 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005515 }
5516 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005517 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5518 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005519 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005520 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005521 }
5522
5523 // (A & B)^(C & D)
5524 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005525 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5526 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005527 // (X & Y)^(X & Y) -> (Y^Z) & X
5528 Value *X = 0, *Y = 0, *Z = 0;
5529 if (A == C)
5530 X = A, Y = B, Z = D;
5531 else if (A == D)
5532 X = A, Y = B, Z = C;
5533 else if (B == C)
5534 X = B, Y = A, Z = D;
5535 else if (B == D)
5536 X = B, Y = A, Z = C;
5537
5538 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005539 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005540 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005541 }
5542 }
5543 }
5544
Reid Spencere4d87aa2006-12-23 06:05:41 +00005545 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5546 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005547 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005548 return R;
5549
Chris Lattner6fc205f2006-05-05 06:39:07 +00005550 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005551 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005552 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005553 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5554 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005555 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005556 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005557 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5558 I.getType(), TD) &&
5559 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5560 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005561 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5562 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005563 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005564 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005565 }
Chris Lattner99c65742007-10-24 05:38:08 +00005566 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005567
Chris Lattner7e708292002-06-25 16:13:24 +00005568 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005569}
5570
Owen Andersond672ecb2009-07-03 00:17:18 +00005571static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005572 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005573 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005574}
Chris Lattnera96879a2004-09-29 17:40:11 +00005575
Dan Gohman6de29f82009-06-15 22:12:54 +00005576static bool HasAddOverflow(ConstantInt *Result,
5577 ConstantInt *In1, ConstantInt *In2,
5578 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005579 if (IsSigned)
5580 if (In2->getValue().isNegative())
5581 return Result->getValue().sgt(In1->getValue());
5582 else
5583 return Result->getValue().slt(In1->getValue());
5584 else
5585 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005586}
5587
Dan Gohman6de29f82009-06-15 22:12:54 +00005588/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005589/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005590static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005591 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005592 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005593 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005594
Dan Gohman6de29f82009-06-15 22:12:54 +00005595 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5596 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005597 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005598 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5599 ExtractElement(In1, Idx, Context),
5600 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005601 IsSigned))
5602 return true;
5603 }
5604 return false;
5605 }
5606
5607 return HasAddOverflow(cast<ConstantInt>(Result),
5608 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5609 IsSigned);
5610}
5611
5612static bool HasSubOverflow(ConstantInt *Result,
5613 ConstantInt *In1, ConstantInt *In2,
5614 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005615 if (IsSigned)
5616 if (In2->getValue().isNegative())
5617 return Result->getValue().slt(In1->getValue());
5618 else
5619 return Result->getValue().sgt(In1->getValue());
5620 else
5621 return Result->getValue().ugt(In1->getValue());
5622}
5623
Dan Gohman6de29f82009-06-15 22:12:54 +00005624/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5625/// overflowed for this type.
5626static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005627 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005628 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005629 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005630
5631 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5632 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005633 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005634 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5635 ExtractElement(In1, Idx, Context),
5636 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005637 IsSigned))
5638 return true;
5639 }
5640 return false;
5641 }
5642
5643 return HasSubOverflow(cast<ConstantInt>(Result),
5644 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5645 IsSigned);
5646}
5647
Chris Lattner10c0d912008-04-22 02:53:33 +00005648
Reid Spencere4d87aa2006-12-23 06:05:41 +00005649/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005650/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005651Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652 ICmpInst::Predicate Cond,
5653 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005654 // Look through bitcasts.
5655 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5656 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005657
Chris Lattner574da9b2005-01-13 20:14:25 +00005658 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005659 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005660 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005661 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005662 // know pointers can't overflow since the gep is inbounds. See if we can
5663 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005664 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5665
5666 // If not, synthesize the offset the hard way.
5667 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005668 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005669 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005670 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005671 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005672 // If the base pointers are different, but the indices are the same, just
5673 // compare the base pointer.
5674 if (PtrBase != GEPRHS->getOperand(0)) {
5675 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005676 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005677 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005678 if (IndicesTheSame)
5679 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5680 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5681 IndicesTheSame = false;
5682 break;
5683 }
5684
5685 // If all indices are the same, just compare the base pointers.
5686 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005687 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005688 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005689
5690 // Otherwise, the base pointers are different and the indices are
5691 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005692 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005693 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005694
Chris Lattnere9d782b2005-01-13 22:25:21 +00005695 // If one of the GEPs has all zero indices, recurse.
5696 bool AllZeros = true;
5697 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5698 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5699 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5700 AllZeros = false;
5701 break;
5702 }
5703 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005704 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5705 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005706
5707 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005708 AllZeros = true;
5709 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5710 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5711 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5712 AllZeros = false;
5713 break;
5714 }
5715 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005716 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005717
Chris Lattner4401c9c2005-01-14 00:20:05 +00005718 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5719 // If the GEPs only differ by one index, compare it.
5720 unsigned NumDifferences = 0; // Keep track of # differences.
5721 unsigned DiffOperand = 0; // The operand that differs.
5722 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5723 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005724 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5725 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005726 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005727 NumDifferences = 2;
5728 break;
5729 } else {
5730 if (NumDifferences++) break;
5731 DiffOperand = i;
5732 }
5733 }
5734
5735 if (NumDifferences == 0) // SAME GEP?
5736 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005737 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005738 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005739
Chris Lattner4401c9c2005-01-14 00:20:05 +00005740 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005741 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5742 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005743 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005744 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005745 }
5746 }
5747
Reid Spencere4d87aa2006-12-23 06:05:41 +00005748 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005749 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005750 if (TD &&
5751 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005752 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5753 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005754 Value *L = EmitGEPOffset(GEPLHS, *this);
5755 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005756 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005757 }
5758 }
5759 return 0;
5760}
5761
Chris Lattnera5406232008-05-19 20:18:56 +00005762/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5763///
5764Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5765 Instruction *LHSI,
5766 Constant *RHSC) {
5767 if (!isa<ConstantFP>(RHSC)) return 0;
5768 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5769
5770 // Get the width of the mantissa. We don't want to hack on conversions that
5771 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005772 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005773 if (MantissaWidth == -1) return 0; // Unknown.
5774
5775 // Check to see that the input is converted from an integer type that is small
5776 // enough that preserves all bits. TODO: check here for "known" sign bits.
5777 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005778 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005779
5780 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005781 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5782 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005783 ++InputSize;
5784
5785 // If the conversion would lose info, don't hack on this.
5786 if ((int)InputSize > MantissaWidth)
5787 return 0;
5788
5789 // Otherwise, we can potentially simplify the comparison. We know that it
5790 // will always come through as an integer value and we know the constant is
5791 // not a NAN (it would have been previously simplified).
5792 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5793
5794 ICmpInst::Predicate Pred;
5795 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005796 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005797 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005798 case FCmpInst::FCMP_OEQ:
5799 Pred = ICmpInst::ICMP_EQ;
5800 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005801 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005802 case FCmpInst::FCMP_OGT:
5803 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5804 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005805 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005806 case FCmpInst::FCMP_OGE:
5807 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5808 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005809 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005810 case FCmpInst::FCMP_OLT:
5811 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5812 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005813 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005814 case FCmpInst::FCMP_OLE:
5815 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5816 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005817 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005818 case FCmpInst::FCMP_ONE:
5819 Pred = ICmpInst::ICMP_NE;
5820 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005821 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005822 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005823 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005824 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005825 }
5826
5827 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5828
5829 // Now we know that the APFloat is a normal number, zero or inf.
5830
Chris Lattner85162782008-05-20 03:50:52 +00005831 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005832 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005833 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005834
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005835 if (!LHSUnsigned) {
5836 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5837 // and large values.
5838 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5839 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5840 APFloat::rmNearestTiesToEven);
5841 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5842 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5843 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005844 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5845 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005846 }
5847 } else {
5848 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5849 // +INF and large values.
5850 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5851 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5852 APFloat::rmNearestTiesToEven);
5853 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5854 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5855 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005856 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5857 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005858 }
Chris Lattnera5406232008-05-19 20:18:56 +00005859 }
5860
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005861 if (!LHSUnsigned) {
5862 // See if the RHS value is < SignedMin.
5863 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5864 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5865 APFloat::rmNearestTiesToEven);
5866 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5867 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5868 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005869 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5870 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005871 }
Chris Lattnera5406232008-05-19 20:18:56 +00005872 }
5873
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005874 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5875 // [0, UMAX], but it may still be fractional. See if it is fractional by
5876 // casting the FP value to the integer value and back, checking for equality.
5877 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005878 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005879 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5880 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005881 if (!RHS.isZero()) {
5882 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005883 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5884 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005885 if (!Equal) {
5886 // If we had a comparison against a fractional value, we have to adjust
5887 // the compare predicate and sometimes the value. RHSC is rounded towards
5888 // zero at this point.
5889 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005890 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005891 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005892 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005893 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005894 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005895 case ICmpInst::ICMP_ULE:
5896 // (float)int <= 4.4 --> int <= 4
5897 // (float)int <= -4.4 --> false
5898 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005900 break;
5901 case ICmpInst::ICMP_SLE:
5902 // (float)int <= 4.4 --> int <= 4
5903 // (float)int <= -4.4 --> int < -4
5904 if (RHS.isNegative())
5905 Pred = ICmpInst::ICMP_SLT;
5906 break;
5907 case ICmpInst::ICMP_ULT:
5908 // (float)int < -4.4 --> false
5909 // (float)int < 4.4 --> int <= 4
5910 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005911 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005912 Pred = ICmpInst::ICMP_ULE;
5913 break;
5914 case ICmpInst::ICMP_SLT:
5915 // (float)int < -4.4 --> int < -4
5916 // (float)int < 4.4 --> int <= 4
5917 if (!RHS.isNegative())
5918 Pred = ICmpInst::ICMP_SLE;
5919 break;
5920 case ICmpInst::ICMP_UGT:
5921 // (float)int > 4.4 --> int > 4
5922 // (float)int > -4.4 --> true
5923 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005924 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005925 break;
5926 case ICmpInst::ICMP_SGT:
5927 // (float)int > 4.4 --> int > 4
5928 // (float)int > -4.4 --> int >= -4
5929 if (RHS.isNegative())
5930 Pred = ICmpInst::ICMP_SGE;
5931 break;
5932 case ICmpInst::ICMP_UGE:
5933 // (float)int >= -4.4 --> true
5934 // (float)int >= 4.4 --> int > 4
5935 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005936 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005937 Pred = ICmpInst::ICMP_UGT;
5938 break;
5939 case ICmpInst::ICMP_SGE:
5940 // (float)int >= -4.4 --> int >= -4
5941 // (float)int >= 4.4 --> int > 4
5942 if (!RHS.isNegative())
5943 Pred = ICmpInst::ICMP_SGT;
5944 break;
5945 }
Chris Lattnera5406232008-05-19 20:18:56 +00005946 }
5947 }
5948
5949 // Lower this FP comparison into an appropriate integer version of the
5950 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005951 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005952}
5953
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005955 bool Changed = false;
5956
5957 /// Orders the operands of the compare so that they are listed from most
5958 /// complex to least complex. This puts constants before unary operators,
5959 /// before binary operators.
5960 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5961 I.swapOperands();
5962 Changed = true;
5963 }
5964
Chris Lattner8b170942002-08-09 23:47:40 +00005965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00005966
Chris Lattner210c5d42009-11-09 23:55:12 +00005967 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5968 return ReplaceInstUsesWith(I, V);
5969
Chris Lattner58e97462007-01-14 19:42:17 +00005970 // Simplify 'fcmp pred X, X'
5971 if (Op0 == Op1) {
5972 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005973 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005974 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5975 case FCmpInst::FCMP_ULT: // True if unordered or less than
5976 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5977 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5978 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5979 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005980 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005981 return &I;
5982
5983 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5984 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5985 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5986 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5987 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5988 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005989 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005990 return &I;
5991 }
5992 }
5993
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 // Handle fcmp with constant RHS
5995 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5996 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5997 switch (LHSI->getOpcode()) {
5998 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005999 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6000 // block. If in the same block, we're encouraging jump threading. If
6001 // not, we are just pessimizing the code by making an i1 phi.
6002 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006003 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006004 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006005 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006006 case Instruction::SIToFP:
6007 case Instruction::UIToFP:
6008 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6009 return NV;
6010 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006011 case Instruction::Select:
6012 // If either operand of the select is a constant, we can fold the
6013 // comparison into the select arms, which will cause one to be
6014 // constant folded and the select turned into a bitwise or.
6015 Value *Op1 = 0, *Op2 = 0;
6016 if (LHSI->hasOneUse()) {
6017 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6018 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006019 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006020 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006021 Op2 = Builder->CreateFCmp(I.getPredicate(),
6022 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006023 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6024 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006025 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006026 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006027 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6028 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029 }
6030 }
6031
6032 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006033 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006034 break;
6035 }
6036 }
6037
6038 return Changed ? &I : 0;
6039}
6040
6041Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006042 bool Changed = false;
6043
6044 /// Orders the operands of the compare so that they are listed from most
6045 /// complex to least complex. This puts constants before unary operators,
6046 /// before binary operators.
6047 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6048 I.swapOperands();
6049 Changed = true;
6050 }
6051
Reid Spencere4d87aa2006-12-23 06:05:41 +00006052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006053
Chris Lattner210c5d42009-11-09 23:55:12 +00006054 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6055 return ReplaceInstUsesWith(I, V);
6056
6057 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006058
Reid Spencere4d87aa2006-12-23 06:05:41 +00006059 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006060 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006061 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006062 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006063 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006064 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006065 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006066 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006067 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006068 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006069
Reid Spencere4d87aa2006-12-23 06:05:41 +00006070 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006071 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006072 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006073 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006074 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006075 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006076 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006077 case ICmpInst::ICMP_SGT:
6078 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006079 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006080 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006081 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006082 return BinaryOperator::CreateAnd(Not, Op0);
6083 }
6084 case ICmpInst::ICMP_UGE:
6085 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6086 // FALL THROUGH
6087 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006088 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006089 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006090 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006091 case ICmpInst::ICMP_SGE:
6092 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6093 // FALL THROUGH
6094 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006095 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006096 return BinaryOperator::CreateOr(Not, Op0);
6097 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006098 }
Chris Lattner8b170942002-08-09 23:47:40 +00006099 }
6100
Dan Gohman1c8491e2009-04-25 17:12:48 +00006101 unsigned BitWidth = 0;
6102 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006103 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6104 else if (Ty->isIntOrIntVector())
6105 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106
6107 bool isSignBit = false;
6108
Dan Gohman81b28ce2008-09-16 18:46:06 +00006109 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006111 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006112
Chris Lattnerb6566012008-01-05 01:18:20 +00006113 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6114 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006115 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006116 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006117 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006118 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006119
Dan Gohman81b28ce2008-09-16 18:46:06 +00006120 // If we have an icmp le or icmp ge instruction, turn it into the
6121 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006122 // them being folded in the code below. The SimplifyICmpInst code has
6123 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006124 switch (I.getPredicate()) {
6125 default: break;
6126 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006127 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006128 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006129 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006130 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006131 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006132 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006133 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006134 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006135 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006136 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006137 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006138 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006139 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006140 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006141 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006142 }
6143
Chris Lattner183661e2008-07-11 05:40:05 +00006144 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006145 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006146 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6148 }
6149
6150 // See if we can fold the comparison based on range information we can get
6151 // by checking whether bits are known to be zero or one in the input.
6152 if (BitWidth != 0) {
6153 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6154 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6155
6156 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006157 isSignBit ? APInt::getSignBit(BitWidth)
6158 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006160 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (SimplifyDemandedBits(I.getOperandUse(1),
6162 APInt::getAllOnesValue(BitWidth),
6163 Op1KnownZero, Op1KnownOne, 0))
6164 return &I;
6165
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006166 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006167 // in. Compute the Min, Max and RHS values based on the known bits. For the
6168 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6170 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006171 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6173 Op0Min, Op0Max);
6174 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6175 Op1Min, Op1Max);
6176 } else {
6177 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6178 Op0Min, Op0Max);
6179 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6180 Op1Min, Op1Max);
6181 }
6182
Chris Lattner183661e2008-07-11 05:40:05 +00006183 // If Min and Max are known to be the same, then SimplifyDemandedBits
6184 // figured out that the LHS is a constant. Just constant fold this now so
6185 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006187 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006188 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006189 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006190 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006191 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192
Chris Lattner183661e2008-07-11 05:40:05 +00006193 // Based on the range information we know about the LHS, see if we can
6194 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006195 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006196 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006197 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006200 break;
6201 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006203 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006204 break;
6205 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006207 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006209 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006211 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6213 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006214 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006215 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216
6217 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6218 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006219 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006220 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 }
Chris Lattner84dff672008-07-11 05:08:55 +00006222 break;
6223 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006227 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006228
6229 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006230 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6232 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006233 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006234 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235
6236 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6237 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006238 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006239 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 }
Chris Lattner84dff672008-07-11 05:08:55 +00006241 break;
6242 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006244 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006246 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006247 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006248 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006249 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6250 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006251 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006252 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253 }
Chris Lattner84dff672008-07-11 05:08:55 +00006254 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255 case ICmpInst::ICMP_SGT:
6256 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006257 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006259 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260
6261 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006262 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006263 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6264 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006265 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006266 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006267 }
6268 break;
6269 case ICmpInst::ICMP_SGE:
6270 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6271 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006272 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006273 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006274 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006275 break;
6276 case ICmpInst::ICMP_SLE:
6277 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6278 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006279 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006280 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006281 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006282 break;
6283 case ICmpInst::ICMP_UGE:
6284 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6285 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006286 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006287 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006288 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006289 break;
6290 case ICmpInst::ICMP_ULE:
6291 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6292 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006293 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006294 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006295 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006296 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006297 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006298
6299 // Turn a signed comparison into an unsigned one if both operands
6300 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006301 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006302 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6303 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006304 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006305 }
6306
6307 // Test if the ICmpInst instruction is used exclusively by a select as
6308 // part of a minimum or maximum operation. If so, refrain from doing
6309 // any other folding. This helps out other analyses which understand
6310 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6311 // and CodeGen. And in this case, at least one of the comparison
6312 // operands has at least one user besides the compare (the select),
6313 // which would often largely negate the benefit of folding anyway.
6314 if (I.hasOneUse())
6315 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6316 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6317 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6318 return 0;
6319
6320 // See if we are doing a comparison between a constant and an instruction that
6321 // can be folded into the comparison.
6322 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006324 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006326 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006327 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6328 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006329 }
6330
Chris Lattner01deb9d2007-04-03 17:43:25 +00006331 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006332 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6333 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6334 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006335 case Instruction::GetElementPtr:
6336 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006337 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006338 bool isAllZeros = true;
6339 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6340 if (!isa<Constant>(LHSI->getOperand(i)) ||
6341 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6342 isAllZeros = false;
6343 break;
6344 }
6345 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006346 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006347 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006348 }
6349 break;
6350
Chris Lattner6970b662005-04-23 15:31:55 +00006351 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006352 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006353 // block. If in the same block, we're encouraging jump threading. If
6354 // not, we are just pessimizing the code by making an i1 phi.
6355 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006356 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006357 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006358 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006359 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006360 // If either operand of the select is a constant, we can fold the
6361 // comparison into the select arms, which will cause one to be
6362 // constant folded and the select turned into a bitwise or.
6363 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006364 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6365 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6366 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6367 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6368
6369 // We only want to perform this transformation if it will not lead to
6370 // additional code. This is true if either both sides of the select
6371 // fold to a constant (in which case the icmp is replaced with a select
6372 // which will usually simplify) or this is the only user of the
6373 // select (in which case we are trading a select+icmp for a simpler
6374 // select+icmp).
6375 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6376 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006377 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6378 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006379 if (!Op2)
6380 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6381 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006382 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006383 }
Chris Lattner6970b662005-04-23 15:31:55 +00006384 break;
6385 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006386 case Instruction::Call:
6387 // If we have (malloc != null), and if the malloc has a single use, we
6388 // can assume it is successful and remove the malloc.
6389 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6390 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006391 // Need to explicitly erase malloc call here, instead of adding it to
6392 // Worklist, because it won't get DCE'd from the Worklist since
6393 // isInstructionTriviallyDead() returns false for function calls.
6394 // It is OK to replace LHSI/MallocCall with Undef because the
6395 // instruction that uses it will be erased via Worklist.
6396 if (extractMallocCall(LHSI)) {
6397 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6398 EraseInstFromFunction(*LHSI);
6399 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006400 ConstantInt::get(Type::getInt1Ty(*Context),
6401 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006402 }
6403 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6404 if (MallocCall->hasOneUse()) {
6405 MallocCall->replaceAllUsesWith(
6406 UndefValue::get(MallocCall->getType()));
6407 EraseInstFromFunction(*MallocCall);
6408 Worklist.Add(LHSI); // The malloc's bitcast use.
6409 return ReplaceInstUsesWith(I,
6410 ConstantInt::get(Type::getInt1Ty(*Context),
6411 !I.isTrueWhenEqual()));
6412 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006413 }
6414 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006415 }
Chris Lattner6970b662005-04-23 15:31:55 +00006416 }
6417
Reid Spencere4d87aa2006-12-23 06:05:41 +00006418 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006419 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006420 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006421 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006422 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006423 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6424 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006425 return NI;
6426
Reid Spencere4d87aa2006-12-23 06:05:41 +00006427 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006428 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6429 // now.
6430 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6431 if (isa<PointerType>(Op0->getType()) &&
6432 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006433 // We keep moving the cast from the left operand over to the right
6434 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006435 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006436
Chris Lattner57d86372007-01-06 01:45:59 +00006437 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6438 // so eliminate it as well.
6439 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6440 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006441
Chris Lattnerde90b762003-11-03 04:25:02 +00006442 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006443 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006444 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006445 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006446 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006447 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006448 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006449 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006450 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006451 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006452 }
Chris Lattner57d86372007-01-06 01:45:59 +00006453 }
6454
6455 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006456 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006457 // This comes up when you have code like
6458 // int X = A < B;
6459 // if (X) ...
6460 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006461 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006462 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006463 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006464 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006465 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006466
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006467 // See if it's the same type of instruction on the left and right.
6468 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6469 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006470 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006471 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006472 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006473 default: break;
6474 case Instruction::Add:
6475 case Instruction::Sub:
6476 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006477 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006478 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006479 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006480 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6481 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6482 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006483 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006484 ? I.getUnsignedPredicate()
6485 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006486 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006487 Op1I->getOperand(0));
6488 }
6489
6490 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006491 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006492 ? I.getUnsignedPredicate()
6493 : I.getSignedPredicate();
6494 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006495 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006496 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006497 }
6498 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006499 break;
6500 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006501 if (!I.isEquality())
6502 break;
6503
Nick Lewycky5d52c452008-08-21 05:56:10 +00006504 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6505 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6506 // Mask = -1 >> count-trailing-zeros(Cst).
6507 if (!CI->isZero() && !CI->isOne()) {
6508 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006509 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006510 APInt::getLowBitsSet(AP.getBitWidth(),
6511 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006512 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006513 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6514 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006515 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006516 }
6517 }
6518 break;
6519 }
6520 }
6521 }
6522 }
6523
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006524 // ~x < ~y --> y < x
6525 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006526 if (match(Op0, m_Not(m_Value(A))) &&
6527 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006528 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006529 }
6530
Chris Lattner65b72ba2006-09-18 04:22:48 +00006531 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006532 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006533
6534 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006535 if (match(Op0, m_Neg(m_Value(A))) &&
6536 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006537 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006538
Dan Gohman4ae51262009-08-12 16:23:25 +00006539 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006540 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6541 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006542 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006543 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006544 }
6545
Dan Gohman4ae51262009-08-12 16:23:25 +00006546 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006547 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006548 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006549 if (match(B, m_ConstantInt(C1)) &&
6550 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006551 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006552 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006553 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6554 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006555 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006556
6557 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006558 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6559 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6560 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6561 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006562 }
6563 }
6564
Dan Gohman4ae51262009-08-12 16:23:25 +00006565 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006566 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006567 // A == (A^B) -> B == 0
6568 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006569 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006570 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006571 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006572
6573 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006574 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006575 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006576 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006577
6578 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006579 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006580 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006581 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006582
Chris Lattner9c2328e2006-11-14 06:06:06 +00006583 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6584 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006585 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6586 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006587 Value *X = 0, *Y = 0, *Z = 0;
6588
6589 if (A == C) {
6590 X = B; Y = D; Z = A;
6591 } else if (A == D) {
6592 X = B; Y = C; Z = A;
6593 } else if (B == C) {
6594 X = A; Y = D; Z = B;
6595 } else if (B == D) {
6596 X = A; Y = C; Z = B;
6597 }
6598
6599 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006600 Op1 = Builder->CreateXor(X, Y, "tmp");
6601 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006602 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006603 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006604 return &I;
6605 }
6606 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006607 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006608
6609 {
6610 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006611 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006612 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006613 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6614
Chris Lattner2799baf2009-12-21 03:19:28 +00006615 // icmp X, X+Cst
6616 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006617 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006618 }
Chris Lattner7e708292002-06-25 16:13:24 +00006619 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006620}
6621
Chris Lattner2799baf2009-12-21 03:19:28 +00006622/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6623Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6624 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006625 ICmpInst::Predicate Pred,
6626 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006627 // If we have X+0, exit early (simplifying logic below) and let it get folded
6628 // elsewhere. icmp X+0, X -> icmp X, X
6629 if (CI->isZero()) {
6630 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6631 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6632 }
6633
6634 // (X+4) == X -> false.
6635 if (Pred == ICmpInst::ICMP_EQ)
6636 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6637
6638 // (X+4) != X -> true.
6639 if (Pred == ICmpInst::ICMP_NE)
6640 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006641
6642 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6643 bool isNUW = false, isNSW = false;
6644 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6645 isNUW = Add->hasNoUnsignedWrap();
6646 isNSW = Add->hasNoSignedWrap();
6647 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006648
6649 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6650 // so the values can never be equal. Similiarly for all other "or equals"
6651 // operators.
6652
6653 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6654 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6655 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6656 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006657 // If this is an NUW add, then this is always false.
6658 if (isNUW)
6659 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6660
Chris Lattner2799baf2009-12-21 03:19:28 +00006661 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6662 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6663 }
6664
6665 // (X+1) >u X --> X <u (0-1) --> X != 255
6666 // (X+2) >u X --> X <u (0-2) --> X <u 254
6667 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006668 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6669 // If this is an NUW add, then this is always true.
6670 if (isNUW)
6671 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006672 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006673 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006674
6675 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6676 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6677 APInt::getSignedMaxValue(BitWidth));
6678
6679 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6680 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6681 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6682 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6683 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6684 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006685 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6686 // If this is an NSW add, then we have two cases: if the constant is
6687 // positive, then this is always false, if negative, this is always true.
6688 if (isNSW) {
6689 bool isTrue = CI->getValue().isNegative();
6690 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6691 }
6692
Chris Lattner2799baf2009-12-21 03:19:28 +00006693 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006694 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006695
6696 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6697 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6698 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6699 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6700 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6701 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006702
6703 // If this is an NSW add, then we have two cases: if the constant is
6704 // positive, then this is always true, if negative, this is always false.
6705 if (isNSW) {
6706 bool isTrue = !CI->getValue().isNegative();
6707 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6708 }
6709
Chris Lattner2799baf2009-12-21 03:19:28 +00006710 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6711 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6712 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6713}
Chris Lattner562ef782007-06-20 23:46:26 +00006714
6715/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6716/// and CmpRHS are both known to be integer constants.
6717Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6718 ConstantInt *DivRHS) {
6719 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6720 const APInt &CmpRHSV = CmpRHS->getValue();
6721
6722 // FIXME: If the operand types don't match the type of the divide
6723 // then don't attempt this transform. The code below doesn't have the
6724 // logic to deal with a signed divide and an unsigned compare (and
6725 // vice versa). This is because (x /s C1) <s C2 produces different
6726 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6727 // (x /u C1) <u C2. Simply casting the operands and result won't
6728 // work. :( The if statement below tests that condition and bails
6729 // if it finds it.
6730 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006731 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006732 return 0;
6733 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006734 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006735 if (DivIsSigned && DivRHS->isAllOnesValue())
6736 return 0; // The overflow computation also screws up here
6737 if (DivRHS->isOne())
6738 return 0; // Not worth bothering, and eliminates some funny cases
6739 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006740
6741 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6742 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6743 // C2 (CI). By solving for X we can turn this into a range check
6744 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006745 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006746
6747 // Determine if the product overflows by seeing if the product is
6748 // not equal to the divide. Make sure we do the same kind of divide
6749 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006750 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6751 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006752
6753 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006754 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006755
Chris Lattner1dbfd482007-06-21 18:11:19 +00006756 // Figure out the interval that is being checked. For example, a comparison
6757 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6758 // Compute this interval based on the constants involved and the signedness of
6759 // the compare/divide. This computes a half-open interval, keeping track of
6760 // whether either value in the interval overflows. After analysis each
6761 // overflow variable is set to 0 if it's corresponding bound variable is valid
6762 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6763 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006764 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006765
Chris Lattner562ef782007-06-20 23:46:26 +00006766 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006767 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006768 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006769 HiOverflow = LoOverflow = ProdOV;
6770 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006771 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006772 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006773 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006774 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006775 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006776 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006777 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006778 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6779 HiOverflow = LoOverflow = ProdOV;
6780 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006781 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006782 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006783 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006784 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006785 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6786 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006787 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006788 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006789 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006790 true) ? -1 : 0;
6791 }
Chris Lattner562ef782007-06-20 23:46:26 +00006792 }
Dan Gohman76491272008-02-13 22:09:18 +00006793 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006794 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006795 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006796 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006797 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006798 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6799 HiOverflow = 1; // [INTMIN+1, overflow)
6800 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6801 }
Dan Gohman76491272008-02-13 22:09:18 +00006802 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006803 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006804 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006805 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006806 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006807 LoOverflow = AddWithOverflow(LoBound, HiBound,
6808 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006809 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006810 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6811 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006812 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006813 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006814 }
6815
Chris Lattner1dbfd482007-06-21 18:11:19 +00006816 // Dividing by a negative swaps the condition. LT <-> GT
6817 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006818 }
6819
6820 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006821 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006822 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006823 case ICmpInst::ICMP_EQ:
6824 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006825 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006826 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006827 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006828 ICmpInst::ICMP_UGE, X, LoBound);
6829 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006830 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006831 ICmpInst::ICMP_ULT, X, HiBound);
6832 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006833 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006834 case ICmpInst::ICMP_NE:
6835 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006836 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006837 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006838 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006839 ICmpInst::ICMP_ULT, X, LoBound);
6840 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006841 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006842 ICmpInst::ICMP_UGE, X, HiBound);
6843 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006844 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006845 case ICmpInst::ICMP_ULT:
6846 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006847 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006848 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006849 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006850 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006851 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006852 case ICmpInst::ICMP_UGT:
6853 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006854 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006855 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006856 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006857 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006858 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006859 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006860 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006861 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006862 }
6863}
6864
6865
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6867///
6868Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6869 Instruction *LHSI,
6870 ConstantInt *RHS) {
6871 const APInt &RHSV = RHS->getValue();
6872
6873 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006874 case Instruction::Trunc:
6875 if (ICI.isEquality() && LHSI->hasOneUse()) {
6876 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6877 // of the high bits truncated out of x are known.
6878 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6879 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6880 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6881 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6882 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6883
6884 // If all the high bits are known, we can do this xform.
6885 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6886 // Pull in the high bits from known-ones set.
6887 APInt NewRHS(RHS->getValue());
6888 NewRHS.zext(SrcBits);
6889 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006890 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006891 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006892 }
6893 }
6894 break;
6895
Duncan Sands0091bf22007-04-04 06:42:45 +00006896 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006897 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6898 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6899 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006900 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6901 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006902 Value *CompareVal = LHSI->getOperand(0);
6903
6904 // If the sign bit of the XorCST is not set, there is no change to
6905 // the operation, just stop using the Xor.
6906 if (!XorCST->getValue().isNegative()) {
6907 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006908 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006909 return &ICI;
6910 }
6911
6912 // Was the old condition true if the operand is positive?
6913 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6914
6915 // If so, the new one isn't.
6916 isTrueIfPositive ^= true;
6917
6918 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006919 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006920 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006921 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006922 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006923 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006924 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006925
6926 if (LHSI->hasOneUse()) {
6927 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6928 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6929 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006930 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006931 ? ICI.getUnsignedPredicate()
6932 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006933 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006934 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006935 }
6936
6937 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006938 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006939 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006940 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006941 ? ICI.getUnsignedPredicate()
6942 : ICI.getSignedPredicate();
6943 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006944 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006945 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006946 }
6947 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006948 }
6949 break;
6950 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6951 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6952 LHSI->getOperand(0)->hasOneUse()) {
6953 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6954
6955 // If the LHS is an AND of a truncating cast, we can widen the
6956 // and/compare to be the input width without changing the value
6957 // produced, eliminating a cast.
6958 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6959 // We can do this transformation if either the AND constant does not
6960 // have its sign bit set or if it is an equality comparison.
6961 // Extending a relational comparison when we're checking the sign
6962 // bit would not work.
6963 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006964 (ICI.isEquality() ||
6965 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006966 uint32_t BitWidth =
6967 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6968 APInt NewCST = AndCST->getValue();
6969 NewCST.zext(BitWidth);
6970 APInt NewCI = RHSV;
6971 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006972 Value *NewAnd =
6973 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006974 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006975 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006976 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977 }
6978 }
6979
6980 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6981 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6982 // happens a LOT in code produced by the C front-end, for bitfield
6983 // access.
6984 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6985 if (Shift && !Shift->isShift())
6986 Shift = 0;
6987
6988 ConstantInt *ShAmt;
6989 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6990 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6991 const Type *AndTy = AndCST->getType(); // Type of the and.
6992
6993 // We can fold this as long as we can't shift unknown bits
6994 // into the mask. This can only happen with signed shift
6995 // rights, as they sign-extend.
6996 if (ShAmt) {
6997 bool CanFold = Shift->isLogicalShift();
6998 if (!CanFold) {
6999 // To test for the bad case of the signed shr, see if any
7000 // of the bits shifted in could be tested after the mask.
7001 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7002 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7003
7004 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7005 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7006 AndCST->getValue()) == 0)
7007 CanFold = true;
7008 }
7009
7010 if (CanFold) {
7011 Constant *NewCst;
7012 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007013 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007014 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007015 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007016
7017 // Check to see if we are shifting out any of the bits being
7018 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007019 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007020 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021 // If we shifted bits out, the fold is not going to work out.
7022 // As a special case, check to see if this means that the
7023 // result is always true or false now.
7024 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007025 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007026 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007027 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007028 } else {
7029 ICI.setOperand(1, NewCst);
7030 Constant *NewAndCST;
7031 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007032 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007033 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007034 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007035 LHSI->setOperand(1, NewAndCST);
7036 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007037 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038 return &ICI;
7039 }
7040 }
7041 }
7042
7043 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7044 // preferable because it allows the C<<Y expression to be hoisted out
7045 // of a loop if Y is invariant and X is not.
7046 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007047 ICI.isEquality() && !Shift->isArithmeticShift() &&
7048 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007049 // Compute C << Y.
7050 Value *NS;
7051 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007052 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007053 } else {
7054 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007055 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007056 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007057
7058 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007059 Value *NewAnd =
7060 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007061
7062 ICI.setOperand(0, NewAnd);
7063 return &ICI;
7064 }
7065 }
7066 break;
7067
Chris Lattnera0141b92007-07-15 20:42:37 +00007068 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7069 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7070 if (!ShAmt) break;
7071
7072 uint32_t TypeBits = RHSV.getBitWidth();
7073
7074 // Check that the shift amount is in range. If not, don't perform
7075 // undefined shifts. When the shift is visited it will be
7076 // simplified.
7077 if (ShAmt->uge(TypeBits))
7078 break;
7079
7080 if (ICI.isEquality()) {
7081 // If we are comparing against bits always shifted out, the
7082 // comparison cannot succeed.
7083 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007084 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007085 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007086 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7087 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007088 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007089 return ReplaceInstUsesWith(ICI, Cst);
7090 }
7091
7092 if (LHSI->hasOneUse()) {
7093 // Otherwise strength reduce the shift into an and.
7094 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7095 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007096 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007097 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098
Chris Lattner74381062009-08-30 07:44:24 +00007099 Value *And =
7100 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007101 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007102 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103 }
7104 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007105
7106 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7107 bool TrueIfSigned = false;
7108 if (LHSI->hasOneUse() &&
7109 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7110 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007111 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007112 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007113 Value *And =
7114 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007115 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007116 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007117 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007118 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007119 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007122 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007123 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007124 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007125 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007126
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007127 // Check that the shift amount is in range. If not, don't perform
7128 // undefined shifts. When the shift is visited it will be
7129 // simplified.
7130 uint32_t TypeBits = RHSV.getBitWidth();
7131 if (ShAmt->uge(TypeBits))
7132 break;
7133
7134 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007135
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007136 // If we are comparing against bits always shifted out, the
7137 // comparison cannot succeed.
7138 APInt Comp = RHSV << ShAmtVal;
7139 if (LHSI->getOpcode() == Instruction::LShr)
7140 Comp = Comp.lshr(ShAmtVal);
7141 else
7142 Comp = Comp.ashr(ShAmtVal);
7143
7144 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7145 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007146 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007147 return ReplaceInstUsesWith(ICI, Cst);
7148 }
7149
7150 // Otherwise, check to see if the bits shifted out are known to be zero.
7151 // If so, we can compare against the unshifted value:
7152 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007153 if (LHSI->hasOneUse() &&
7154 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007155 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007156 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007157 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007158 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007159
Evan Chengf30752c2008-04-23 00:38:06 +00007160 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007161 // Otherwise strength reduce the shift into an and.
7162 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007163 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007164
Chris Lattner74381062009-08-30 07:44:24 +00007165 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7166 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007167 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007168 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 }
7170 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007171 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172
7173 case Instruction::SDiv:
7174 case Instruction::UDiv:
7175 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7176 // Fold this div into the comparison, producing a range check.
7177 // Determine, based on the divide type, what the range is being
7178 // checked. If there is an overflow on the low or high side, remember
7179 // it, otherwise compute the range [low, hi) bounding the new value.
7180 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007181 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7182 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7183 DivRHS))
7184 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007186
7187 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007188 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007189 if (!ICI.isEquality()) {
7190 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7191 if (!LHSC) break;
7192 const APInt &LHSV = LHSC->getValue();
7193
7194 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7195 .subtract(LHSV);
7196
Nick Lewycky4a134af2009-10-25 05:20:17 +00007197 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007198 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007199 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007200 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007201 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007202 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007203 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007204 }
7205 } else {
7206 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007207 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007208 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007209 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007210 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007211 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007212 }
7213 }
7214 }
7215 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007216 }
7217
7218 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7219 if (ICI.isEquality()) {
7220 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7221
7222 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7223 // the second operand is a constant, simplify a bit.
7224 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7225 switch (BO->getOpcode()) {
7226 case Instruction::SRem:
7227 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7228 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7229 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7230 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007231 Value *NewRem =
7232 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7233 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007234 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007235 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007236 }
7237 }
7238 break;
7239 case Instruction::Add:
7240 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7241 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7242 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007243 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007244 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007245 } else if (RHSV == 0) {
7246 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7247 // efficiently invertible, or if the add has just this one use.
7248 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7249
Dan Gohman186a6362009-08-12 16:04:34 +00007250 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007251 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007252 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007253 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007254 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007255 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007256 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007257 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007258 }
7259 }
7260 break;
7261 case Instruction::Xor:
7262 // For the xor case, we can xor two constants together, eliminating
7263 // the explicit xor.
7264 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007265 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007266 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007267
7268 // FALLTHROUGH
7269 case Instruction::Sub:
7270 // Replace (([sub|xor] A, B) != 0) with (A != B)
7271 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007272 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007273 BO->getOperand(1));
7274 break;
7275
7276 case Instruction::Or:
7277 // If bits are being or'd in that are not present in the constant we
7278 // are comparing against, then the comparison could never succeed!
7279 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007280 Constant *NotCI = ConstantExpr::getNot(RHS);
7281 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007282 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007283 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007284 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007285 }
7286 break;
7287
7288 case Instruction::And:
7289 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7290 // If bits are being compared against that are and'd out, then the
7291 // comparison can never succeed!
7292 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007293 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007294 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007295 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007296
7297 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7298 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007299 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007300 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007301 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007302
7303 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007304 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007305 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007306 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007307 ICmpInst::Predicate pred = isICMP_NE ?
7308 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007309 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007310 }
7311
7312 // ((X & ~7) == 0) --> X < 8
7313 if (RHSV == 0 && isHighOnes(BOC)) {
7314 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007315 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007316 ICmpInst::Predicate pred = isICMP_NE ?
7317 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007318 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007319 }
7320 }
7321 default: break;
7322 }
7323 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7324 // Handle icmp {eq|ne} <intrinsic>, intcst.
7325 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007326 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007327 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007328 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007329 return &ICI;
7330 }
7331 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007332 }
7333 return 0;
7334}
7335
7336/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7337/// We only handle extending casts so far.
7338///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007339Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7340 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007341 Value *LHSCIOp = LHSCI->getOperand(0);
7342 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007343 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007344 Value *RHSCIOp;
7345
Chris Lattner8c756c12007-05-05 22:41:33 +00007346 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7347 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007348 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7349 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007350 cast<IntegerType>(DestTy)->getBitWidth()) {
7351 Value *RHSOp = 0;
7352 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007353 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007354 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7355 RHSOp = RHSC->getOperand(0);
7356 // If the pointer types don't match, insert a bitcast.
7357 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007358 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007359 }
7360
7361 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007362 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007363 }
7364
7365 // The code below only handles extension cast instructions, so far.
7366 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007367 if (LHSCI->getOpcode() != Instruction::ZExt &&
7368 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007369 return 0;
7370
Reid Spencere4d87aa2006-12-23 06:05:41 +00007371 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007372 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007373
Reid Spencere4d87aa2006-12-23 06:05:41 +00007374 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007375 // Not an extension from the same type?
7376 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007377 if (RHSCIOp->getType() != LHSCIOp->getType())
7378 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007379
Nick Lewycky4189a532008-01-28 03:48:02 +00007380 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007381 // and the other is a zext), then we can't handle this.
7382 if (CI->getOpcode() != LHSCI->getOpcode())
7383 return 0;
7384
Nick Lewycky4189a532008-01-28 03:48:02 +00007385 // Deal with equality cases early.
7386 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007387 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007388
7389 // A signed comparison of sign extended values simplifies into a
7390 // signed comparison.
7391 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007392 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007393
7394 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007395 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007396 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007397
Reid Spencere4d87aa2006-12-23 06:05:41 +00007398 // If we aren't dealing with a constant on the RHS, exit early
7399 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7400 if (!CI)
7401 return 0;
7402
7403 // Compute the constant that would happen if we truncated to SrcTy then
7404 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007405 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7406 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007407 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007408
7409 // If the re-extended constant didn't change...
7410 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007411 // Deal with equality cases early.
7412 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007413 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007414
7415 // A signed comparison of sign extended values simplifies into a
7416 // signed comparison.
7417 if (isSignedExt && isSignedCmp)
7418 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7419
7420 // The other three cases all fold into an unsigned comparison.
7421 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007422 }
7423
7424 // The re-extended constant changed so the constant cannot be represented
7425 // in the shorter type. Consequently, we cannot emit a simple comparison.
7426
7427 // First, handle some easy cases. We know the result cannot be equal at this
7428 // point so handle the ICI.isEquality() cases
7429 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007430 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007431 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007432 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007433
7434 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7435 // should have been folded away previously and not enter in here.
7436 Value *Result;
7437 if (isSignedCmp) {
7438 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007439 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007440 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007441 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007442 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007443 } else {
7444 // We're performing an unsigned comparison.
7445 if (isSignedExt) {
7446 // We're performing an unsigned comp with a sign extended value.
7447 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007448 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007449 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007450 } else {
7451 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007452 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007453 }
7454 }
7455
7456 // Finally, return the value computed.
7457 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007458 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007459 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007460
7461 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7462 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7463 "ICmp should be folded!");
7464 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007465 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007466 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007467}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007468
Reid Spencer832254e2007-02-02 02:16:23 +00007469Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7470 return commonShiftTransforms(I);
7471}
7472
7473Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7474 return commonShiftTransforms(I);
7475}
7476
7477Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007478 if (Instruction *R = commonShiftTransforms(I))
7479 return R;
7480
7481 Value *Op0 = I.getOperand(0);
7482
7483 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7484 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7485 if (CSI->isAllOnesValue())
7486 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007487
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007488 // See if we can turn a signed shr into an unsigned shr.
7489 if (MaskedValueIsZero(Op0,
7490 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7491 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7492
7493 // Arithmetic shifting an all-sign-bit value is a no-op.
7494 unsigned NumSignBits = ComputeNumSignBits(Op0);
7495 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7496 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007497
Chris Lattner348f6652007-12-06 01:59:46 +00007498 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007499}
7500
7501Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7502 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007503 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007504
7505 // shl X, 0 == X and shr X, 0 == X
7506 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007507 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7508 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007509 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007510
Reid Spencere4d87aa2006-12-23 06:05:41 +00007511 if (isa<UndefValue>(Op0)) {
7512 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007513 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007514 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007515 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007516 }
7517 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007518 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7519 return ReplaceInstUsesWith(I, Op0);
7520 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007521 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007522 }
7523
Dan Gohman9004c8a2009-05-21 02:28:33 +00007524 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007525 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007526 return &I;
7527
Chris Lattner2eefe512004-04-09 19:05:30 +00007528 // Try to fold constant and into select arguments.
7529 if (isa<Constant>(Op0))
7530 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007531 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007532 return R;
7533
Reid Spencerb83eb642006-10-20 07:07:24 +00007534 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007535 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7536 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007537 return 0;
7538}
7539
Reid Spencerb83eb642006-10-20 07:07:24 +00007540Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007541 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007542 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007543
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007544 // See if we can simplify any instructions used by the instruction whose sole
7545 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007546 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007547
Dan Gohmana119de82009-06-14 23:30:43 +00007548 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7549 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007550 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007551 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007552 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007553 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007554 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007555 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007556 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007557 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007558 }
7559
7560 // ((X*C1) << C2) == (X * (C1 << C2))
7561 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7562 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7563 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007565 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007566
7567 // Try to fold constant and into select arguments.
7568 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7569 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7570 return R;
7571 if (isa<PHINode>(Op0))
7572 if (Instruction *NV = FoldOpIntoPhi(I))
7573 return NV;
7574
Chris Lattner8999dd32007-12-22 09:07:47 +00007575 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7576 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7577 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7578 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7579 // place. Don't try to do this transformation in this case. Also, we
7580 // require that the input operand is a shift-by-constant so that we have
7581 // confidence that the shifts will get folded together. We could do this
7582 // xform in more cases, but it is unlikely to be profitable.
7583 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7584 isa<ConstantInt>(TrOp->getOperand(1))) {
7585 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007586 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007587 // (shift2 (shift1 & 0x00FF), c2)
7588 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007589
7590 // For logical shifts, the truncation has the effect of making the high
7591 // part of the register be zeros. Emulate this by inserting an AND to
7592 // clear the top bits as needed. This 'and' will usually be zapped by
7593 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007594 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7595 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007596 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7597
7598 // The mask we constructed says what the trunc would do if occurring
7599 // between the shifts. We want to know the effect *after* the second
7600 // shift. We know that it is a logical shift by a constant, so adjust the
7601 // mask as appropriate.
7602 if (I.getOpcode() == Instruction::Shl)
7603 MaskV <<= Op1->getZExtValue();
7604 else {
7605 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7606 MaskV = MaskV.lshr(Op1->getZExtValue());
7607 }
7608
Chris Lattner74381062009-08-30 07:44:24 +00007609 // shift1 & 0x00FF
7610 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7611 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007612
7613 // Return the value truncated to the interesting size.
7614 return new TruncInst(And, I.getType());
7615 }
7616 }
7617
Chris Lattner4d5542c2006-01-06 07:12:35 +00007618 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007619 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7620 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7621 Value *V1, *V2;
7622 ConstantInt *CC;
7623 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007624 default: break;
7625 case Instruction::Add:
7626 case Instruction::And:
7627 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007628 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007629 // These operators commute.
7630 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007631 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007632 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007633 m_Specific(Op1)))) {
7634 Value *YS = // (Y << C)
7635 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7636 // (X + (Y << C))
7637 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7638 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007639 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007640 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007641 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007642 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007643
Chris Lattner150f12a2005-09-18 06:30:59 +00007644 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007645 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007646 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007647 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007648 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007649 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007650 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007651 Value *YS = // (Y << C)
7652 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7653 Op0BO->getName());
7654 // X & (CC << C)
7655 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7656 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007657 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007658 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007659 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007660
Reid Spencera07cb7d2007-02-02 14:41:37 +00007661 // FALL THROUGH.
7662 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007663 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007664 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007665 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007666 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007667 Value *YS = // (Y << C)
7668 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7669 // (X + (Y << C))
7670 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7671 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007672 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007673 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007674 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007675 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007676
Chris Lattner13d4ab42006-05-31 21:14:00 +00007677 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007678 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7679 match(Op0BO->getOperand(0),
7680 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007681 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007682 cast<BinaryOperator>(Op0BO->getOperand(0))
7683 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007684 Value *YS = // (Y << C)
7685 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7686 // X & (CC << C)
7687 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7688 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007689
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007690 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007691 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007692
Chris Lattner11021cb2005-09-18 05:12:10 +00007693 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007694 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007695 }
7696
7697
7698 // If the operand is an bitwise operator with a constant RHS, and the
7699 // shift is the only use, we can pull it out of the shift.
7700 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7701 bool isValid = true; // Valid only for And, Or, Xor
7702 bool highBitSet = false; // Transform if high bit of constant set?
7703
7704 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007705 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007706 case Instruction::Add:
7707 isValid = isLeftShift;
7708 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007709 case Instruction::Or:
7710 case Instruction::Xor:
7711 highBitSet = false;
7712 break;
7713 case Instruction::And:
7714 highBitSet = true;
7715 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007716 }
7717
7718 // If this is a signed shift right, and the high bit is modified
7719 // by the logical operation, do not perform the transformation.
7720 // The highBitSet boolean indicates the value of the high bit of
7721 // the constant which would cause it to be modified for this
7722 // operation.
7723 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007724 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007725 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007726
7727 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007728 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007729
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007730 Value *NewShift =
7731 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007732 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007733
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007734 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007735 NewRHS);
7736 }
7737 }
7738 }
7739 }
7740
Chris Lattnerad0124c2006-01-06 07:52:12 +00007741 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007742 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7743 if (ShiftOp && !ShiftOp->isShift())
7744 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007745
Reid Spencerb83eb642006-10-20 07:07:24 +00007746 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007747 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007748 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7749 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007750 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7751 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7752 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007753
Zhou Sheng4351c642007-04-02 08:20:41 +00007754 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007755
7756 const IntegerType *Ty = cast<IntegerType>(I.getType());
7757
7758 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007759 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007760 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7761 // saturates.
7762 if (AmtSum >= TypeBits) {
7763 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007764 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007765 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7766 }
7767
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007768 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007769 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007770 }
7771
7772 if (ShiftOp->getOpcode() == Instruction::LShr &&
7773 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007774 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007775 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007776
Chris Lattnerb87056f2007-02-05 00:57:54 +00007777 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007778 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007779 }
7780
7781 if (ShiftOp->getOpcode() == Instruction::AShr &&
7782 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007783 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007784 if (AmtSum >= TypeBits)
7785 AmtSum = TypeBits-1;
7786
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007787 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007788
Zhou Shenge9e03f62007-03-28 15:02:20 +00007789 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007790 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007791 }
7792
Chris Lattnerb87056f2007-02-05 00:57:54 +00007793 // Okay, if we get here, one shift must be left, and the other shift must be
7794 // right. See if the amounts are equal.
7795 if (ShiftAmt1 == ShiftAmt2) {
7796 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7797 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007798 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007799 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007800 }
7801 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7802 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007803 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007804 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007805 }
7806 // We can simplify ((X << C) >>s C) into a trunc + sext.
7807 // NOTE: we could do this for any C, but that would make 'unusual' integer
7808 // types. For now, just stick to ones well-supported by the code
7809 // generators.
7810 const Type *SExtType = 0;
7811 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007812 case 1 :
7813 case 8 :
7814 case 16 :
7815 case 32 :
7816 case 64 :
7817 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007818 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007819 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007820 default: break;
7821 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007822 if (SExtType)
7823 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007824 // Otherwise, we can't handle it yet.
7825 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007826 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007827
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007828 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007829 if (I.getOpcode() == Instruction::Shl) {
7830 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7831 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007832 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007833
Reid Spencer55702aa2007-03-25 21:11:44 +00007834 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007835 return BinaryOperator::CreateAnd(Shift,
7836 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007837 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007838
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007839 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007840 if (I.getOpcode() == Instruction::LShr) {
7841 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007842 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007843
Reid Spencerd5e30f02007-03-26 17:18:58 +00007844 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007845 return BinaryOperator::CreateAnd(Shift,
7846 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007847 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007848
7849 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7850 } else {
7851 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007852 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007853
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007854 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007855 if (I.getOpcode() == Instruction::Shl) {
7856 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7857 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007858 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7859 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007860
Reid Spencer55702aa2007-03-25 21:11:44 +00007861 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007862 return BinaryOperator::CreateAnd(Shift,
7863 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007864 }
7865
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007866 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007867 if (I.getOpcode() == Instruction::LShr) {
7868 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007869 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007870
Reid Spencer68d27cf2007-03-26 23:45:51 +00007871 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007872 return BinaryOperator::CreateAnd(Shift,
7873 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007874 }
7875
7876 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007877 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007878 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007879 return 0;
7880}
7881
Chris Lattnera1be5662002-05-02 17:06:02 +00007882
Chris Lattnercfd65102005-10-29 04:36:15 +00007883/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7884/// expression. If so, decompose it, returning some value X, such that Val is
7885/// X*Scale+Offset.
7886///
7887static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007888 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007889 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7890 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007891 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007892 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007893 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007894 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007895 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7896 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7897 if (I->getOpcode() == Instruction::Shl) {
7898 // This is a value scaled by '1 << the shift amt'.
7899 Scale = 1U << RHS->getZExtValue();
7900 Offset = 0;
7901 return I->getOperand(0);
7902 } else if (I->getOpcode() == Instruction::Mul) {
7903 // This value is scaled by 'RHS'.
7904 Scale = RHS->getZExtValue();
7905 Offset = 0;
7906 return I->getOperand(0);
7907 } else if (I->getOpcode() == Instruction::Add) {
7908 // We have X+C. Check to see if we really have (X*C2)+C1,
7909 // where C1 is divisible by C2.
7910 unsigned SubScale;
7911 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007912 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7913 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007914 Offset += RHS->getZExtValue();
7915 Scale = SubScale;
7916 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007917 }
7918 }
7919 }
7920
7921 // Otherwise, we can't look past this.
7922 Scale = 1;
7923 Offset = 0;
7924 return Val;
7925}
7926
7927
Chris Lattnerb3f83972005-10-24 06:03:58 +00007928/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7929/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007930Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007931 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007932 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007933
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007934 BuilderTy AllocaBuilder(*Builder);
7935 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7936
Chris Lattnerb53c2382005-10-24 06:22:12 +00007937 // Remove any uses of AI that are dead.
7938 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007939
Chris Lattnerb53c2382005-10-24 06:22:12 +00007940 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7941 Instruction *User = cast<Instruction>(*UI++);
7942 if (isInstructionTriviallyDead(User)) {
7943 while (UI != E && *UI == User)
7944 ++UI; // If this instruction uses AI more than once, don't break UI.
7945
Chris Lattnerb53c2382005-10-24 06:22:12 +00007946 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007947 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007948 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007949 }
7950 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007951
7952 // This requires TargetData to get the alloca alignment and size information.
7953 if (!TD) return 0;
7954
Chris Lattnerb3f83972005-10-24 06:03:58 +00007955 // Get the type really allocated and the type casted to.
7956 const Type *AllocElTy = AI.getAllocatedType();
7957 const Type *CastElTy = PTy->getElementType();
7958 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007959
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007960 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7961 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007962 if (CastElTyAlign < AllocElTyAlign) return 0;
7963
Chris Lattner39387a52005-10-24 06:35:18 +00007964 // If the allocation has multiple uses, only promote it if we are strictly
7965 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007966 // same, we open the door to infinite loops of various kinds. (A reference
7967 // from a dbg.declare doesn't count as a use for this purpose.)
7968 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7969 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007970
Duncan Sands777d2302009-05-09 07:06:46 +00007971 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7972 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007973 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007974
Chris Lattner455fcc82005-10-29 03:19:53 +00007975 // See if we can satisfy the modulus by pulling a scale out of the array
7976 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007977 unsigned ArraySizeScale;
7978 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007979 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007980 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7981 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007982
Chris Lattner455fcc82005-10-29 03:19:53 +00007983 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7984 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007985 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7986 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007987
Chris Lattner455fcc82005-10-29 03:19:53 +00007988 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7989 Value *Amt = 0;
7990 if (Scale == 1) {
7991 Amt = NumElements;
7992 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007993 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007994 // Insert before the alloca, not before the cast.
7995 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007996 }
7997
Jeff Cohen86796be2007-04-04 16:58:57 +00007998 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007999 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008000 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008001 }
8002
Victor Hernandez7b929da2009-10-23 21:09:37 +00008003 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008004 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008005 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008006
Dale Johannesena0a66372009-03-05 00:39:02 +00008007 // If the allocation has one real use plus a dbg.declare, just remove the
8008 // declare.
8009 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8010 EraseInstFromFunction(*DI);
8011 }
8012 // If the allocation has multiple real uses, insert a cast and change all
8013 // things that used it to use the new cast. This will also hack on CI, but it
8014 // will die soon.
8015 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008016 // New is the allocation instruction, pointer typed. AI is the original
8017 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008018 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008019 AI.replaceAllUsesWith(NewCast);
8020 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008021 return ReplaceInstUsesWith(CI, New);
8022}
8023
Chris Lattner70074e02006-05-13 02:06:03 +00008024/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008025/// and return it as type Ty without inserting any new casts and without
8026/// changing the computed value. This is used by code that tries to decide
8027/// whether promoting or shrinking integer operations to wider or smaller types
8028/// will allow us to eliminate a truncate or extend.
8029///
8030/// This is a truncation operation if Ty is smaller than V->getType(), or an
8031/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008032///
8033/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8034/// should return true if trunc(V) can be computed by computing V in the smaller
8035/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8036/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8037/// efficiently truncated.
8038///
8039/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8040/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8041/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008042bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008043 unsigned CastOpc,
8044 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008045 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008046 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008047 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008048
8049 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008050 if (!I) return false;
8051
Dan Gohman6de29f82009-06-15 22:12:54 +00008052 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008053
Chris Lattner951626b2007-08-02 06:11:14 +00008054 // If this is an extension or truncate, we can often eliminate it.
8055 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8056 // If this is a cast from the destination type, we can trivially eliminate
8057 // it, and this will remove a cast overall.
8058 if (I->getOperand(0)->getType() == Ty) {
8059 // If the first operand is itself a cast, and is eliminable, do not count
8060 // this as an eliminable cast. We would prefer to eliminate those two
8061 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008062 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008063 ++NumCastsRemoved;
8064 return true;
8065 }
8066 }
8067
8068 // We can't extend or shrink something that has multiple uses: doing so would
8069 // require duplicating the instruction in general, which isn't profitable.
8070 if (!I->hasOneUse()) return false;
8071
Evan Chengf35fd542009-01-15 17:01:23 +00008072 unsigned Opc = I->getOpcode();
8073 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 case Instruction::Add:
8075 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008076 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008077 case Instruction::And:
8078 case Instruction::Or:
8079 case Instruction::Xor:
8080 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008081 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008082 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008083 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008084 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008085
Eli Friedman070a9812009-07-13 22:46:01 +00008086 case Instruction::UDiv:
8087 case Instruction::URem: {
8088 // UDiv and URem can be truncated if all the truncated bits are zero.
8089 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8090 uint32_t BitWidth = Ty->getScalarSizeInBits();
8091 if (BitWidth < OrigBitWidth) {
8092 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8093 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8094 MaskedValueIsZero(I->getOperand(1), Mask)) {
8095 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8096 NumCastsRemoved) &&
8097 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8098 NumCastsRemoved);
8099 }
8100 }
8101 break;
8102 }
Chris Lattner46b96052006-11-29 07:18:39 +00008103 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008104 // If we are truncating the result of this SHL, and if it's a shift of a
8105 // constant amount, we can always perform a SHL in a smaller type.
8106 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008107 uint32_t BitWidth = Ty->getScalarSizeInBits();
8108 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008109 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008110 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008111 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008112 }
8113 break;
8114 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008115 // If this is a truncate of a logical shr, we can truncate it to a smaller
8116 // lshr iff we know that the bits we would otherwise be shifting in are
8117 // already zeros.
8118 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008119 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8120 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008121 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008122 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008123 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8124 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008125 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008126 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008127 }
8128 }
Chris Lattner46b96052006-11-29 07:18:39 +00008129 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008130 case Instruction::ZExt:
8131 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008132 case Instruction::Trunc:
8133 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008134 // can safely replace it. Note that replacing it does not reduce the number
8135 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008136 if (Opc == CastOpc)
8137 return true;
8138
8139 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008140 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008141 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008142 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008143 case Instruction::Select: {
8144 SelectInst *SI = cast<SelectInst>(I);
8145 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008146 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008147 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008148 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008149 }
Chris Lattner8114b712008-06-18 04:00:49 +00008150 case Instruction::PHI: {
8151 // We can change a phi if we can change all operands.
8152 PHINode *PN = cast<PHINode>(I);
8153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8154 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008155 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008156 return false;
8157 return true;
8158 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008159 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008160 // TODO: Can handle more cases here.
8161 break;
8162 }
8163
8164 return false;
8165}
8166
8167/// EvaluateInDifferentType - Given an expression that
8168/// CanEvaluateInDifferentType returns true for, actually insert the code to
8169/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008170Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008171 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008172 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008173 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008174
8175 // Otherwise, it must be an instruction.
8176 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008177 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008178 unsigned Opc = I->getOpcode();
8179 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008180 case Instruction::Add:
8181 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008182 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008183 case Instruction::And:
8184 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008185 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008186 case Instruction::AShr:
8187 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008188 case Instruction::Shl:
8189 case Instruction::UDiv:
8190 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008191 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008192 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008193 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008194 break;
8195 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008196 case Instruction::Trunc:
8197 case Instruction::ZExt:
8198 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008199 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008200 // just return the source. There's no need to insert it because it is not
8201 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008202 if (I->getOperand(0)->getType() == Ty)
8203 return I->getOperand(0);
8204
Chris Lattner8114b712008-06-18 04:00:49 +00008205 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008206 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008207 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008208 case Instruction::Select: {
8209 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8210 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8211 Res = SelectInst::Create(I->getOperand(0), True, False);
8212 break;
8213 }
Chris Lattner8114b712008-06-18 04:00:49 +00008214 case Instruction::PHI: {
8215 PHINode *OPN = cast<PHINode>(I);
8216 PHINode *NPN = PHINode::Create(Ty);
8217 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8218 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8219 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8220 }
8221 Res = NPN;
8222 break;
8223 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008224 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008225 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008226 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008227 break;
8228 }
8229
Chris Lattner8114b712008-06-18 04:00:49 +00008230 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008231 return InsertNewInstBefore(Res, *I);
8232}
8233
Reid Spencer3da59db2006-11-27 01:05:10 +00008234/// @brief Implement the transforms common to all CastInst visitors.
8235Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008236 Value *Src = CI.getOperand(0);
8237
Dan Gohman23d9d272007-05-11 21:10:54 +00008238 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008239 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008240 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008241 if (Instruction::CastOps opc =
8242 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8243 // The first cast (CSrc) is eliminable so we need to fix up or replace
8244 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008245 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008246 }
8247 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008248
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008250 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8251 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8252 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008253
8254 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008255 if (isa<PHINode>(Src)) {
8256 // We don't do this if this would create a PHI node with an illegal type if
8257 // it is currently legal.
8258 if (!isa<IntegerType>(Src->getType()) ||
8259 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008260 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008261 if (Instruction *NV = FoldOpIntoPhi(CI))
8262 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008263 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008264
Reid Spencer3da59db2006-11-27 01:05:10 +00008265 return 0;
8266}
8267
Chris Lattner46cd5a12009-01-09 05:44:56 +00008268/// FindElementAtOffset - Given a type and a constant offset, determine whether
8269/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008270/// the specified offset. If so, fill them into NewIndices and return the
8271/// resultant element type, otherwise return null.
8272static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8273 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008274 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008275 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008276 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008277 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008278
8279 // Start with the index over the outer type. Note that the type size
8280 // might be zero (even if the offset isn't zero) if the indexed type
8281 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008282 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008283 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008284 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008285 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008286 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008287
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008288 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008289 if (Offset < 0) {
8290 --FirstIdx;
8291 Offset += TySize;
8292 assert(Offset >= 0);
8293 }
8294 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8295 }
8296
Owen Andersoneed707b2009-07-24 23:12:02 +00008297 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008298
8299 // Index into the types. If we fail, set OrigBase to null.
8300 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008301 // Indexing into tail padding between struct/array elements.
8302 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008303 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008304
Chris Lattner46cd5a12009-01-09 05:44:56 +00008305 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8306 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008307 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8308 "Offset must stay within the indexed type");
8309
Chris Lattner46cd5a12009-01-09 05:44:56 +00008310 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008311 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008312
8313 Offset -= SL->getElementOffset(Elt);
8314 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008315 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008316 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008317 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008318 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008319 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008320 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008321 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008322 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008323 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008324 }
8325 }
8326
Chris Lattner3914f722009-01-24 01:00:13 +00008327 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008328}
8329
Chris Lattnerd3e28342007-04-27 17:44:50 +00008330/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8331Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8332 Value *Src = CI.getOperand(0);
8333
Chris Lattnerd3e28342007-04-27 17:44:50 +00008334 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008335 // If casting the result of a getelementptr instruction with no offset, turn
8336 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008337 if (GEP->hasAllZeroIndices()) {
8338 // Changing the cast operand is usually not a good idea but it is safe
8339 // here because the pointer operand is being replaced with another
8340 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008341 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008342 CI.setOperand(0, GEP->getOperand(0));
8343 return &CI;
8344 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008345
8346 // If the GEP has a single use, and the base pointer is a bitcast, and the
8347 // GEP computes a constant offset, see if we can convert these three
8348 // instructions into fewer. This typically happens with unions and other
8349 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008350 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008351 if (GEP->hasAllConstantIndices()) {
8352 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008353 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008354 int64_t Offset = OffsetV->getSExtValue();
8355
8356 // Get the base pointer input of the bitcast, and the type it points to.
8357 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8358 const Type *GEPIdxTy =
8359 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008360 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008361 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008362 // If we were able to index down into an element, create the GEP
8363 // and bitcast the result. This eliminates one bitcast, potentially
8364 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008365 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8366 Builder->CreateInBoundsGEP(OrigBase,
8367 NewIndices.begin(), NewIndices.end()) :
8368 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008369 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008370
Chris Lattner46cd5a12009-01-09 05:44:56 +00008371 if (isa<BitCastInst>(CI))
8372 return new BitCastInst(NGEP, CI.getType());
8373 assert(isa<PtrToIntInst>(CI));
8374 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008375 }
8376 }
8377 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008378 }
8379
8380 return commonCastTransforms(CI);
8381}
8382
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008383/// commonIntCastTransforms - This function implements the common transforms
8384/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008385Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8386 if (Instruction *Result = commonCastTransforms(CI))
8387 return Result;
8388
8389 Value *Src = CI.getOperand(0);
8390 const Type *SrcTy = Src->getType();
8391 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008392 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8393 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008394
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 // See if we can simplify any instructions used by the LHS whose sole
8396 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008397 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008398 return &CI;
8399
8400 // If the source isn't an instruction or has more than one use then we
8401 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008402 Instruction *SrcI = dyn_cast<Instruction>(Src);
8403 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008404 return 0;
8405
Chris Lattnerc739cd62007-03-03 05:27:34 +00008406 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008407 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008408 // Only do this if the dest type is a simple type, don't convert the
8409 // expression tree to something weird like i93 unless the source is also
8410 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008411 if ((isa<VectorType>(DestTy) ||
8412 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8413 CanEvaluateInDifferentType(SrcI, DestTy,
8414 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008415 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008416 // eliminates the cast, so it is always a win. If this is a zero-extension,
8417 // we need to do an AND to maintain the clear top-part of the computation,
8418 // so we require that the input have eliminated at least one cast. If this
8419 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008421 bool DoXForm = false;
8422 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008423 switch (CI.getOpcode()) {
8424 default:
8425 // All the others use floating point so we shouldn't actually
8426 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008427 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008428 case Instruction::Trunc:
8429 DoXForm = true;
8430 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008431 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008432 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008433
Chris Lattner39c27ed2009-01-31 19:05:27 +00008434 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008435 // If it's unnecessary to issue an AND to clear the high bits, it's
8436 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008437 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008438 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8439 if (MaskedValueIsZero(TryRes, Mask))
8440 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008441
8442 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008443 if (TryI->use_empty())
8444 EraseInstFromFunction(*TryI);
8445 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008446 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008447 }
Evan Chengf35fd542009-01-15 17:01:23 +00008448 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008449 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008450 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008451 // If we do not have to emit the truncate + sext pair, then it's always
8452 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008453 //
8454 // It's not safe to eliminate the trunc + sext pair if one of the
8455 // eliminated cast is a truncate. e.g.
8456 // t2 = trunc i32 t1 to i16
8457 // t3 = sext i16 t2 to i32
8458 // !=
8459 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008460 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008461 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8462 if (NumSignBits > (DestBitSize - SrcBitSize))
8463 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008464
8465 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008466 if (TryI->use_empty())
8467 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008468 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008469 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008470 }
Evan Chengf35fd542009-01-15 17:01:23 +00008471 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008472
8473 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008474 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8475 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008476 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8477 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008478 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008479 // Just replace this cast with the result.
8480 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008481
Reid Spencer3da59db2006-11-27 01:05:10 +00008482 assert(Res->getType() == DestTy);
8483 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008484 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008485 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008486 // Just replace this cast with the result.
8487 return ReplaceInstUsesWith(CI, Res);
8488 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008489 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008490
8491 // If the high bits are already zero, just replace this cast with the
8492 // result.
8493 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8494 if (MaskedValueIsZero(Res, Mask))
8495 return ReplaceInstUsesWith(CI, Res);
8496
8497 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008498 Constant *C = ConstantInt::get(*Context,
8499 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008500 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008501 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008502 case Instruction::SExt: {
8503 // If the high bits are already filled with sign bit, just replace this
8504 // cast with the result.
8505 unsigned NumSignBits = ComputeNumSignBits(Res);
8506 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008507 return ReplaceInstUsesWith(CI, Res);
8508
Reid Spencer3da59db2006-11-27 01:05:10 +00008509 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008510 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008511 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008512 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008513 }
8514 }
8515
8516 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8517 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8518
8519 switch (SrcI->getOpcode()) {
8520 case Instruction::Add:
8521 case Instruction::Mul:
8522 case Instruction::And:
8523 case Instruction::Or:
8524 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008525 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008526 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8527 // Don't insert two casts unless at least one can be eliminated.
8528 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008529 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008530 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8531 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008532 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008533 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008534 }
8535 }
8536
8537 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8538 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8539 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008540 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008541 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008542 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008543 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008544 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008545 }
8546 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008547
Eli Friedman65445c52009-07-13 21:45:57 +00008548 case Instruction::Shl: {
8549 // Canonicalize trunc inside shl, if we can.
8550 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8551 if (CI && DestBitSize < SrcBitSize &&
8552 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008553 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8554 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008555 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008556 }
8557 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008558 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008559 }
8560 return 0;
8561}
8562
Chris Lattner8a9f5712007-04-11 06:57:46 +00008563Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008564 if (Instruction *Result = commonIntCastTransforms(CI))
8565 return Result;
8566
8567 Value *Src = CI.getOperand(0);
8568 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008569 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8570 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008571
8572 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008573 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008574 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008575 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008576 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008577 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008578 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008579
Chris Lattner4f9797d2009-03-24 18:15:30 +00008580 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8581 ConstantInt *ShAmtV = 0;
8582 Value *ShiftOp = 0;
8583 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008584 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008585 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8586
8587 // Get a mask for the bits shifting in.
8588 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8589 if (MaskedValueIsZero(ShiftOp, Mask)) {
8590 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008591 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008592
8593 // Okay, we can shrink this. Truncate the input, then return a new
8594 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008595 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008596 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008597 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008598 }
8599 }
Chris Lattner9956c052009-11-08 19:23:30 +00008600
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008601 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008602}
8603
Evan Chengb98a10e2008-03-24 00:21:34 +00008604/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8605/// in order to eliminate the icmp.
8606Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8607 bool DoXform) {
8608 // If we are just checking for a icmp eq of a single bit and zext'ing it
8609 // to an integer, then shift the bit to the appropriate place and then
8610 // cast to integer to avoid the comparison.
8611 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8612 const APInt &Op1CV = Op1C->getValue();
8613
8614 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8615 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8616 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8617 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8618 if (!DoXform) return ICI;
8619
8620 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008621 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008622 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008623 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008624 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008625 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008626
8627 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008628 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008629 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008630 }
8631
8632 return ReplaceInstUsesWith(CI, In);
8633 }
8634
8635
8636
8637 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8638 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8639 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8640 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8641 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8642 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8643 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8644 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8645 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8646 // This only works for EQ and NE
8647 ICI->isEquality()) {
8648 // If Op1C some other power of two, convert:
8649 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8650 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8651 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8652 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8653
8654 APInt KnownZeroMask(~KnownZero);
8655 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8656 if (!DoXform) return ICI;
8657
8658 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8659 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8660 // (X&4) == 2 --> false
8661 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008662 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008663 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008664 return ReplaceInstUsesWith(CI, Res);
8665 }
8666
8667 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8668 Value *In = ICI->getOperand(0);
8669 if (ShiftAmt) {
8670 // Perform a logical shr by shiftamt.
8671 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008672 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8673 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008674 }
8675
8676 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008677 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008678 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008679 }
8680
8681 if (CI.getType() == In->getType())
8682 return ReplaceInstUsesWith(CI, In);
8683 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008684 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008685 }
8686 }
8687 }
8688
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008689 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8690 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8691 // may lead to additional simplifications.
8692 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8693 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8694 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008695 Value *LHS = ICI->getOperand(0);
8696 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008697
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008698 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8699 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8700 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8701 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8702 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008703
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008704 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8705 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8706 APInt UnknownBit = ~KnownBits;
8707 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008708 if (!DoXform) return ICI;
8709
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008710 Value *Result = Builder->CreateXor(LHS, RHS);
8711
8712 // Mask off any bits that are set and won't be shifted away.
8713 if (KnownOneLHS.uge(UnknownBit))
8714 Result = Builder->CreateAnd(Result,
8715 ConstantInt::get(ITy, UnknownBit));
8716
8717 // Shift the bit we're testing down to the lsb.
8718 Result = Builder->CreateLShr(
8719 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8720
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008721 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008722 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8723 Result->takeName(ICI);
8724 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008725 }
8726 }
8727 }
8728 }
8729
Evan Chengb98a10e2008-03-24 00:21:34 +00008730 return 0;
8731}
8732
Chris Lattner8a9f5712007-04-11 06:57:46 +00008733Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008734 // If one of the common conversion will work ..
8735 if (Instruction *Result = commonIntCastTransforms(CI))
8736 return Result;
8737
8738 Value *Src = CI.getOperand(0);
8739
Chris Lattnera84f47c2009-02-17 20:47:23 +00008740 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8741 // types and if the sizes are just right we can convert this into a logical
8742 // 'and' which will be much cheaper than the pair of casts.
8743 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8744 // Get the sizes of the types involved. We know that the intermediate type
8745 // will be smaller than A or C, but don't know the relation between A and C.
8746 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008747 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8748 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8749 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008750 // If we're actually extending zero bits, then if
8751 // SrcSize < DstSize: zext(a & mask)
8752 // SrcSize == DstSize: a & mask
8753 // SrcSize > DstSize: trunc(a) & mask
8754 if (SrcSize < DstSize) {
8755 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008756 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008757 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008758 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008759 }
8760
8761 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008762 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008763 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008764 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008765 }
8766 if (SrcSize > DstSize) {
8767 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008768 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008769 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008770 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008771 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008772 }
8773 }
8774
Evan Chengb98a10e2008-03-24 00:21:34 +00008775 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8776 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008777
Evan Chengb98a10e2008-03-24 00:21:34 +00008778 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8779 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8780 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8781 // of the (zext icmp) will be transformed.
8782 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8783 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8784 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8785 (transformZExtICmp(LHS, CI, false) ||
8786 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008787 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8788 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008789 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008790 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008791 }
8792
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008793 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008794 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8795 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8796 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8797 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008798 if (TI0->getType() == CI.getType())
8799 return
8800 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008801 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008802 }
8803
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008804 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8805 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8806 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8807 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8808 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8809 And->getOperand(1) == C)
8810 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8811 Value *TI0 = TI->getOperand(0);
8812 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008813 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008814 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008815 return BinaryOperator::CreateXor(NewAnd, ZC);
8816 }
8817 }
8818
Reid Spencer3da59db2006-11-27 01:05:10 +00008819 return 0;
8820}
8821
Chris Lattner8a9f5712007-04-11 06:57:46 +00008822Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008823 if (Instruction *I = commonIntCastTransforms(CI))
8824 return I;
8825
Chris Lattner8a9f5712007-04-11 06:57:46 +00008826 Value *Src = CI.getOperand(0);
8827
Dan Gohman1975d032008-10-30 20:40:10 +00008828 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008829 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008830 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008831 Constant::getAllOnesValue(CI.getType()),
8832 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008833
8834 // See if the value being truncated is already sign extended. If so, just
8835 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008836 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008837 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008838 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8839 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8840 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008841 unsigned NumSignBits = ComputeNumSignBits(Op);
8842
8843 if (OpBits == DestBits) {
8844 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8845 // bits, it is already ready.
8846 if (NumSignBits > DestBits-MidBits)
8847 return ReplaceInstUsesWith(CI, Op);
8848 } else if (OpBits < DestBits) {
8849 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8850 // bits, just sext from i32.
8851 if (NumSignBits > OpBits-MidBits)
8852 return new SExtInst(Op, CI.getType(), "tmp");
8853 } else {
8854 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8855 // bits, just truncate to i32.
8856 if (NumSignBits > OpBits-MidBits)
8857 return new TruncInst(Op, CI.getType(), "tmp");
8858 }
8859 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008860
8861 // If the input is a shl/ashr pair of a same constant, then this is a sign
8862 // extension from a smaller value. If we could trust arbitrary bitwidth
8863 // integers, we could turn this into a truncate to the smaller bit and then
8864 // use a sext for the whole extension. Since we don't, look deeper and check
8865 // for a truncate. If the source and dest are the same type, eliminate the
8866 // trunc and extend and just do shifts. For example, turn:
8867 // %a = trunc i32 %i to i8
8868 // %b = shl i8 %a, 6
8869 // %c = ashr i8 %b, 6
8870 // %d = sext i8 %c to i32
8871 // into:
8872 // %a = shl i32 %i, 30
8873 // %d = ashr i32 %a, 30
8874 Value *A = 0;
8875 ConstantInt *BA = 0, *CA = 0;
8876 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008877 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008878 BA == CA && isa<TruncInst>(A)) {
8879 Value *I = cast<TruncInst>(A)->getOperand(0);
8880 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008881 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8882 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008883 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008884 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008885 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008886 return BinaryOperator::CreateAShr(I, ShAmtV);
8887 }
8888 }
8889
Chris Lattnerba417832007-04-11 06:12:58 +00008890 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008891}
8892
Chris Lattnerb7530652008-01-27 05:29:54 +00008893/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8894/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008895static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008896 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008897 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008898 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008899 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8900 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008901 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008902 return 0;
8903}
8904
8905/// LookThroughFPExtensions - If this is an fp extension instruction, look
8906/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008907static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008908 if (Instruction *I = dyn_cast<Instruction>(V))
8909 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008910 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008911
8912 // If this value is a constant, return the constant in the smallest FP type
8913 // that can accurately represent it. This allows us to turn
8914 // (float)((double)X+2.0) into x+2.0f.
8915 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008916 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008917 return V; // No constant folding of this.
8918 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008919 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008920 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008921 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008922 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008923 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008924 return V;
8925 // Don't try to shrink to various long double types.
8926 }
8927
8928 return V;
8929}
8930
8931Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8932 if (Instruction *I = commonCastTransforms(CI))
8933 return I;
8934
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008935 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008936 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008937 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008938 // many builtins (sqrt, etc).
8939 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8940 if (OpI && OpI->hasOneUse()) {
8941 switch (OpI->getOpcode()) {
8942 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008943 case Instruction::FAdd:
8944 case Instruction::FSub:
8945 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008946 case Instruction::FDiv:
8947 case Instruction::FRem:
8948 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008949 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8950 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008951 if (LHSTrunc->getType() != SrcTy &&
8952 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008953 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008954 // If the source types were both smaller than the destination type of
8955 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008956 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8957 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008958 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8959 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008960 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008961 }
8962 }
8963 break;
8964 }
8965 }
8966 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008967}
8968
8969Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8970 return commonCastTransforms(CI);
8971}
8972
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008973Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008974 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8975 if (OpI == 0)
8976 return commonCastTransforms(FI);
8977
8978 // fptoui(uitofp(X)) --> X
8979 // fptoui(sitofp(X)) --> X
8980 // This is safe if the intermediate type has enough bits in its mantissa to
8981 // accurately represent all values of X. For example, do not do this with
8982 // i64->float->i64. This is also safe for sitofp case, because any negative
8983 // 'X' value would cause an undefined result for the fptoui.
8984 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8985 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008986 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008987 OpI->getType()->getFPMantissaWidth())
8988 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008989
8990 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008991}
8992
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008993Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008994 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8995 if (OpI == 0)
8996 return commonCastTransforms(FI);
8997
8998 // fptosi(sitofp(X)) --> X
8999 // fptosi(uitofp(X)) --> X
9000 // This is safe if the intermediate type has enough bits in its mantissa to
9001 // accurately represent all values of X. For example, do not do this with
9002 // i64->float->i64. This is also safe for sitofp case, because any negative
9003 // 'X' value would cause an undefined result for the fptoui.
9004 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9005 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009006 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009007 OpI->getType()->getFPMantissaWidth())
9008 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009009
9010 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009011}
9012
9013Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9014 return commonCastTransforms(CI);
9015}
9016
9017Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9018 return commonCastTransforms(CI);
9019}
9020
Chris Lattnera0e69692009-03-24 18:35:40 +00009021Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9022 // If the destination integer type is smaller than the intptr_t type for
9023 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9024 // trunc to be exposed to other transforms. Don't do this for extending
9025 // ptrtoint's, because we don't know if the target sign or zero extends its
9026 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009027 if (TD &&
9028 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009029 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9030 TD->getIntPtrType(CI.getContext()),
9031 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009032 return new TruncInst(P, CI.getType());
9033 }
9034
Chris Lattnerd3e28342007-04-27 17:44:50 +00009035 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009036}
9037
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009038Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009039 // If the source integer type is larger than the intptr_t type for
9040 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9041 // allows the trunc to be exposed to other transforms. Don't do this for
9042 // extending inttoptr's, because we don't know if the target sign or zero
9043 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009044 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009045 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009046 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9047 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009048 return new IntToPtrInst(P, CI.getType());
9049 }
9050
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009051 if (Instruction *I = commonCastTransforms(CI))
9052 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009053
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009054 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009055}
9056
Chris Lattnerd3e28342007-04-27 17:44:50 +00009057Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009058 // If the operands are integer typed then apply the integer transforms,
9059 // otherwise just apply the common ones.
9060 Value *Src = CI.getOperand(0);
9061 const Type *SrcTy = Src->getType();
9062 const Type *DestTy = CI.getType();
9063
Eli Friedman7e25d452009-07-13 20:53:00 +00009064 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009065 if (Instruction *I = commonPointerCastTransforms(CI))
9066 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009067 } else {
9068 if (Instruction *Result = commonCastTransforms(CI))
9069 return Result;
9070 }
9071
9072
9073 // Get rid of casts from one type to the same type. These are useless and can
9074 // be replaced by the operand.
9075 if (DestTy == Src->getType())
9076 return ReplaceInstUsesWith(CI, Src);
9077
Reid Spencer3da59db2006-11-27 01:05:10 +00009078 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009079 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9080 const Type *DstElTy = DstPTy->getElementType();
9081 const Type *SrcElTy = SrcPTy->getElementType();
9082
Nate Begeman83ad90a2008-03-31 00:22:16 +00009083 // If the address spaces don't match, don't eliminate the bitcast, which is
9084 // required for changing types.
9085 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9086 return 0;
9087
Victor Hernandez83d63912009-09-18 22:35:49 +00009088 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009089 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009090 // There is no need to modify malloc calls because it is their bitcast that
9091 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009092 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009093 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9094 return V;
9095
Chris Lattnerd717c182007-05-05 22:32:24 +00009096 // If the source and destination are pointers, and this cast is equivalent
9097 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009098 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009099 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009100 unsigned NumZeros = 0;
9101 while (SrcElTy != DstElTy &&
9102 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9103 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9104 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9105 ++NumZeros;
9106 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009107
Chris Lattnerd3e28342007-04-27 17:44:50 +00009108 // If we found a path from the src to dest, create the getelementptr now.
9109 if (SrcElTy == DstElTy) {
9110 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009111 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9112 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009113 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009114 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009115
Eli Friedman2451a642009-07-18 23:06:53 +00009116 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9117 if (DestVTy->getNumElements() == 1) {
9118 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009119 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009120 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009121 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009122 }
9123 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9124 }
9125 }
9126
9127 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9128 if (SrcVTy->getNumElements() == 1) {
9129 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009130 Value *Elem =
9131 Builder->CreateExtractElement(Src,
9132 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009133 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9134 }
9135 }
9136 }
9137
Reid Spencer3da59db2006-11-27 01:05:10 +00009138 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9139 if (SVI->hasOneUse()) {
9140 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9141 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009142 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009143 cast<VectorType>(DestTy)->getNumElements() ==
9144 SVI->getType()->getNumElements() &&
9145 SVI->getType()->getNumElements() ==
9146 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009147 CastInst *Tmp;
9148 // If either of the operands is a cast from CI.getType(), then
9149 // evaluating the shuffle in the casted destination's type will allow
9150 // us to eliminate at least one cast.
9151 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9152 Tmp->getOperand(0)->getType() == DestTy) ||
9153 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9154 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009155 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9156 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009157 // Return a new shuffle vector. Use the same element ID's, as we
9158 // know the vector types match #elts.
9159 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009160 }
9161 }
9162 }
9163 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009164 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009165}
9166
Chris Lattnere576b912004-04-09 23:46:01 +00009167/// GetSelectFoldableOperands - We want to turn code that looks like this:
9168/// %C = or %A, %B
9169/// %D = select %cond, %C, %A
9170/// into:
9171/// %C = select %cond, %B, 0
9172/// %D = or %A, %C
9173///
9174/// Assuming that the specified instruction is an operand to the select, return
9175/// a bitmask indicating which operands of this instruction are foldable if they
9176/// equal the other incoming value of the select.
9177///
9178static unsigned GetSelectFoldableOperands(Instruction *I) {
9179 switch (I->getOpcode()) {
9180 case Instruction::Add:
9181 case Instruction::Mul:
9182 case Instruction::And:
9183 case Instruction::Or:
9184 case Instruction::Xor:
9185 return 3; // Can fold through either operand.
9186 case Instruction::Sub: // Can only fold on the amount subtracted.
9187 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009188 case Instruction::LShr:
9189 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009190 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009191 default:
9192 return 0; // Cannot fold
9193 }
9194}
9195
9196/// GetSelectFoldableConstant - For the same transformation as the previous
9197/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009198static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009199 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009200 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009201 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009202 case Instruction::Add:
9203 case Instruction::Sub:
9204 case Instruction::Or:
9205 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009206 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009207 case Instruction::LShr:
9208 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009209 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009210 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009211 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009212 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009213 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009214 }
9215}
9216
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009217/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9218/// have the same opcode and only one use each. Try to simplify this.
9219Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9220 Instruction *FI) {
9221 if (TI->getNumOperands() == 1) {
9222 // If this is a non-volatile load or a cast from the same type,
9223 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009224 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009225 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9226 return 0;
9227 } else {
9228 return 0; // unknown unary op.
9229 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009230
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009231 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009232 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009233 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009234 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009235 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009236 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009237 }
9238
Reid Spencer832254e2007-02-02 02:16:23 +00009239 // Only handle binary operators here.
9240 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009241 return 0;
9242
9243 // Figure out if the operations have any operands in common.
9244 Value *MatchOp, *OtherOpT, *OtherOpF;
9245 bool MatchIsOpZero;
9246 if (TI->getOperand(0) == FI->getOperand(0)) {
9247 MatchOp = TI->getOperand(0);
9248 OtherOpT = TI->getOperand(1);
9249 OtherOpF = FI->getOperand(1);
9250 MatchIsOpZero = true;
9251 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9252 MatchOp = TI->getOperand(1);
9253 OtherOpT = TI->getOperand(0);
9254 OtherOpF = FI->getOperand(0);
9255 MatchIsOpZero = false;
9256 } else if (!TI->isCommutative()) {
9257 return 0;
9258 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9259 MatchOp = TI->getOperand(0);
9260 OtherOpT = TI->getOperand(1);
9261 OtherOpF = FI->getOperand(0);
9262 MatchIsOpZero = true;
9263 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9264 MatchOp = TI->getOperand(1);
9265 OtherOpT = TI->getOperand(0);
9266 OtherOpF = FI->getOperand(1);
9267 MatchIsOpZero = true;
9268 } else {
9269 return 0;
9270 }
9271
9272 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009273 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9274 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009275 InsertNewInstBefore(NewSI, SI);
9276
9277 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9278 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009279 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009280 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009281 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009282 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009283 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009284 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009285}
9286
Evan Chengde621922009-03-31 20:42:45 +00009287static bool isSelect01(Constant *C1, Constant *C2) {
9288 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9289 if (!C1I)
9290 return false;
9291 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9292 if (!C2I)
9293 return false;
9294 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9295}
9296
9297/// FoldSelectIntoOp - Try fold the select into one of the operands to
9298/// facilitate further optimization.
9299Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9300 Value *FalseVal) {
9301 // See the comment above GetSelectFoldableOperands for a description of the
9302 // transformation we are doing here.
9303 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9304 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9305 !isa<Constant>(FalseVal)) {
9306 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9307 unsigned OpToFold = 0;
9308 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9309 OpToFold = 1;
9310 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9311 OpToFold = 2;
9312 }
9313
9314 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009315 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009316 Value *OOp = TVI->getOperand(2-OpToFold);
9317 // Avoid creating select between 2 constants unless it's selecting
9318 // between 0 and 1.
9319 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9320 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9321 InsertNewInstBefore(NewSel, SI);
9322 NewSel->takeName(TVI);
9323 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9324 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009325 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009326 }
9327 }
9328 }
9329 }
9330 }
9331
9332 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9333 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9334 !isa<Constant>(TrueVal)) {
9335 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9336 unsigned OpToFold = 0;
9337 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9338 OpToFold = 1;
9339 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9340 OpToFold = 2;
9341 }
9342
9343 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009344 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009345 Value *OOp = FVI->getOperand(2-OpToFold);
9346 // Avoid creating select between 2 constants unless it's selecting
9347 // between 0 and 1.
9348 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9349 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9350 InsertNewInstBefore(NewSel, SI);
9351 NewSel->takeName(FVI);
9352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9353 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009354 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009355 }
9356 }
9357 }
9358 }
9359 }
9360
9361 return 0;
9362}
9363
Dan Gohman81b28ce2008-09-16 18:46:06 +00009364/// visitSelectInstWithICmp - Visit a SelectInst that has an
9365/// ICmpInst as its first operand.
9366///
9367Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9368 ICmpInst *ICI) {
9369 bool Changed = false;
9370 ICmpInst::Predicate Pred = ICI->getPredicate();
9371 Value *CmpLHS = ICI->getOperand(0);
9372 Value *CmpRHS = ICI->getOperand(1);
9373 Value *TrueVal = SI.getTrueValue();
9374 Value *FalseVal = SI.getFalseValue();
9375
9376 // Check cases where the comparison is with a constant that
9377 // can be adjusted to fit the min/max idiom. We may edit ICI in
9378 // place here, so make sure the select is the only user.
9379 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009380 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009381 switch (Pred) {
9382 default: break;
9383 case ICmpInst::ICMP_ULT:
9384 case ICmpInst::ICMP_SLT: {
9385 // X < MIN ? T : F --> F
9386 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9387 return ReplaceInstUsesWith(SI, FalseVal);
9388 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009389 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009390 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9391 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9392 Pred = ICmpInst::getSwappedPredicate(Pred);
9393 CmpRHS = AdjustedRHS;
9394 std::swap(FalseVal, TrueVal);
9395 ICI->setPredicate(Pred);
9396 ICI->setOperand(1, CmpRHS);
9397 SI.setOperand(1, TrueVal);
9398 SI.setOperand(2, FalseVal);
9399 Changed = true;
9400 }
9401 break;
9402 }
9403 case ICmpInst::ICMP_UGT:
9404 case ICmpInst::ICMP_SGT: {
9405 // X > MAX ? T : F --> F
9406 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9407 return ReplaceInstUsesWith(SI, FalseVal);
9408 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009409 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009410 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9411 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9412 Pred = ICmpInst::getSwappedPredicate(Pred);
9413 CmpRHS = AdjustedRHS;
9414 std::swap(FalseVal, TrueVal);
9415 ICI->setPredicate(Pred);
9416 ICI->setOperand(1, CmpRHS);
9417 SI.setOperand(1, TrueVal);
9418 SI.setOperand(2, FalseVal);
9419 Changed = true;
9420 }
9421 break;
9422 }
9423 }
9424
Dan Gohman1975d032008-10-30 20:40:10 +00009425 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9426 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009427 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009428 if (match(TrueVal, m_ConstantInt<-1>()) &&
9429 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009430 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009431 else if (match(TrueVal, m_ConstantInt<0>()) &&
9432 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009433 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9434
Dan Gohman1975d032008-10-30 20:40:10 +00009435 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9436 // If we are just checking for a icmp eq of a single bit and zext'ing it
9437 // to an integer, then shift the bit to the appropriate place and then
9438 // cast to integer to avoid the comparison.
9439 const APInt &Op1CV = CI->getValue();
9440
9441 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9442 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9443 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009444 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009445 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009446 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009447 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009448 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009449 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009450 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009451 if (In->getType() != SI.getType())
9452 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009453 true/*SExt*/, "tmp", ICI);
9454
9455 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009456 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009457 In->getName()+".not"), *ICI);
9458
9459 return ReplaceInstUsesWith(SI, In);
9460 }
9461 }
9462 }
9463
Dan Gohman81b28ce2008-09-16 18:46:06 +00009464 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9465 // Transform (X == Y) ? X : Y -> Y
9466 if (Pred == ICmpInst::ICMP_EQ)
9467 return ReplaceInstUsesWith(SI, FalseVal);
9468 // Transform (X != Y) ? X : Y -> X
9469 if (Pred == ICmpInst::ICMP_NE)
9470 return ReplaceInstUsesWith(SI, TrueVal);
9471 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9472
9473 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9474 // Transform (X == Y) ? Y : X -> X
9475 if (Pred == ICmpInst::ICMP_EQ)
9476 return ReplaceInstUsesWith(SI, FalseVal);
9477 // Transform (X != Y) ? Y : X -> Y
9478 if (Pred == ICmpInst::ICMP_NE)
9479 return ReplaceInstUsesWith(SI, TrueVal);
9480 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9481 }
9482
9483 /// NOTE: if we wanted to, this is where to detect integer ABS
9484
9485 return Changed ? &SI : 0;
9486}
9487
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009488
Chris Lattner7f239582009-10-22 00:17:26 +00009489/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9490/// PHI node (but the two may be in different blocks). See if the true/false
9491/// values (V) are live in all of the predecessor blocks of the PHI. For
9492/// example, cases like this cannot be mapped:
9493///
9494/// X = phi [ C1, BB1], [C2, BB2]
9495/// Y = add
9496/// Z = select X, Y, 0
9497///
9498/// because Y is not live in BB1/BB2.
9499///
9500static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9501 const SelectInst &SI) {
9502 // If the value is a non-instruction value like a constant or argument, it
9503 // can always be mapped.
9504 const Instruction *I = dyn_cast<Instruction>(V);
9505 if (I == 0) return true;
9506
9507 // If V is a PHI node defined in the same block as the condition PHI, we can
9508 // map the arguments.
9509 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9510
9511 if (const PHINode *VP = dyn_cast<PHINode>(I))
9512 if (VP->getParent() == CondPHI->getParent())
9513 return true;
9514
9515 // Otherwise, if the PHI and select are defined in the same block and if V is
9516 // defined in a different block, then we can transform it.
9517 if (SI.getParent() == CondPHI->getParent() &&
9518 I->getParent() != CondPHI->getParent())
9519 return true;
9520
9521 // Otherwise we have a 'hard' case and we can't tell without doing more
9522 // detailed dominator based analysis, punt.
9523 return false;
9524}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009525
Chris Lattner3d69f462004-03-12 05:52:32 +00009526Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009527 Value *CondVal = SI.getCondition();
9528 Value *TrueVal = SI.getTrueValue();
9529 Value *FalseVal = SI.getFalseValue();
9530
9531 // select true, X, Y -> X
9532 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009533 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009534 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009535
9536 // select C, X, X -> X
9537 if (TrueVal == FalseVal)
9538 return ReplaceInstUsesWith(SI, TrueVal);
9539
Chris Lattnere87597f2004-10-16 18:11:37 +00009540 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9541 return ReplaceInstUsesWith(SI, FalseVal);
9542 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9543 return ReplaceInstUsesWith(SI, TrueVal);
9544 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9545 if (isa<Constant>(TrueVal))
9546 return ReplaceInstUsesWith(SI, TrueVal);
9547 else
9548 return ReplaceInstUsesWith(SI, FalseVal);
9549 }
9550
Owen Anderson1d0be152009-08-13 21:58:54 +00009551 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009552 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009553 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009554 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009555 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009556 } else {
9557 // Change: A = select B, false, C --> A = and !B, C
9558 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009559 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009560 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009561 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009562 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009563 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009564 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009565 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009566 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009567 } else {
9568 // Change: A = select B, C, true --> A = or !B, C
9569 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009570 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009571 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009572 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009573 }
9574 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009575
9576 // select a, b, a -> a&b
9577 // select a, a, b -> a|b
9578 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009579 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009580 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009581 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009582 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009583
Chris Lattner2eefe512004-04-09 19:05:30 +00009584 // Selecting between two integer constants?
9585 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9586 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009587 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009588 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009589 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009590 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009591 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009592 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009593 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009594 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009595 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009596 }
Chris Lattner457dd822004-06-09 07:59:58 +00009597
Reid Spencere4d87aa2006-12-23 06:05:41 +00009598 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009599 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009600 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009601 // non-constant value, eliminate this whole mess. This corresponds to
9602 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009603 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009604 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009605 cast<Constant>(IC->getOperand(1))->isNullValue())
9606 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9607 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009608 isa<ConstantInt>(ICA->getOperand(1)) &&
9609 (ICA->getOperand(1) == TrueValC ||
9610 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009611 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9612 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009613 // know whether we have a icmp_ne or icmp_eq and whether the
9614 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009615 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009616 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009617 Value *V = ICA;
9618 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009619 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009620 Instruction::Xor, V, ICA->getOperand(1)), SI);
9621 return ReplaceInstUsesWith(SI, V);
9622 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009623 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009624 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009625
9626 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009627 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9628 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009629 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009630 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9631 // This is not safe in general for floating point:
9632 // consider X== -0, Y== +0.
9633 // It becomes safe if either operand is a nonzero constant.
9634 ConstantFP *CFPt, *CFPf;
9635 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9636 !CFPt->getValueAPF().isZero()) ||
9637 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9638 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009639 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009640 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009641 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009642 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009643 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009644 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009645
Reid Spencere4d87aa2006-12-23 06:05:41 +00009646 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009647 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009648 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9649 // This is not safe in general for floating point:
9650 // consider X== -0, Y== +0.
9651 // It becomes safe if either operand is a nonzero constant.
9652 ConstantFP *CFPt, *CFPf;
9653 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9654 !CFPt->getValueAPF().isZero()) ||
9655 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9656 !CFPf->getValueAPF().isZero()))
9657 return ReplaceInstUsesWith(SI, FalseVal);
9658 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009659 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009660 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9661 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009662 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009663 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009664 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009665 }
9666
9667 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009668 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9669 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9670 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009671
Chris Lattner87875da2005-01-13 22:52:24 +00009672 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9673 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9674 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009675 Instruction *AddOp = 0, *SubOp = 0;
9676
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009677 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9678 if (TI->getOpcode() == FI->getOpcode())
9679 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9680 return IV;
9681
9682 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9683 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009684 if ((TI->getOpcode() == Instruction::Sub &&
9685 FI->getOpcode() == Instruction::Add) ||
9686 (TI->getOpcode() == Instruction::FSub &&
9687 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009688 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009689 } else if ((FI->getOpcode() == Instruction::Sub &&
9690 TI->getOpcode() == Instruction::Add) ||
9691 (FI->getOpcode() == Instruction::FSub &&
9692 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009693 AddOp = TI; SubOp = FI;
9694 }
9695
9696 if (AddOp) {
9697 Value *OtherAddOp = 0;
9698 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9699 OtherAddOp = AddOp->getOperand(1);
9700 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9701 OtherAddOp = AddOp->getOperand(0);
9702 }
9703
9704 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009705 // So at this point we know we have (Y -> OtherAddOp):
9706 // select C, (add X, Y), (sub X, Z)
9707 Value *NegVal; // Compute -Z
9708 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009709 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009710 } else {
9711 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009712 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009713 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009714 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009715
9716 Value *NewTrueOp = OtherAddOp;
9717 Value *NewFalseOp = NegVal;
9718 if (AddOp != TI)
9719 std::swap(NewTrueOp, NewFalseOp);
9720 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009721 SelectInst::Create(CondVal, NewTrueOp,
9722 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009723
9724 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009725 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009726 }
9727 }
9728 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009729
Chris Lattnere576b912004-04-09 23:46:01 +00009730 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009731 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009732 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9733 if (FoldI)
9734 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009735 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009736
Chris Lattner7f239582009-10-22 00:17:26 +00009737 // See if we can fold the select into a phi node if the condition is a select.
9738 if (isa<PHINode>(SI.getCondition()))
9739 // The true/false values have to be live in the PHI predecessor's blocks.
9740 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9741 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9742 if (Instruction *NV = FoldOpIntoPhi(SI))
9743 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009744
Chris Lattnera1df33c2005-04-24 07:30:14 +00009745 if (BinaryOperator::isNot(CondVal)) {
9746 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9747 SI.setOperand(1, FalseVal);
9748 SI.setOperand(2, TrueVal);
9749 return &SI;
9750 }
9751
Chris Lattner3d69f462004-03-12 05:52:32 +00009752 return 0;
9753}
9754
Dan Gohmaneee962e2008-04-10 18:43:06 +00009755/// EnforceKnownAlignment - If the specified pointer points to an object that
9756/// we control, modify the object's alignment to PrefAlign. This isn't
9757/// often possible though. If alignment is important, a more reliable approach
9758/// is to simply align all global variables and allocation instructions to
9759/// their preferred alignment from the beginning.
9760///
9761static unsigned EnforceKnownAlignment(Value *V,
9762 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009763
Dan Gohmaneee962e2008-04-10 18:43:06 +00009764 User *U = dyn_cast<User>(V);
9765 if (!U) return Align;
9766
Dan Gohmanca178902009-07-17 20:47:02 +00009767 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009768 default: break;
9769 case Instruction::BitCast:
9770 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9771 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009772 // If all indexes are zero, it is just the alignment of the base pointer.
9773 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009774 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009775 if (!isa<Constant>(*i) ||
9776 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009777 AllZeroOperands = false;
9778 break;
9779 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009780
9781 if (AllZeroOperands) {
9782 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009783 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009784 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009785 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009786 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009787 }
9788
9789 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9790 // If there is a large requested alignment and we can, bump up the alignment
9791 // of the global.
9792 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009793 if (GV->getAlignment() >= PrefAlign)
9794 Align = GV->getAlignment();
9795 else {
9796 GV->setAlignment(PrefAlign);
9797 Align = PrefAlign;
9798 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009799 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009800 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9801 // If there is a requested alignment and if this is an alloca, round up.
9802 if (AI->getAlignment() >= PrefAlign)
9803 Align = AI->getAlignment();
9804 else {
9805 AI->setAlignment(PrefAlign);
9806 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009807 }
9808 }
9809
9810 return Align;
9811}
9812
9813/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9814/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9815/// and it is more than the alignment of the ultimate object, see if we can
9816/// increase the alignment of the ultimate object, making this check succeed.
9817unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9818 unsigned PrefAlign) {
9819 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9820 sizeof(PrefAlign) * CHAR_BIT;
9821 APInt Mask = APInt::getAllOnesValue(BitWidth);
9822 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9823 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9824 unsigned TrailZ = KnownZero.countTrailingOnes();
9825 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9826
9827 if (PrefAlign > Align)
9828 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9829
9830 // We don't need to make any adjustment.
9831 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009832}
9833
Chris Lattnerf497b022008-01-13 23:50:23 +00009834Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009835 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009836 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009837 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009838 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009839
9840 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009841 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009842 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009843 return MI;
9844 }
9845
9846 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9847 // load/store.
9848 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9849 if (MemOpLength == 0) return 0;
9850
Chris Lattner37ac6082008-01-14 00:28:35 +00009851 // Source and destination pointer types are always "i8*" for intrinsic. See
9852 // if the size is something we can handle with a single primitive load/store.
9853 // A single load+store correctly handles overlapping memory in the memmove
9854 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009855 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009856 if (Size == 0) return MI; // Delete this mem transfer.
9857
9858 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009859 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009860
Chris Lattner37ac6082008-01-14 00:28:35 +00009861 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009862 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009863 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009864
9865 // Memcpy forces the use of i8* for the source and destination. That means
9866 // that if you're using memcpy to move one double around, you'll get a cast
9867 // from double* to i8*. We'd much rather use a double load+store rather than
9868 // an i64 load+store, here because this improves the odds that the source or
9869 // dest address will be promotable. See if we can find a better type than the
9870 // integer datatype.
9871 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9872 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009873 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009874 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9875 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009876 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009877 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9878 if (STy->getNumElements() == 1)
9879 SrcETy = STy->getElementType(0);
9880 else
9881 break;
9882 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9883 if (ATy->getNumElements() == 1)
9884 SrcETy = ATy->getElementType();
9885 else
9886 break;
9887 } else
9888 break;
9889 }
9890
Dan Gohman8f8e2692008-05-23 01:52:21 +00009891 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009892 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009893 }
9894 }
9895
9896
Chris Lattnerf497b022008-01-13 23:50:23 +00009897 // If the memcpy/memmove provides better alignment info than we can
9898 // infer, use it.
9899 SrcAlign = std::max(SrcAlign, CopyAlign);
9900 DstAlign = std::max(DstAlign, CopyAlign);
9901
Chris Lattner08142f22009-08-30 19:47:22 +00009902 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9903 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009904 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9905 InsertNewInstBefore(L, *MI);
9906 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9907
9908 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009909 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009910 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009911}
Chris Lattner3d69f462004-03-12 05:52:32 +00009912
Chris Lattner69ea9d22008-04-30 06:39:11 +00009913Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9914 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009915 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009916 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009917 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009918 return MI;
9919 }
9920
9921 // Extract the length and alignment and fill if they are constant.
9922 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9923 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009924 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009925 return 0;
9926 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009927 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009928
9929 // If the length is zero, this is a no-op
9930 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9931
9932 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9933 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009934 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009935
9936 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009937 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009938
9939 // Alignment 0 is identity for alignment 1 for memset, but not store.
9940 if (Alignment == 0) Alignment = 1;
9941
9942 // Extract the fill value and store.
9943 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009944 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009945 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009946
9947 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009948 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009949 return MI;
9950 }
9951
9952 return 0;
9953}
9954
9955
Chris Lattner8b0ea312006-01-13 20:11:04 +00009956/// visitCallInst - CallInst simplification. This mostly only handles folding
9957/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9958/// the heavy lifting.
9959///
Chris Lattner9fe38862003-06-19 17:00:31 +00009960Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009961 if (isFreeCall(&CI))
9962 return visitFree(CI);
9963
Chris Lattneraab6ec42009-05-13 17:39:14 +00009964 // If the caller function is nounwind, mark the call as nounwind, even if the
9965 // callee isn't.
9966 if (CI.getParent()->getParent()->doesNotThrow() &&
9967 !CI.doesNotThrow()) {
9968 CI.setDoesNotThrow();
9969 return &CI;
9970 }
9971
Chris Lattner8b0ea312006-01-13 20:11:04 +00009972 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9973 if (!II) return visitCallSite(&CI);
9974
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009975 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9976 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009977 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009978 bool Changed = false;
9979
9980 // memmove/cpy/set of zero bytes is a noop.
9981 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9982 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9983
Chris Lattner35b9e482004-10-12 04:52:52 +00009984 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009985 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009986 // Replace the instruction with just byte operations. We would
9987 // transform other cases to loads/stores, but we don't know if
9988 // alignment is sufficient.
9989 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009990 }
9991
Chris Lattner35b9e482004-10-12 04:52:52 +00009992 // If we have a memmove and the source operation is a constant global,
9993 // then the source and dest pointers can't alias, so we can change this
9994 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009995 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009996 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9997 if (GVSrc->isConstant()) {
9998 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009999 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10000 const Type *Tys[1];
10001 Tys[0] = CI.getOperand(3)->getType();
10002 CI.setOperand(0,
10003 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010004 Changed = true;
10005 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010006 }
Chris Lattnera935db82008-05-28 05:30:41 +000010007
Eli Friedman0c826d92009-12-17 21:07:31 +000010008 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010009 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010010 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010011 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010012 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010013
Chris Lattner95a959d2006-03-06 20:18:44 +000010014 // If we can determine a pointer alignment that is bigger than currently
10015 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010016 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010017 if (Instruction *I = SimplifyMemTransfer(MI))
10018 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010019 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10020 if (Instruction *I = SimplifyMemSet(MSI))
10021 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010022 }
10023
Chris Lattner8b0ea312006-01-13 20:11:04 +000010024 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010025 }
10026
10027 switch (II->getIntrinsicID()) {
10028 default: break;
10029 case Intrinsic::bswap:
10030 // bswap(bswap(x)) -> x
10031 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10032 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10033 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
10034 break;
Chris Lattner2bbac752009-11-26 21:42:47 +000010035 case Intrinsic::uadd_with_overflow: {
10036 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10037 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10038 uint32_t BitWidth = IT->getBitWidth();
10039 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010040 APInt LHSKnownZero(BitWidth, 0);
10041 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010042 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10043 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10044 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10045
10046 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010047 APInt RHSKnownZero(BitWidth, 0);
10048 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010049 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10050 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10051 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10052 if (LHSKnownNegative && RHSKnownNegative) {
10053 // The sign bit is set in both cases: this MUST overflow.
10054 // Create a simple add instruction, and insert it into the struct.
10055 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10056 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010057 Constant *V[] = {
10058 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10059 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010060 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10061 return InsertValueInst::Create(Struct, Add, 0);
10062 }
10063
10064 if (LHSKnownPositive && RHSKnownPositive) {
10065 // The sign bit is clear in both cases: this CANNOT overflow.
10066 // Create a simple add instruction, and insert it into the struct.
10067 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10068 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010069 Constant *V[] = {
10070 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10071 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010072 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10073 return InsertValueInst::Create(Struct, Add, 0);
10074 }
10075 }
10076 }
10077 // FALL THROUGH uadd into sadd
10078 case Intrinsic::sadd_with_overflow:
10079 // Canonicalize constants into the RHS.
10080 if (isa<Constant>(II->getOperand(1)) &&
10081 !isa<Constant>(II->getOperand(2))) {
10082 Value *LHS = II->getOperand(1);
10083 II->setOperand(1, II->getOperand(2));
10084 II->setOperand(2, LHS);
10085 return II;
10086 }
10087
10088 // X + undef -> undef
10089 if (isa<UndefValue>(II->getOperand(2)))
10090 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10091
10092 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10093 // X + 0 -> {X, false}
10094 if (RHS->isZero()) {
10095 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010096 UndefValue::get(II->getOperand(0)->getType()),
10097 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010098 };
10099 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10100 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10101 }
10102 }
10103 break;
10104 case Intrinsic::usub_with_overflow:
10105 case Intrinsic::ssub_with_overflow:
10106 // undef - X -> undef
10107 // X - undef -> undef
10108 if (isa<UndefValue>(II->getOperand(1)) ||
10109 isa<UndefValue>(II->getOperand(2)))
10110 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10111
10112 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10113 // X - 0 -> {X, false}
10114 if (RHS->isZero()) {
10115 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010116 UndefValue::get(II->getOperand(1)->getType()),
10117 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010118 };
10119 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10120 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10121 }
10122 }
10123 break;
10124 case Intrinsic::umul_with_overflow:
10125 case Intrinsic::smul_with_overflow:
10126 // Canonicalize constants into the RHS.
10127 if (isa<Constant>(II->getOperand(1)) &&
10128 !isa<Constant>(II->getOperand(2))) {
10129 Value *LHS = II->getOperand(1);
10130 II->setOperand(1, II->getOperand(2));
10131 II->setOperand(2, LHS);
10132 return II;
10133 }
10134
10135 // X * undef -> undef
10136 if (isa<UndefValue>(II->getOperand(2)))
10137 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10138
10139 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10140 // X*0 -> {0, false}
10141 if (RHSI->isZero())
10142 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10143
10144 // X * 1 -> {X, false}
10145 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010146 Constant *V[] = {
10147 UndefValue::get(II->getOperand(1)->getType()),
10148 ConstantInt::getFalse(*Context)
10149 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010150 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010151 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010152 }
10153 }
10154 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010155 case Intrinsic::ppc_altivec_lvx:
10156 case Intrinsic::ppc_altivec_lvxl:
10157 case Intrinsic::x86_sse_loadu_ps:
10158 case Intrinsic::x86_sse2_loadu_pd:
10159 case Intrinsic::x86_sse2_loadu_dq:
10160 // Turn PPC lvx -> load if the pointer is known aligned.
10161 // Turn X86 loadups -> load if the pointer is known aligned.
10162 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010163 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10164 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010165 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010166 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010167 break;
10168 case Intrinsic::ppc_altivec_stvx:
10169 case Intrinsic::ppc_altivec_stvxl:
10170 // Turn stvx -> store if the pointer is known aligned.
10171 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10172 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010173 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010174 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010175 return new StoreInst(II->getOperand(1), Ptr);
10176 }
10177 break;
10178 case Intrinsic::x86_sse_storeu_ps:
10179 case Intrinsic::x86_sse2_storeu_pd:
10180 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010181 // Turn X86 storeu -> store if the pointer is known aligned.
10182 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10183 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010184 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010185 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010186 return new StoreInst(II->getOperand(2), Ptr);
10187 }
10188 break;
10189
10190 case Intrinsic::x86_sse_cvttss2si: {
10191 // These intrinsics only demands the 0th element of its input vector. If
10192 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010193 unsigned VWidth =
10194 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10195 APInt DemandedElts(VWidth, 1);
10196 APInt UndefElts(VWidth, 0);
10197 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010198 UndefElts)) {
10199 II->setOperand(1, V);
10200 return II;
10201 }
10202 break;
10203 }
10204
10205 case Intrinsic::ppc_altivec_vperm:
10206 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10207 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10208 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010209
Chris Lattner0521e3c2008-06-18 04:33:20 +000010210 // Check that all of the elements are integer constants or undefs.
10211 bool AllEltsOk = true;
10212 for (unsigned i = 0; i != 16; ++i) {
10213 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10214 !isa<UndefValue>(Mask->getOperand(i))) {
10215 AllEltsOk = false;
10216 break;
10217 }
10218 }
10219
10220 if (AllEltsOk) {
10221 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010222 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10223 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010224 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010225
Chris Lattner0521e3c2008-06-18 04:33:20 +000010226 // Only extract each element once.
10227 Value *ExtractedElts[32];
10228 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10229
Chris Lattnere2ed0572006-04-06 19:19:17 +000010230 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010231 if (isa<UndefValue>(Mask->getOperand(i)))
10232 continue;
10233 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10234 Idx &= 31; // Match the hardware behavior.
10235
10236 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010237 ExtractedElts[Idx] =
10238 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10239 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10240 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010241 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010242
Chris Lattner0521e3c2008-06-18 04:33:20 +000010243 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010244 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10245 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10246 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010247 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010248 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010249 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010250 }
10251 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010252
Chris Lattner0521e3c2008-06-18 04:33:20 +000010253 case Intrinsic::stackrestore: {
10254 // If the save is right next to the restore, remove the restore. This can
10255 // happen when variable allocas are DCE'd.
10256 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10257 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10258 BasicBlock::iterator BI = SS;
10259 if (&*++BI == II)
10260 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010261 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010262 }
10263
10264 // Scan down this block to see if there is another stack restore in the
10265 // same block without an intervening call/alloca.
10266 BasicBlock::iterator BI = II;
10267 TerminatorInst *TI = II->getParent()->getTerminator();
10268 bool CannotRemove = false;
10269 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010270 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010271 CannotRemove = true;
10272 break;
10273 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010274 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10275 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10276 // If there is a stackrestore below this one, remove this one.
10277 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10278 return EraseInstFromFunction(CI);
10279 // Otherwise, ignore the intrinsic.
10280 } else {
10281 // If we found a non-intrinsic call, we can't remove the stack
10282 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010283 CannotRemove = true;
10284 break;
10285 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010286 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010287 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010288
10289 // If the stack restore is in a return/unwind block and if there are no
10290 // allocas or calls between the restore and the return, nuke the restore.
10291 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10292 return EraseInstFromFunction(CI);
10293 break;
10294 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010295 }
10296
Chris Lattner8b0ea312006-01-13 20:11:04 +000010297 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010298}
10299
10300// InvokeInst simplification
10301//
10302Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010303 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010304}
10305
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010306/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10307/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010308static bool isSafeToEliminateVarargsCast(const CallSite CS,
10309 const CastInst * const CI,
10310 const TargetData * const TD,
10311 const int ix) {
10312 if (!CI->isLosslessCast())
10313 return false;
10314
10315 // The size of ByVal arguments is derived from the type, so we
10316 // can't change to a type with a different size. If the size were
10317 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010318 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010319 return true;
10320
10321 const Type* SrcTy =
10322 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10323 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10324 if (!SrcTy->isSized() || !DstTy->isSized())
10325 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010326 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010327 return false;
10328 return true;
10329}
10330
Chris Lattnera44d8a22003-10-07 22:32:43 +000010331// visitCallSite - Improvements for call and invoke instructions.
10332//
10333Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010334 bool Changed = false;
10335
10336 // If the callee is a constexpr cast of a function, attempt to move the cast
10337 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010338 if (transformConstExprCastCall(CS)) return 0;
10339
Chris Lattner6c266db2003-10-07 22:54:13 +000010340 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010341
Chris Lattner08b22ec2005-05-13 07:09:09 +000010342 if (Function *CalleeF = dyn_cast<Function>(Callee))
10343 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10344 Instruction *OldCall = CS.getInstruction();
10345 // If the call and callee calling conventions don't match, this call must
10346 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010347 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010348 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010349 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010350 // If OldCall dues not return void then replaceAllUsesWith undef.
10351 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010352 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010353 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010354 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10355 return EraseInstFromFunction(*OldCall);
10356 return 0;
10357 }
10358
Chris Lattner17be6352004-10-18 02:59:09 +000010359 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10360 // This instruction is not reachable, just remove it. We insert a store to
10361 // undef so that we know that this code is not reachable, despite the fact
10362 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010363 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010364 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010365 CS.getInstruction());
10366
Devang Patel228ebd02009-10-13 22:56:32 +000010367 // If CS dues not return void then replaceAllUsesWith undef.
10368 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010369 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010370 CS.getInstruction()->
10371 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010372
10373 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10374 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010375 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010376 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010377 }
Chris Lattner17be6352004-10-18 02:59:09 +000010378 return EraseInstFromFunction(*CS.getInstruction());
10379 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010380
Duncan Sandscdb6d922007-09-17 10:26:40 +000010381 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10382 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10383 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10384 return transformCallThroughTrampoline(CS);
10385
Chris Lattner6c266db2003-10-07 22:54:13 +000010386 const PointerType *PTy = cast<PointerType>(Callee->getType());
10387 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10388 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010389 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010390 // See if we can optimize any arguments passed through the varargs area of
10391 // the call.
10392 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010393 E = CS.arg_end(); I != E; ++I, ++ix) {
10394 CastInst *CI = dyn_cast<CastInst>(*I);
10395 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10396 *I = CI->getOperand(0);
10397 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010398 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010399 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010400 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010401
Duncan Sandsf0c33542007-12-19 21:13:37 +000010402 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010403 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010404 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010405 Changed = true;
10406 }
10407
Chris Lattner6c266db2003-10-07 22:54:13 +000010408 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010409}
10410
Chris Lattner9fe38862003-06-19 17:00:31 +000010411// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10412// attempt to move the cast to the arguments of the call/invoke.
10413//
10414bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10415 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10416 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010417 if (CE->getOpcode() != Instruction::BitCast ||
10418 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010419 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010420 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010421 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010422 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010423
10424 // Okay, this is a cast from a function to a different type. Unless doing so
10425 // would cause a type conversion of one of our arguments, change this call to
10426 // be a direct call with arguments casted to the appropriate types.
10427 //
10428 const FunctionType *FT = Callee->getFunctionType();
10429 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010430 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010431
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010432 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010433 return false; // TODO: Handle multiple return values.
10434
Chris Lattnerf78616b2004-01-14 06:06:08 +000010435 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010436 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010437 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010438 // Conversion is ok if changing from one pointer type to another or from
10439 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010440 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010441 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010442 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010443 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010444 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010445
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010446 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010447 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010448 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010449 return false; // Cannot transform this return value.
10450
Chris Lattner58d74912008-03-12 17:45:29 +000010451 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010452 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010453 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010454 return false; // Attribute not compatible with transformed value.
10455 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010456
Chris Lattnerf78616b2004-01-14 06:06:08 +000010457 // If the callsite is an invoke instruction, and the return value is used by
10458 // a PHI node in a successor, we cannot change the return type of the call
10459 // because there is no place to put the cast instruction (without breaking
10460 // the critical edge). Bail out in this case.
10461 if (!Caller->use_empty())
10462 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10463 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10464 UI != E; ++UI)
10465 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10466 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010467 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010468 return false;
10469 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010470
10471 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10472 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010473
Chris Lattner9fe38862003-06-19 17:00:31 +000010474 CallSite::arg_iterator AI = CS.arg_begin();
10475 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10476 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010477 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010478
10479 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010480 return false; // Cannot transform this parameter value.
10481
Devang Patel19c87462008-09-26 22:53:05 +000010482 if (CallerPAL.getParamAttributes(i + 1)
10483 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010484 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010485
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010486 // Converting from one pointer type to another or between a pointer and an
10487 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010488 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010489 (TD && ((isa<PointerType>(ParamTy) ||
10490 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10491 (isa<PointerType>(ActTy) ||
10492 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010493 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010494 }
10495
10496 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010497 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010498 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010499
Chris Lattner58d74912008-03-12 17:45:29 +000010500 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10501 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010502 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010503 // won't be dropping them. Check that these extra arguments have attributes
10504 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010505 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10506 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010507 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010508 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010509 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010510 return false;
10511 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010512
Chris Lattner9fe38862003-06-19 17:00:31 +000010513 // Okay, we decided that this is a safe thing to do: go ahead and start
10514 // inserting cast instructions as necessary...
10515 std::vector<Value*> Args;
10516 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010517 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010518 attrVec.reserve(NumCommonArgs);
10519
10520 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010521 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010522
10523 // If the return value is not being used, the type may not be compatible
10524 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010525 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010526
10527 // Add the new return attributes.
10528 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010529 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010530
10531 AI = CS.arg_begin();
10532 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10533 const Type *ParamTy = FT->getParamType(i);
10534 if ((*AI)->getType() == ParamTy) {
10535 Args.push_back(*AI);
10536 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010537 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010538 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010539 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010540 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010541
10542 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010543 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010544 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010545 }
10546
10547 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010548 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010549 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010550 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010551
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010552 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010553 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010554 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010555 errs() << "WARNING: While resolving call to function '"
10556 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010557 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010558 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010559 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10560 const Type *PTy = getPromotedType((*AI)->getType());
10561 if (PTy != (*AI)->getType()) {
10562 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010563 Instruction::CastOps opcode =
10564 CastInst::getCastOpcode(*AI, false, PTy, false);
10565 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010566 } else {
10567 Args.push_back(*AI);
10568 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010569
Duncan Sandse1e520f2008-01-13 08:02:44 +000010570 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010571 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010572 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010573 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010574 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010575 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010576
Devang Patel19c87462008-09-26 22:53:05 +000010577 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10578 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10579
Devang Patel9674d152009-10-14 17:29:00 +000010580 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010581 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010582
Eric Christophera66297a2009-07-25 02:45:27 +000010583 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10584 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010585
Chris Lattner9fe38862003-06-19 17:00:31 +000010586 Instruction *NC;
10587 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010588 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010589 Args.begin(), Args.end(),
10590 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010591 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010592 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010593 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010594 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10595 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010596 CallInst *CI = cast<CallInst>(Caller);
10597 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010598 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010599 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010600 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010601 }
10602
Chris Lattner6934a042007-02-11 01:23:03 +000010603 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010604 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010605 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010606 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010607 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010608 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010609 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010610
10611 // If this is an invoke instruction, we should insert it after the first
10612 // non-phi, instruction in the normal successor block.
10613 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010614 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010615 InsertNewInstBefore(NC, *I);
10616 } else {
10617 // Otherwise, it's a call, just insert cast right after the call instr
10618 InsertNewInstBefore(NC, *Caller);
10619 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010620 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010621 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010622 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010623 }
10624 }
10625
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010626
Chris Lattner931f8f32009-08-31 05:17:58 +000010627 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010628 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010629
10630 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010631 return true;
10632}
10633
Duncan Sandscdb6d922007-09-17 10:26:40 +000010634// transformCallThroughTrampoline - Turn a call to a function created by the
10635// init_trampoline intrinsic into a direct call to the underlying function.
10636//
10637Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10638 Value *Callee = CS.getCalledValue();
10639 const PointerType *PTy = cast<PointerType>(Callee->getType());
10640 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010641 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010642
10643 // If the call already has the 'nest' attribute somewhere then give up -
10644 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010645 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010646 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010647
10648 IntrinsicInst *Tramp =
10649 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10650
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010651 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010652 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10653 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10654
Devang Patel05988662008-09-25 21:00:45 +000010655 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010656 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010657 unsigned NestIdx = 1;
10658 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010659 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010660
10661 // Look for a parameter marked with the 'nest' attribute.
10662 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10663 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010664 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010665 // Record the parameter type and any other attributes.
10666 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010667 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010668 break;
10669 }
10670
10671 if (NestTy) {
10672 Instruction *Caller = CS.getInstruction();
10673 std::vector<Value*> NewArgs;
10674 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10675
Devang Patel05988662008-09-25 21:00:45 +000010676 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010677 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010678
Duncan Sandscdb6d922007-09-17 10:26:40 +000010679 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010680 // mean appending it. Likewise for attributes.
10681
Devang Patel19c87462008-09-26 22:53:05 +000010682 // Add any result attributes.
10683 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010684 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010685
Duncan Sandscdb6d922007-09-17 10:26:40 +000010686 {
10687 unsigned Idx = 1;
10688 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10689 do {
10690 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010691 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010692 Value *NestVal = Tramp->getOperand(3);
10693 if (NestVal->getType() != NestTy)
10694 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10695 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010696 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010697 }
10698
10699 if (I == E)
10700 break;
10701
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010702 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010703 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010704 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010705 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010706 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010707
10708 ++Idx, ++I;
10709 } while (1);
10710 }
10711
Devang Patel19c87462008-09-26 22:53:05 +000010712 // Add any function attributes.
10713 if (Attributes Attr = Attrs.getFnAttributes())
10714 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10715
Duncan Sandscdb6d922007-09-17 10:26:40 +000010716 // The trampoline may have been bitcast to a bogus type (FTy).
10717 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010718 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010719
Duncan Sandscdb6d922007-09-17 10:26:40 +000010720 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010721 NewTypes.reserve(FTy->getNumParams()+1);
10722
Duncan Sandscdb6d922007-09-17 10:26:40 +000010723 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010724 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010725 {
10726 unsigned Idx = 1;
10727 FunctionType::param_iterator I = FTy->param_begin(),
10728 E = FTy->param_end();
10729
10730 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010731 if (Idx == NestIdx)
10732 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010733 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010734
10735 if (I == E)
10736 break;
10737
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010738 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010739 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010740
10741 ++Idx, ++I;
10742 } while (1);
10743 }
10744
10745 // Replace the trampoline call with a direct call. Let the generic
10746 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010747 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010748 FTy->isVarArg());
10749 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010750 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010751 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010752 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010753 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10754 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010755
10756 Instruction *NewCaller;
10757 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010758 NewCaller = InvokeInst::Create(NewCallee,
10759 II->getNormalDest(), II->getUnwindDest(),
10760 NewArgs.begin(), NewArgs.end(),
10761 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010762 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010763 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010764 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010765 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10766 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010767 if (cast<CallInst>(Caller)->isTailCall())
10768 cast<CallInst>(NewCaller)->setTailCall();
10769 cast<CallInst>(NewCaller)->
10770 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010771 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010772 }
Devang Patel9674d152009-10-14 17:29:00 +000010773 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010774 Caller->replaceAllUsesWith(NewCaller);
10775 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010776 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010777 return 0;
10778 }
10779 }
10780
10781 // Replace the trampoline call with a direct call. Since there is no 'nest'
10782 // parameter, there is no need to adjust the argument list. Let the generic
10783 // code sort out any function type mismatches.
10784 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010785 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010786 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010787 CS.setCalledFunction(NewCallee);
10788 return CS.getInstruction();
10789}
10790
Dan Gohman9ad29202009-09-16 16:50:24 +000010791/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10792/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010793/// and a single binop.
10794Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10795 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010796 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010797 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010798 Value *LHSVal = FirstInst->getOperand(0);
10799 Value *RHSVal = FirstInst->getOperand(1);
10800
10801 const Type *LHSType = LHSVal->getType();
10802 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010803
Dan Gohman9ad29202009-09-16 16:50:24 +000010804 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010805 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010806 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010807 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010808 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010809 // types or GEP's with different index types.
10810 I->getOperand(0)->getType() != LHSType ||
10811 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010812 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010813
10814 // If they are CmpInst instructions, check their predicates
10815 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10816 if (cast<CmpInst>(I)->getPredicate() !=
10817 cast<CmpInst>(FirstInst)->getPredicate())
10818 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010819
10820 // Keep track of which operand needs a phi node.
10821 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10822 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010823 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010824
10825 // If both LHS and RHS would need a PHI, don't do this transformation,
10826 // because it would increase the number of PHIs entering the block,
10827 // which leads to higher register pressure. This is especially
10828 // bad when the PHIs are in the header of a loop.
10829 if (!LHSVal && !RHSVal)
10830 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010831
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010832 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010833
Chris Lattner7da52b22006-11-01 04:51:18 +000010834 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010835 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010836 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010837 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010838 NewLHS = PHINode::Create(LHSType,
10839 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010840 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10841 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010842 InsertNewInstBefore(NewLHS, PN);
10843 LHSVal = NewLHS;
10844 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010845
10846 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010847 NewRHS = PHINode::Create(RHSType,
10848 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010849 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10850 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010851 InsertNewInstBefore(NewRHS, PN);
10852 RHSVal = NewRHS;
10853 }
10854
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010855 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010856 if (NewLHS || NewRHS) {
10857 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10858 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10859 if (NewLHS) {
10860 Value *NewInLHS = InInst->getOperand(0);
10861 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10862 }
10863 if (NewRHS) {
10864 Value *NewInRHS = InInst->getOperand(1);
10865 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10866 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010867 }
10868 }
10869
Chris Lattner7da52b22006-11-01 04:51:18 +000010870 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010871 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010872 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010873 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010874 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010875}
10876
Chris Lattner05f18922008-12-01 02:34:36 +000010877Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10878 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10879
10880 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10881 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010882 // This is true if all GEP bases are allocas and if all indices into them are
10883 // constants.
10884 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010885
10886 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010887 // more than one phi, which leads to higher register pressure. This is
10888 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010889 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010890
Dan Gohman9ad29202009-09-16 16:50:24 +000010891 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010892 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10893 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10894 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10895 GEP->getNumOperands() != FirstInst->getNumOperands())
10896 return 0;
10897
Chris Lattner36d3e322009-02-21 00:46:50 +000010898 // Keep track of whether or not all GEPs are of alloca pointers.
10899 if (AllBasePointersAreAllocas &&
10900 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10901 !GEP->hasAllConstantIndices()))
10902 AllBasePointersAreAllocas = false;
10903
Chris Lattner05f18922008-12-01 02:34:36 +000010904 // Compare the operand lists.
10905 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10906 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10907 continue;
10908
10909 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10910 // if one of the PHIs has a constant for the index. The index may be
10911 // substantially cheaper to compute for the constants, so making it a
10912 // variable index could pessimize the path. This also handles the case
10913 // for struct indices, which must always be constant.
10914 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10915 isa<ConstantInt>(GEP->getOperand(op)))
10916 return 0;
10917
10918 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10919 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010920
10921 // If we already needed a PHI for an earlier operand, and another operand
10922 // also requires a PHI, we'd be introducing more PHIs than we're
10923 // eliminating, which increases register pressure on entry to the PHI's
10924 // block.
10925 if (NeededPhi)
10926 return 0;
10927
Chris Lattner05f18922008-12-01 02:34:36 +000010928 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010929 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010930 }
10931 }
10932
Chris Lattner36d3e322009-02-21 00:46:50 +000010933 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010934 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010935 // offset calculation, but all the predecessors will have to materialize the
10936 // stack address into a register anyway. We'd actually rather *clone* the
10937 // load up into the predecessors so that we have a load of a gep of an alloca,
10938 // which can usually all be folded into the load.
10939 if (AllBasePointersAreAllocas)
10940 return 0;
10941
Chris Lattner05f18922008-12-01 02:34:36 +000010942 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10943 // that is variable.
10944 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10945
10946 bool HasAnyPHIs = false;
10947 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10948 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10949 Value *FirstOp = FirstInst->getOperand(i);
10950 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10951 FirstOp->getName()+".pn");
10952 InsertNewInstBefore(NewPN, PN);
10953
10954 NewPN->reserveOperandSpace(e);
10955 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10956 OperandPhis[i] = NewPN;
10957 FixedOperands[i] = NewPN;
10958 HasAnyPHIs = true;
10959 }
10960
10961
10962 // Add all operands to the new PHIs.
10963 if (HasAnyPHIs) {
10964 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10965 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10966 BasicBlock *InBB = PN.getIncomingBlock(i);
10967
10968 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10969 if (PHINode *OpPhi = OperandPhis[op])
10970 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10971 }
10972 }
10973
10974 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010975 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10976 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10977 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010978 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10979 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010980}
10981
10982
Chris Lattner21550882009-02-23 05:56:17 +000010983/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10984/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010985/// obvious the value of the load is not changed from the point of the load to
10986/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010987///
10988/// Finally, it is safe, but not profitable, to sink a load targetting a
10989/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10990/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010991static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010992 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10993
10994 for (++BBI; BBI != E; ++BBI)
10995 if (BBI->mayWriteToMemory())
10996 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010997
10998 // Check for non-address taken alloca. If not address-taken already, it isn't
10999 // profitable to do this xform.
11000 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11001 bool isAddressTaken = false;
11002 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11003 UI != E; ++UI) {
11004 if (isa<LoadInst>(UI)) continue;
11005 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11006 // If storing TO the alloca, then the address isn't taken.
11007 if (SI->getOperand(1) == AI) continue;
11008 }
11009 isAddressTaken = true;
11010 break;
11011 }
11012
Chris Lattner36d3e322009-02-21 00:46:50 +000011013 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011014 return false;
11015 }
11016
Chris Lattner36d3e322009-02-21 00:46:50 +000011017 // If this load is a load from a GEP with a constant offset from an alloca,
11018 // then we don't want to sink it. In its present form, it will be
11019 // load [constant stack offset]. Sinking it will cause us to have to
11020 // materialize the stack addresses in each predecessor in a register only to
11021 // do a shared load from register in the successor.
11022 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11023 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11024 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11025 return false;
11026
Chris Lattner76c73142006-11-01 07:13:54 +000011027 return true;
11028}
11029
Chris Lattner751a3622009-11-01 20:04:24 +000011030Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11031 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11032
11033 // When processing loads, we need to propagate two bits of information to the
11034 // sunk load: whether it is volatile, and what its alignment is. We currently
11035 // don't sink loads when some have their alignment specified and some don't.
11036 // visitLoadInst will propagate an alignment onto the load when TD is around,
11037 // and if TD isn't around, we can't handle the mixed case.
11038 bool isVolatile = FirstLI->isVolatile();
11039 unsigned LoadAlignment = FirstLI->getAlignment();
11040
11041 // We can't sink the load if the loaded value could be modified between the
11042 // load and the PHI.
11043 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11044 !isSafeAndProfitableToSinkLoad(FirstLI))
11045 return 0;
11046
11047 // If the PHI is of volatile loads and the load block has multiple
11048 // successors, sinking it would remove a load of the volatile value from
11049 // the path through the other successor.
11050 if (isVolatile &&
11051 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11052 return 0;
11053
11054 // Check to see if all arguments are the same operation.
11055 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11056 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11057 if (!LI || !LI->hasOneUse())
11058 return 0;
11059
11060 // We can't sink the load if the loaded value could be modified between
11061 // the load and the PHI.
11062 if (LI->isVolatile() != isVolatile ||
11063 LI->getParent() != PN.getIncomingBlock(i) ||
11064 !isSafeAndProfitableToSinkLoad(LI))
11065 return 0;
11066
11067 // If some of the loads have an alignment specified but not all of them,
11068 // we can't do the transformation.
11069 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11070 return 0;
11071
Chris Lattnera664bb72009-11-01 20:07:07 +000011072 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011073
11074 // If the PHI is of volatile loads and the load block has multiple
11075 // successors, sinking it would remove a load of the volatile value from
11076 // the path through the other successor.
11077 if (isVolatile &&
11078 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11079 return 0;
11080 }
11081
11082 // Okay, they are all the same operation. Create a new PHI node of the
11083 // correct type, and PHI together all of the LHS's of the instructions.
11084 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11085 PN.getName()+".in");
11086 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11087
11088 Value *InVal = FirstLI->getOperand(0);
11089 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11090
11091 // Add all operands to the new PHI.
11092 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11093 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11094 if (NewInVal != InVal)
11095 InVal = 0;
11096 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11097 }
11098
11099 Value *PhiVal;
11100 if (InVal) {
11101 // The new PHI unions all of the same values together. This is really
11102 // common, so we handle it intelligently here for compile-time speed.
11103 PhiVal = InVal;
11104 delete NewPN;
11105 } else {
11106 InsertNewInstBefore(NewPN, PN);
11107 PhiVal = NewPN;
11108 }
11109
11110 // If this was a volatile load that we are merging, make sure to loop through
11111 // and mark all the input loads as non-volatile. If we don't do this, we will
11112 // insert a new volatile load and the old ones will not be deletable.
11113 if (isVolatile)
11114 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11115 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11116
11117 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11118}
11119
Chris Lattner9fe38862003-06-19 17:00:31 +000011120
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011121
11122/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11123/// operator and they all are only used by the PHI, PHI together their
11124/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011125Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11126 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11127
Chris Lattner751a3622009-11-01 20:04:24 +000011128 if (isa<GetElementPtrInst>(FirstInst))
11129 return FoldPHIArgGEPIntoPHI(PN);
11130 if (isa<LoadInst>(FirstInst))
11131 return FoldPHIArgLoadIntoPHI(PN);
11132
Chris Lattnerbac32862004-11-14 19:13:23 +000011133 // Scan the instruction, looking for input operations that can be folded away.
11134 // If all input operands to the phi are the same instruction (e.g. a cast from
11135 // the same type or "+42") we can pull the operation through the PHI, reducing
11136 // code size and simplifying code.
11137 Constant *ConstantOp = 0;
11138 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011139
Chris Lattnerbac32862004-11-14 19:13:23 +000011140 if (isa<CastInst>(FirstInst)) {
11141 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011142
11143 // Be careful about transforming integer PHIs. We don't want to pessimize
11144 // the code by turning an i32 into an i1293.
11145 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011146 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011147 return 0;
11148 }
Reid Spencer832254e2007-02-02 02:16:23 +000011149 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011150 // Can fold binop, compare or shift here if the RHS is a constant,
11151 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011152 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011153 if (ConstantOp == 0)
11154 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011155 } else {
11156 return 0; // Cannot fold this operation.
11157 }
11158
11159 // Check to see if all arguments are the same operation.
11160 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011161 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11162 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011163 return 0;
11164 if (CastSrcTy) {
11165 if (I->getOperand(0)->getType() != CastSrcTy)
11166 return 0; // Cast operation must match.
11167 } else if (I->getOperand(1) != ConstantOp) {
11168 return 0;
11169 }
11170 }
11171
11172 // Okay, they are all the same operation. Create a new PHI node of the
11173 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011174 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11175 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011176 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011177
11178 Value *InVal = FirstInst->getOperand(0);
11179 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011180
11181 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011182 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11183 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11184 if (NewInVal != InVal)
11185 InVal = 0;
11186 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11187 }
11188
11189 Value *PhiVal;
11190 if (InVal) {
11191 // The new PHI unions all of the same values together. This is really
11192 // common, so we handle it intelligently here for compile-time speed.
11193 PhiVal = InVal;
11194 delete NewPN;
11195 } else {
11196 InsertNewInstBefore(NewPN, PN);
11197 PhiVal = NewPN;
11198 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011199
Chris Lattnerbac32862004-11-14 19:13:23 +000011200 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011201 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011202 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011203
Chris Lattner54545ac2008-04-29 17:13:43 +000011204 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011205 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011206
Chris Lattner751a3622009-11-01 20:04:24 +000011207 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11208 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11209 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011210}
Chris Lattnera1be5662002-05-02 17:06:02 +000011211
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011212/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11213/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011214static bool DeadPHICycle(PHINode *PN,
11215 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011216 if (PN->use_empty()) return true;
11217 if (!PN->hasOneUse()) return false;
11218
11219 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011220 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011221 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011222
11223 // Don't scan crazily complex things.
11224 if (PotentiallyDeadPHIs.size() == 16)
11225 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011226
11227 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11228 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011229
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011230 return false;
11231}
11232
Chris Lattnercf5008a2007-11-06 21:52:06 +000011233/// PHIsEqualValue - Return true if this phi node is always equal to
11234/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11235/// z = some value; x = phi (y, z); y = phi (x, z)
11236static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11237 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11238 // See if we already saw this PHI node.
11239 if (!ValueEqualPHIs.insert(PN))
11240 return true;
11241
11242 // Don't scan crazily complex things.
11243 if (ValueEqualPHIs.size() == 16)
11244 return false;
11245
11246 // Scan the operands to see if they are either phi nodes or are equal to
11247 // the value.
11248 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11249 Value *Op = PN->getIncomingValue(i);
11250 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11251 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11252 return false;
11253 } else if (Op != NonPhiInVal)
11254 return false;
11255 }
11256
11257 return true;
11258}
11259
11260
Chris Lattner9956c052009-11-08 19:23:30 +000011261namespace {
11262struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011263 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011264 unsigned Shift; // The amount shifted.
11265 Instruction *Inst; // The trunc instruction.
11266
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011267 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11268 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011269
11270 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011271 if (PHIId < RHS.PHIId) return true;
11272 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011273 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011274 if (Shift > RHS.Shift) return false;
11275 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011276 RHS.Inst->getType()->getPrimitiveSizeInBits();
11277 }
11278};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011279
11280struct LoweredPHIRecord {
11281 PHINode *PN; // The PHI that was lowered.
11282 unsigned Shift; // The amount shifted.
11283 unsigned Width; // The width extracted.
11284
11285 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11286 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11287
11288 // Ctor form used by DenseMap.
11289 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11290 : PN(pn), Shift(Sh), Width(0) {}
11291};
11292}
11293
11294namespace llvm {
11295 template<>
11296 struct DenseMapInfo<LoweredPHIRecord> {
11297 static inline LoweredPHIRecord getEmptyKey() {
11298 return LoweredPHIRecord(0, 0);
11299 }
11300 static inline LoweredPHIRecord getTombstoneKey() {
11301 return LoweredPHIRecord(0, 1);
11302 }
11303 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11304 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11305 (Val.Width>>3);
11306 }
11307 static bool isEqual(const LoweredPHIRecord &LHS,
11308 const LoweredPHIRecord &RHS) {
11309 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11310 LHS.Width == RHS.Width;
11311 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011312 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011313 template <>
11314 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011315}
11316
11317
11318/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11319/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11320/// so, we split the PHI into the various pieces being extracted. This sort of
11321/// thing is introduced when SROA promotes an aggregate to large integer values.
11322///
11323/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11324/// inttoptr. We should produce new PHIs in the right type.
11325///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011326Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11327 // PHIUsers - Keep track of all of the truncated values extracted from a set
11328 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011329 SmallVector<PHIUsageRecord, 16> PHIUsers;
11330
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011331 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11332 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11333 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11334 // check the uses of (to ensure they are all extracts).
11335 SmallVector<PHINode*, 8> PHIsToSlice;
11336 SmallPtrSet<PHINode*, 8> PHIsInspected;
11337
11338 PHIsToSlice.push_back(&FirstPhi);
11339 PHIsInspected.insert(&FirstPhi);
11340
11341 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11342 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011343
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011344 // Scan the input list of the PHI. If any input is an invoke, and if the
11345 // input is defined in the predecessor, then we won't be split the critical
11346 // edge which is required to insert a truncate. Because of this, we have to
11347 // bail out.
11348 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11349 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11350 if (II == 0) continue;
11351 if (II->getParent() != PN->getIncomingBlock(i))
11352 continue;
11353
11354 // If we have a phi, and if it's directly in the predecessor, then we have
11355 // a critical edge where we need to put the truncate. Since we can't
11356 // split the edge in instcombine, we have to bail out.
11357 return 0;
11358 }
11359
11360
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011361 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11362 UI != E; ++UI) {
11363 Instruction *User = cast<Instruction>(*UI);
11364
11365 // If the user is a PHI, inspect its uses recursively.
11366 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11367 if (PHIsInspected.insert(UserPN))
11368 PHIsToSlice.push_back(UserPN);
11369 continue;
11370 }
11371
11372 // Truncates are always ok.
11373 if (isa<TruncInst>(User)) {
11374 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11375 continue;
11376 }
11377
11378 // Otherwise it must be a lshr which can only be used by one trunc.
11379 if (User->getOpcode() != Instruction::LShr ||
11380 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11381 !isa<ConstantInt>(User->getOperand(1)))
11382 return 0;
11383
11384 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11385 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011386 }
Chris Lattner9956c052009-11-08 19:23:30 +000011387 }
11388
11389 // If we have no users, they must be all self uses, just nuke the PHI.
11390 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011391 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011392
11393 // If this phi node is transformable, create new PHIs for all the pieces
11394 // extracted out of it. First, sort the users by their offset and size.
11395 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11396
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011397 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11398 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11399 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11400 );
Chris Lattner9956c052009-11-08 19:23:30 +000011401
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011402 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11403 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011404 DenseMap<BasicBlock*, Value*> PredValues;
11405
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011406 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11407 // introduce redundant PHIs.
11408 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11409
11410 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11411 unsigned PHIId = PHIUsers[UserI].PHIId;
11412 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011413 unsigned Offset = PHIUsers[UserI].Shift;
11414 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011415
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011416 PHINode *EltPHI;
11417
11418 // If we've already lowered a user like this, reuse the previously lowered
11419 // value.
11420 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011421
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011422 // Otherwise, Create the new PHI node for this user.
11423 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11424 assert(EltPHI->getType() != PN->getType() &&
11425 "Truncate didn't shrink phi?");
11426
11427 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11428 BasicBlock *Pred = PN->getIncomingBlock(i);
11429 Value *&PredVal = PredValues[Pred];
11430
11431 // If we already have a value for this predecessor, reuse it.
11432 if (PredVal) {
11433 EltPHI->addIncoming(PredVal, Pred);
11434 continue;
11435 }
Chris Lattner9956c052009-11-08 19:23:30 +000011436
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011437 // Handle the PHI self-reuse case.
11438 Value *InVal = PN->getIncomingValue(i);
11439 if (InVal == PN) {
11440 PredVal = EltPHI;
11441 EltPHI->addIncoming(PredVal, Pred);
11442 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011443 }
11444
11445 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011446 // If the incoming value was a PHI, and if it was one of the PHIs we
11447 // already rewrote it, just use the lowered value.
11448 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11449 PredVal = Res;
11450 EltPHI->addIncoming(PredVal, Pred);
11451 continue;
11452 }
11453 }
11454
11455 // Otherwise, do an extract in the predecessor.
11456 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11457 Value *Res = InVal;
11458 if (Offset)
11459 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11460 Offset), "extract");
11461 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11462 PredVal = Res;
11463 EltPHI->addIncoming(Res, Pred);
11464
11465 // If the incoming value was a PHI, and if it was one of the PHIs we are
11466 // rewriting, we will ultimately delete the code we inserted. This
11467 // means we need to revisit that PHI to make sure we extract out the
11468 // needed piece.
11469 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11470 if (PHIsInspected.count(OldInVal)) {
11471 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11472 OldInVal)-PHIsToSlice.begin();
11473 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11474 cast<Instruction>(Res)));
11475 ++UserE;
11476 }
Chris Lattner9956c052009-11-08 19:23:30 +000011477 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011478 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011479
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011480 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11481 << *EltPHI << '\n');
11482 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011483 }
Chris Lattner9956c052009-11-08 19:23:30 +000011484
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011485 // Replace the use of this piece with the PHI node.
11486 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011487 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011488
11489 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11490 // with undefs.
11491 Value *Undef = UndefValue::get(FirstPhi.getType());
11492 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11493 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11494 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011495}
11496
Chris Lattner473945d2002-05-06 18:06:38 +000011497// PHINode simplification
11498//
Chris Lattner7e708292002-06-25 16:13:24 +000011499Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011500 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011501 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011502
Owen Anderson7e057142006-07-10 22:03:18 +000011503 if (Value *V = PN.hasConstantValue())
11504 return ReplaceInstUsesWith(PN, V);
11505
Owen Anderson7e057142006-07-10 22:03:18 +000011506 // If all PHI operands are the same operation, pull them through the PHI,
11507 // reducing code size.
11508 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011509 isa<Instruction>(PN.getIncomingValue(1)) &&
11510 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11511 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11512 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11513 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011514 PN.getIncomingValue(0)->hasOneUse())
11515 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11516 return Result;
11517
11518 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11519 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11520 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011521 if (PN.hasOneUse()) {
11522 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11523 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011524 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011525 PotentiallyDeadPHIs.insert(&PN);
11526 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011527 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011528 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011529
11530 // If this phi has a single use, and if that use just computes a value for
11531 // the next iteration of a loop, delete the phi. This occurs with unused
11532 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11533 // common case here is good because the only other things that catch this
11534 // are induction variable analysis (sometimes) and ADCE, which is only run
11535 // late.
11536 if (PHIUser->hasOneUse() &&
11537 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11538 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011539 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011540 }
11541 }
Owen Anderson7e057142006-07-10 22:03:18 +000011542
Chris Lattnercf5008a2007-11-06 21:52:06 +000011543 // We sometimes end up with phi cycles that non-obviously end up being the
11544 // same value, for example:
11545 // z = some value; x = phi (y, z); y = phi (x, z)
11546 // where the phi nodes don't necessarily need to be in the same block. Do a
11547 // quick check to see if the PHI node only contains a single non-phi value, if
11548 // so, scan to see if the phi cycle is actually equal to that value.
11549 {
11550 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11551 // Scan for the first non-phi operand.
11552 while (InValNo != NumOperandVals &&
11553 isa<PHINode>(PN.getIncomingValue(InValNo)))
11554 ++InValNo;
11555
11556 if (InValNo != NumOperandVals) {
11557 Value *NonPhiInVal = PN.getOperand(InValNo);
11558
11559 // Scan the rest of the operands to see if there are any conflicts, if so
11560 // there is no need to recursively scan other phis.
11561 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11562 Value *OpVal = PN.getIncomingValue(InValNo);
11563 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11564 break;
11565 }
11566
11567 // If we scanned over all operands, then we have one unique value plus
11568 // phi values. Scan PHI nodes to see if they all merge in each other or
11569 // the value.
11570 if (InValNo == NumOperandVals) {
11571 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11572 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11573 return ReplaceInstUsesWith(PN, NonPhiInVal);
11574 }
11575 }
11576 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011577
Dan Gohman5b097012009-10-31 14:22:52 +000011578 // If there are multiple PHIs, sort their operands so that they all list
11579 // the blocks in the same order. This will help identical PHIs be eliminated
11580 // by other passes. Other passes shouldn't depend on this for correctness
11581 // however.
11582 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11583 if (&PN != FirstPN)
11584 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011585 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011586 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11587 if (BBA != BBB) {
11588 Value *VA = PN.getIncomingValue(i);
11589 unsigned j = PN.getBasicBlockIndex(BBB);
11590 Value *VB = PN.getIncomingValue(j);
11591 PN.setIncomingBlock(i, BBB);
11592 PN.setIncomingValue(i, VB);
11593 PN.setIncomingBlock(j, BBA);
11594 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011595 // NOTE: Instcombine normally would want us to "return &PN" if we
11596 // modified any of the operands of an instruction. However, since we
11597 // aren't adding or removing uses (just rearranging them) we don't do
11598 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011599 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011600 }
11601
Chris Lattner9956c052009-11-08 19:23:30 +000011602 // If this is an integer PHI and we know that it has an illegal type, see if
11603 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11604 // PHI into the various pieces being extracted. This sort of thing is
11605 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011606 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011607 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11608 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11609 return Res;
11610
Chris Lattner60921c92003-12-19 05:58:40 +000011611 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011612}
11613
Chris Lattner7e708292002-06-25 16:13:24 +000011614Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011615 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11616
11617 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11618 return ReplaceInstUsesWith(GEP, V);
11619
Chris Lattner620ce142004-05-07 22:09:22 +000011620 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011621
Chris Lattnere87597f2004-10-16 18:11:37 +000011622 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011623 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011624
Chris Lattner28977af2004-04-05 01:30:19 +000011625 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011626 if (TD) {
11627 bool MadeChange = false;
11628 unsigned PtrSize = TD->getPointerSizeInBits();
11629
11630 gep_type_iterator GTI = gep_type_begin(GEP);
11631 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11632 I != E; ++I, ++GTI) {
11633 if (!isa<SequentialType>(*GTI)) continue;
11634
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011635 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011636 // to what we need. If narrower, sign-extend it to what we need. This
11637 // explicit cast can make subsequent optimizations more obvious.
11638 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011639 if (OpBits == PtrSize)
11640 continue;
11641
Chris Lattner2345d1d2009-08-30 20:01:10 +000011642 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011643 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011644 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011645 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011646 }
Chris Lattner28977af2004-04-05 01:30:19 +000011647
Chris Lattner90ac28c2002-08-02 19:29:35 +000011648 // Combine Indices - If the source pointer to this getelementptr instruction
11649 // is a getelementptr instruction, combine the indices of the two
11650 // getelementptr instructions into a single instruction.
11651 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011652 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011653 // Note that if our source is a gep chain itself that we wait for that
11654 // chain to be resolved before we perform this transformation. This
11655 // avoids us creating a TON of code in some cases.
11656 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011657 if (GetElementPtrInst *SrcGEP =
11658 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11659 if (SrcGEP->getNumOperands() == 2)
11660 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011661
Chris Lattner72588fc2007-02-15 22:48:32 +000011662 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011663
11664 // Find out whether the last index in the source GEP is a sequential idx.
11665 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011666 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11667 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011668 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011669
Chris Lattner90ac28c2002-08-02 19:29:35 +000011670 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011671 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011672 // Replace: gep (gep %P, long B), long A, ...
11673 // With: T = long A+B; gep %P, T, ...
11674 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011675 Value *Sum;
11676 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11677 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011678 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011679 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011680 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011681 Sum = SO1;
11682 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011683 // If they aren't the same type, then the input hasn't been processed
11684 // by the loop above yet (which canonicalizes sequential index types to
11685 // intptr_t). Just avoid transforming this until the input has been
11686 // normalized.
11687 if (SO1->getType() != GO1->getType())
11688 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011689 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011690 }
Chris Lattner620ce142004-05-07 22:09:22 +000011691
Chris Lattnerab984842009-08-30 05:30:55 +000011692 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011693 if (Src->getNumOperands() == 2) {
11694 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011695 GEP.setOperand(1, Sum);
11696 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011697 }
Chris Lattnerab984842009-08-30 05:30:55 +000011698 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011699 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011700 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011701 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011702 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011703 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011704 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011705 Indices.append(Src->op_begin()+1, Src->op_end());
11706 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011707 }
11708
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011709 if (!Indices.empty())
11710 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11711 Src->isInBounds()) ?
11712 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11713 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011714 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011715 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011716 }
11717
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011718 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11719 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011720 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011721
Chris Lattner2de23192009-08-30 20:38:21 +000011722 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11723 // want to change the gep until the bitcasts are eliminated.
11724 if (getBitCastOperand(X)) {
11725 Worklist.AddValue(PtrOp);
11726 return 0;
11727 }
11728
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011729 bool HasZeroPointerIndex = false;
11730 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11731 HasZeroPointerIndex = C->isZero();
11732
Chris Lattner963f4ba2009-08-30 20:36:46 +000011733 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11734 // into : GEP [10 x i8]* X, i32 0, ...
11735 //
11736 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11737 // into : GEP i8* X, ...
11738 //
11739 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011740 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011741 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11742 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011743 if (const ArrayType *CATy =
11744 dyn_cast<ArrayType>(CPTy->getElementType())) {
11745 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11746 if (CATy->getElementType() == XTy->getElementType()) {
11747 // -> GEP i8* X, ...
11748 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011749 return cast<GEPOperator>(&GEP)->isInBounds() ?
11750 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11751 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011752 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11753 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011754 }
11755
11756 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011757 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011758 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011759 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011760 // At this point, we know that the cast source type is a pointer
11761 // to an array of the same type as the destination pointer
11762 // array. Because the array type is never stepped over (there
11763 // is a leading zero) we can fold the cast into this GEP.
11764 GEP.setOperand(0, X);
11765 return &GEP;
11766 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011767 }
11768 }
Chris Lattnereed48272005-09-13 00:40:14 +000011769 } else if (GEP.getNumOperands() == 2) {
11770 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011771 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11772 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011773 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11774 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011775 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011776 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11777 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011778 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011779 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011780 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011781 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11782 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011783 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011784 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011785 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011786 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011787
11788 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011789 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011790 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011791 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011792
Owen Anderson1d0be152009-08-13 21:58:54 +000011793 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011794 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011795 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011796
11797 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11798 // allow either a mul, shift, or constant here.
11799 Value *NewIdx = 0;
11800 ConstantInt *Scale = 0;
11801 if (ArrayEltSize == 1) {
11802 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011803 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011804 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011805 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011806 Scale = CI;
11807 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11808 if (Inst->getOpcode() == Instruction::Shl &&
11809 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011810 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11811 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011812 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011813 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011814 NewIdx = Inst->getOperand(0);
11815 } else if (Inst->getOpcode() == Instruction::Mul &&
11816 isa<ConstantInt>(Inst->getOperand(1))) {
11817 Scale = cast<ConstantInt>(Inst->getOperand(1));
11818 NewIdx = Inst->getOperand(0);
11819 }
11820 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011821
Chris Lattner7835cdd2005-09-13 18:36:04 +000011822 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011823 // out, perform the transformation. Note, we don't know whether Scale is
11824 // signed or not. We'll use unsigned version of division/modulo
11825 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011826 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011827 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011828 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011829 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011830 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011831 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11832 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011833 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011834 }
11835
11836 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011837 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011838 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011839 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011840 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11841 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11842 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011843 // The NewGEP must be pointer typed, so must the old one -> BitCast
11844 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011845 }
11846 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011847 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011848 }
Chris Lattner58407792009-01-09 04:53:57 +000011849
Chris Lattner46cd5a12009-01-09 05:44:56 +000011850 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011851 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011852 /// Y = gep X, <...constant indices...>
11853 /// into a gep of the original struct. This is important for SROA and alias
11854 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011855 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011856 if (TD &&
11857 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011858 // Determine how much the GEP moves the pointer. We are guaranteed to get
11859 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011860 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011861 int64_t Offset = OffsetV->getSExtValue();
11862
11863 // If this GEP instruction doesn't move the pointer, just replace the GEP
11864 // with a bitcast of the real input to the dest type.
11865 if (Offset == 0) {
11866 // If the bitcast is of an allocation, and the allocation will be
11867 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011868 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011869 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011870 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11871 if (Instruction *I = visitBitCast(*BCI)) {
11872 if (I != BCI) {
11873 I->takeName(BCI);
11874 BCI->getParent()->getInstList().insert(BCI, I);
11875 ReplaceInstUsesWith(*BCI, I);
11876 }
11877 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011878 }
Chris Lattner58407792009-01-09 04:53:57 +000011879 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011880 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011881 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011882
11883 // Otherwise, if the offset is non-zero, we need to find out if there is a
11884 // field at Offset in 'A's type. If so, we can pull the cast through the
11885 // GEP.
11886 SmallVector<Value*, 8> NewIndices;
11887 const Type *InTy =
11888 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011889 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011890 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11891 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11892 NewIndices.end()) :
11893 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11894 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011895
11896 if (NGEP->getType() == GEP.getType())
11897 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011898 NGEP->takeName(&GEP);
11899 return new BitCastInst(NGEP, GEP.getType());
11900 }
Chris Lattner58407792009-01-09 04:53:57 +000011901 }
11902 }
11903
Chris Lattner8a2a3112001-12-14 16:52:21 +000011904 return 0;
11905}
11906
Victor Hernandez7b929da2009-10-23 21:09:37 +000011907Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011908 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011909 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011910 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11911 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011912 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011913 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011914 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011915 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011916
Chris Lattner0864acf2002-11-04 16:18:53 +000011917 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011918 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011919 //
11920 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011921 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011922
11923 // Now that I is pointing to the first non-allocation-inst in the block,
11924 // insert our getelementptr instruction...
11925 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011926 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011927 Value *Idx[2];
11928 Idx[0] = NullIdx;
11929 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011930 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11931 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011932
11933 // Now make everything use the getelementptr instead of the original
11934 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011935 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011936 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011937 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011938 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011939 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011940
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011941 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011942 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011943 // Note that we only do this for alloca's, because malloc should allocate
11944 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011945 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011946 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011947
11948 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11949 if (AI.getAlignment() == 0)
11950 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11951 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011952
Chris Lattner0864acf2002-11-04 16:18:53 +000011953 return 0;
11954}
11955
Victor Hernandez66284e02009-10-24 04:23:03 +000011956Instruction *InstCombiner::visitFree(Instruction &FI) {
11957 Value *Op = FI.getOperand(1);
11958
11959 // free undef -> unreachable.
11960 if (isa<UndefValue>(Op)) {
11961 // Insert a new store to null because we cannot modify the CFG here.
11962 new StoreInst(ConstantInt::getTrue(*Context),
11963 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11964 return EraseInstFromFunction(FI);
11965 }
11966
11967 // If we have 'free null' delete the instruction. This can happen in stl code
11968 // when lots of inlining happens.
11969 if (isa<ConstantPointerNull>(Op))
11970 return EraseInstFromFunction(FI);
11971
Victor Hernandez046e78c2009-10-26 23:43:48 +000011972 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011973 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011974 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11975 if (Op->hasOneUse() && CI->hasOneUse()) {
11976 EraseInstFromFunction(FI);
11977 EraseInstFromFunction(*CI);
11978 return EraseInstFromFunction(*cast<Instruction>(Op));
11979 }
11980 } else {
11981 // Op is a call to malloc
11982 if (Op->hasOneUse()) {
11983 EraseInstFromFunction(FI);
11984 return EraseInstFromFunction(*cast<Instruction>(Op));
11985 }
11986 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011987 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011988
11989 return 0;
11990}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011991
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011992/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011993static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011994 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011995 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011996 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011997 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011998
Mon P Wang6753f952009-02-07 22:19:29 +000011999 const PointerType *DestTy = cast<PointerType>(CI->getType());
12000 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012001 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012002
12003 // If the address spaces don't match, don't eliminate the cast.
12004 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12005 return 0;
12006
Chris Lattnerb89e0712004-07-13 01:49:43 +000012007 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012008
Reid Spencer42230162007-01-22 05:51:25 +000012009 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012010 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012011 // If the source is an array, the code below will not succeed. Check to
12012 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12013 // constants.
12014 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12015 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12016 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012017 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012018 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12019 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012020 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012021 SrcTy = cast<PointerType>(CastOp->getType());
12022 SrcPTy = SrcTy->getElementType();
12023 }
12024
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012025 if (IC.getTargetData() &&
12026 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012027 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012028 // Do not allow turning this into a load of an integer, which is then
12029 // casted to a pointer, this pessimizes pointer analysis a lot.
12030 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012031 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12032 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012033
Chris Lattnerf9527852005-01-31 04:50:46 +000012034 // Okay, we are casting from one integer or pointer type to another of
12035 // the same size. Instead of casting the pointer before the load, cast
12036 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012037 Value *NewLoad =
12038 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012039 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012040 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012041 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012042 }
12043 }
12044 return 0;
12045}
12046
Chris Lattner833b8a42003-06-26 05:06:25 +000012047Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12048 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012049
Dan Gohman9941f742007-07-20 16:34:21 +000012050 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012051 if (TD) {
12052 unsigned KnownAlign =
12053 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12054 if (KnownAlign >
12055 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12056 LI.getAlignment()))
12057 LI.setAlignment(KnownAlign);
12058 }
Dan Gohman9941f742007-07-20 16:34:21 +000012059
Chris Lattner963f4ba2009-08-30 20:36:46 +000012060 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012061 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012062 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012063 return Res;
12064
12065 // None of the following transforms are legal for volatile loads.
12066 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012067
Dan Gohman2276a7b2008-10-15 23:19:35 +000012068 // Do really simple store-to-load forwarding and load CSE, to catch cases
12069 // where there are several consequtive memory accesses to the same location,
12070 // separated by a few arithmetic operations.
12071 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012072 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12073 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012074
Chris Lattner878e4942009-10-22 06:25:11 +000012075 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012076 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12077 const Value *GEPI0 = GEPI->getOperand(0);
12078 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012079 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012080 // Insert a new store to null instruction before the load to indicate
12081 // that this code is not reachable. We do this instead of inserting
12082 // an unreachable instruction directly because we cannot modify the
12083 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012084 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012085 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012086 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012087 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012088 }
Chris Lattner37366c12005-05-01 04:24:53 +000012089
Chris Lattner878e4942009-10-22 06:25:11 +000012090 // load null/undef -> unreachable
12091 // TODO: Consider a target hook for valid address spaces for this xform.
12092 if (isa<UndefValue>(Op) ||
12093 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12094 // Insert a new store to null instruction before the load to indicate that
12095 // this code is not reachable. We do this instead of inserting an
12096 // unreachable instruction directly because we cannot modify the CFG.
12097 new StoreInst(UndefValue::get(LI.getType()),
12098 Constant::getNullValue(Op->getType()), &LI);
12099 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012100 }
Chris Lattner878e4942009-10-22 06:25:11 +000012101
12102 // Instcombine load (constantexpr_cast global) -> cast (load global)
12103 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12104 if (CE->isCast())
12105 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12106 return Res;
12107
Chris Lattner37366c12005-05-01 04:24:53 +000012108 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012109 // Change select and PHI nodes to select values instead of addresses: this
12110 // helps alias analysis out a lot, allows many others simplifications, and
12111 // exposes redundancy in the code.
12112 //
12113 // Note that we cannot do the transformation unless we know that the
12114 // introduced loads cannot trap! Something like this is valid as long as
12115 // the condition is always false: load (select bool %C, int* null, int* %G),
12116 // but it would not be valid if we transformed it to load from null
12117 // unconditionally.
12118 //
12119 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12120 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012121 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12122 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012123 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12124 SI->getOperand(1)->getName()+".val");
12125 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12126 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012127 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012128 }
12129
Chris Lattner684fe212004-09-23 15:46:00 +000012130 // load (select (cond, null, P)) -> load P
12131 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12132 if (C->isNullValue()) {
12133 LI.setOperand(0, SI->getOperand(2));
12134 return &LI;
12135 }
12136
12137 // load (select (cond, P, null)) -> load P
12138 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12139 if (C->isNullValue()) {
12140 LI.setOperand(0, SI->getOperand(1));
12141 return &LI;
12142 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012143 }
12144 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012145 return 0;
12146}
12147
Reid Spencer55af2b52007-01-19 21:20:31 +000012148/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012149/// when possible. This makes it generally easy to do alias analysis and/or
12150/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012151static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12152 User *CI = cast<User>(SI.getOperand(1));
12153 Value *CastOp = CI->getOperand(0);
12154
12155 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012156 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12157 if (SrcTy == 0) return 0;
12158
12159 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012160
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012161 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12162 return 0;
12163
Chris Lattner3914f722009-01-24 01:00:13 +000012164 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12165 /// to its first element. This allows us to handle things like:
12166 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12167 /// on 32-bit hosts.
12168 SmallVector<Value*, 4> NewGEPIndices;
12169
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012170 // If the source is an array, the code below will not succeed. Check to
12171 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12172 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012173 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12174 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012175 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012176 NewGEPIndices.push_back(Zero);
12177
12178 while (1) {
12179 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012180 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012181 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012182 NewGEPIndices.push_back(Zero);
12183 SrcPTy = STy->getElementType(0);
12184 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12185 NewGEPIndices.push_back(Zero);
12186 SrcPTy = ATy->getElementType();
12187 } else {
12188 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012189 }
Chris Lattner3914f722009-01-24 01:00:13 +000012190 }
12191
Owen Andersondebcb012009-07-29 22:17:13 +000012192 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012193 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012194
12195 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12196 return 0;
12197
Chris Lattner71759c42009-01-16 20:12:52 +000012198 // If the pointers point into different address spaces or if they point to
12199 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012200 if (!IC.getTargetData() ||
12201 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012202 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012203 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12204 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012205 return 0;
12206
12207 // Okay, we are casting from one integer or pointer type to another of
12208 // the same size. Instead of casting the pointer before
12209 // the store, cast the value to be stored.
12210 Value *NewCast;
12211 Value *SIOp0 = SI.getOperand(0);
12212 Instruction::CastOps opcode = Instruction::BitCast;
12213 const Type* CastSrcTy = SIOp0->getType();
12214 const Type* CastDstTy = SrcPTy;
12215 if (isa<PointerType>(CastDstTy)) {
12216 if (CastSrcTy->isInteger())
12217 opcode = Instruction::IntToPtr;
12218 } else if (isa<IntegerType>(CastDstTy)) {
12219 if (isa<PointerType>(SIOp0->getType()))
12220 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012221 }
Chris Lattner3914f722009-01-24 01:00:13 +000012222
12223 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12224 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012225 if (!NewGEPIndices.empty())
12226 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12227 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012228
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012229 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12230 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012231 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012232}
12233
Chris Lattner4aebaee2008-11-27 08:56:30 +000012234/// equivalentAddressValues - Test if A and B will obviously have the same
12235/// value. This includes recognizing that %t0 and %t1 will have the same
12236/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012237/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012238/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012239/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012240/// %t2 = load i32* %t1
12241///
12242static bool equivalentAddressValues(Value *A, Value *B) {
12243 // Test if the values are trivially equivalent.
12244 if (A == B) return true;
12245
12246 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012247 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12248 // its only used to compare two uses within the same basic block, which
12249 // means that they'll always either have the same value or one of them
12250 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012251 if (isa<BinaryOperator>(A) ||
12252 isa<CastInst>(A) ||
12253 isa<PHINode>(A) ||
12254 isa<GetElementPtrInst>(A))
12255 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012256 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012257 return true;
12258
12259 // Otherwise they may not be equivalent.
12260 return false;
12261}
12262
Dale Johannesen4945c652009-03-03 21:26:39 +000012263// If this instruction has two uses, one of which is a llvm.dbg.declare,
12264// return the llvm.dbg.declare.
12265DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12266 if (!V->hasNUses(2))
12267 return 0;
12268 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12269 UI != E; ++UI) {
12270 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12271 return DI;
12272 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12273 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12274 return DI;
12275 }
12276 }
12277 return 0;
12278}
12279
Chris Lattner2f503e62005-01-31 05:36:43 +000012280Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12281 Value *Val = SI.getOperand(0);
12282 Value *Ptr = SI.getOperand(1);
12283
Chris Lattner836692d2007-01-15 06:51:56 +000012284 // If the RHS is an alloca with a single use, zapify the store, making the
12285 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012286 // If the RHS is an alloca with a two uses, the other one being a
12287 // llvm.dbg.declare, zapify the store and the declare, making the
12288 // alloca dead. We must do this to prevent declare's from affecting
12289 // codegen.
12290 if (!SI.isVolatile()) {
12291 if (Ptr->hasOneUse()) {
12292 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012293 EraseInstFromFunction(SI);
12294 ++NumCombined;
12295 return 0;
12296 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012297 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12298 if (isa<AllocaInst>(GEP->getOperand(0))) {
12299 if (GEP->getOperand(0)->hasOneUse()) {
12300 EraseInstFromFunction(SI);
12301 ++NumCombined;
12302 return 0;
12303 }
12304 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12305 EraseInstFromFunction(*DI);
12306 EraseInstFromFunction(SI);
12307 ++NumCombined;
12308 return 0;
12309 }
12310 }
12311 }
12312 }
12313 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12314 EraseInstFromFunction(*DI);
12315 EraseInstFromFunction(SI);
12316 ++NumCombined;
12317 return 0;
12318 }
Chris Lattner836692d2007-01-15 06:51:56 +000012319 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012320
Dan Gohman9941f742007-07-20 16:34:21 +000012321 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012322 if (TD) {
12323 unsigned KnownAlign =
12324 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12325 if (KnownAlign >
12326 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12327 SI.getAlignment()))
12328 SI.setAlignment(KnownAlign);
12329 }
Dan Gohman9941f742007-07-20 16:34:21 +000012330
Dale Johannesenacb51a32009-03-03 01:43:03 +000012331 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012332 // stores to the same location, separated by a few arithmetic operations. This
12333 // situation often occurs with bitfield accesses.
12334 BasicBlock::iterator BBI = &SI;
12335 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12336 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012337 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012338 // Don't count debug info directives, lest they affect codegen,
12339 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12340 // It is necessary for correctness to skip those that feed into a
12341 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012342 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012343 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012344 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012345 continue;
12346 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012347
12348 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12349 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012350 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12351 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012352 ++NumDeadStore;
12353 ++BBI;
12354 EraseInstFromFunction(*PrevSI);
12355 continue;
12356 }
12357 break;
12358 }
12359
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012360 // If this is a load, we have to stop. However, if the loaded value is from
12361 // the pointer we're loading and is producing the pointer we're storing,
12362 // then *this* store is dead (X = load P; store X -> P).
12363 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012364 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12365 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012366 EraseInstFromFunction(SI);
12367 ++NumCombined;
12368 return 0;
12369 }
12370 // Otherwise, this is a load from some other location. Stores before it
12371 // may not be dead.
12372 break;
12373 }
12374
Chris Lattner9ca96412006-02-08 03:25:32 +000012375 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012376 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012377 break;
12378 }
12379
12380
12381 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012382
12383 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012384 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012385 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012386 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012387 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012388 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012389 ++NumCombined;
12390 }
12391 return 0; // Do not modify these!
12392 }
12393
12394 // store undef, Ptr -> noop
12395 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012396 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012397 ++NumCombined;
12398 return 0;
12399 }
12400
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012401 // If the pointer destination is a cast, see if we can fold the cast into the
12402 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012403 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012404 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12405 return Res;
12406 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012407 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012408 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12409 return Res;
12410
Chris Lattner408902b2005-09-12 23:23:25 +000012411
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012412 // If this store is the last instruction in the basic block (possibly
12413 // excepting debug info instructions and the pointer bitcasts that feed
12414 // into them), and if the block ends with an unconditional branch, try
12415 // to move it to the successor block.
12416 BBI = &SI;
12417 do {
12418 ++BBI;
12419 } while (isa<DbgInfoIntrinsic>(BBI) ||
12420 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012421 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012422 if (BI->isUnconditional())
12423 if (SimplifyStoreAtEndOfBlock(SI))
12424 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012425
Chris Lattner2f503e62005-01-31 05:36:43 +000012426 return 0;
12427}
12428
Chris Lattner3284d1f2007-04-15 00:07:55 +000012429/// SimplifyStoreAtEndOfBlock - Turn things like:
12430/// if () { *P = v1; } else { *P = v2 }
12431/// into a phi node with a store in the successor.
12432///
Chris Lattner31755a02007-04-15 01:02:18 +000012433/// Simplify things like:
12434/// *P = v1; if () { *P = v2; }
12435/// into a phi node with a store in the successor.
12436///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012437bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12438 BasicBlock *StoreBB = SI.getParent();
12439
12440 // Check to see if the successor block has exactly two incoming edges. If
12441 // so, see if the other predecessor contains a store to the same location.
12442 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012443 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012444
12445 // Determine whether Dest has exactly two predecessors and, if so, compute
12446 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012447 pred_iterator PI = pred_begin(DestBB);
12448 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012449 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012450 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012451 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012452 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012453 return false;
12454
12455 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012456 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012457 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012458 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012459 }
Chris Lattner31755a02007-04-15 01:02:18 +000012460 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012461 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012462
12463 // Bail out if all the relevant blocks aren't distinct (this can happen,
12464 // for example, if SI is in an infinite loop)
12465 if (StoreBB == DestBB || OtherBB == DestBB)
12466 return false;
12467
Chris Lattner31755a02007-04-15 01:02:18 +000012468 // Verify that the other block ends in a branch and is not otherwise empty.
12469 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012470 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012471 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012472 return false;
12473
Chris Lattner31755a02007-04-15 01:02:18 +000012474 // If the other block ends in an unconditional branch, check for the 'if then
12475 // else' case. there is an instruction before the branch.
12476 StoreInst *OtherStore = 0;
12477 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012478 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012479 // Skip over debugging info.
12480 while (isa<DbgInfoIntrinsic>(BBI) ||
12481 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12482 if (BBI==OtherBB->begin())
12483 return false;
12484 --BBI;
12485 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012486 // If this isn't a store, isn't a store to the same location, or if the
12487 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012488 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012489 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12490 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012491 return false;
12492 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012493 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012494 // destinations is StoreBB, then we have the if/then case.
12495 if (OtherBr->getSuccessor(0) != StoreBB &&
12496 OtherBr->getSuccessor(1) != StoreBB)
12497 return false;
12498
12499 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012500 // if/then triangle. See if there is a store to the same ptr as SI that
12501 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012502 for (;; --BBI) {
12503 // Check to see if we find the matching store.
12504 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012505 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12506 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012507 return false;
12508 break;
12509 }
Eli Friedman6903a242008-06-13 22:02:12 +000012510 // If we find something that may be using or overwriting the stored
12511 // value, or if we run out of instructions, we can't do the xform.
12512 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012513 BBI == OtherBB->begin())
12514 return false;
12515 }
12516
12517 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012518 // make sure nothing reads or overwrites the stored value in
12519 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012520 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12521 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012522 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012523 return false;
12524 }
12525 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012526
Chris Lattner31755a02007-04-15 01:02:18 +000012527 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012528 Value *MergedVal = OtherStore->getOperand(0);
12529 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012530 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012531 PN->reserveOperandSpace(2);
12532 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012533 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12534 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012535 }
12536
12537 // Advance to a place where it is safe to insert the new store and
12538 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012539 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012540 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012541 OtherStore->isVolatile(),
12542 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012543
12544 // Nuke the old stores.
12545 EraseInstFromFunction(SI);
12546 EraseInstFromFunction(*OtherStore);
12547 ++NumCombined;
12548 return true;
12549}
12550
Chris Lattner2f503e62005-01-31 05:36:43 +000012551
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012552Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12553 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012554 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012555 BasicBlock *TrueDest;
12556 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012557 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012558 !isa<Constant>(X)) {
12559 // Swap Destinations and condition...
12560 BI.setCondition(X);
12561 BI.setSuccessor(0, FalseDest);
12562 BI.setSuccessor(1, TrueDest);
12563 return &BI;
12564 }
12565
Reid Spencere4d87aa2006-12-23 06:05:41 +000012566 // Cannonicalize fcmp_one -> fcmp_oeq
12567 FCmpInst::Predicate FPred; Value *Y;
12568 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012569 TrueDest, FalseDest)) &&
12570 BI.getCondition()->hasOneUse())
12571 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12572 FPred == FCmpInst::FCMP_OGE) {
12573 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12574 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12575
12576 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012577 BI.setSuccessor(0, FalseDest);
12578 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012579 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012580 return &BI;
12581 }
12582
12583 // Cannonicalize icmp_ne -> icmp_eq
12584 ICmpInst::Predicate IPred;
12585 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012586 TrueDest, FalseDest)) &&
12587 BI.getCondition()->hasOneUse())
12588 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12589 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12590 IPred == ICmpInst::ICMP_SGE) {
12591 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12592 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12593 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012594 BI.setSuccessor(0, FalseDest);
12595 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012596 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012597 return &BI;
12598 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012599
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012600 return 0;
12601}
Chris Lattner0864acf2002-11-04 16:18:53 +000012602
Chris Lattner46238a62004-07-03 00:26:11 +000012603Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12604 Value *Cond = SI.getCondition();
12605 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12606 if (I->getOpcode() == Instruction::Add)
12607 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12608 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12609 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012610 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012611 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012612 AddRHS));
12613 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012614 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012615 return &SI;
12616 }
12617 }
12618 return 0;
12619}
12620
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012621Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012622 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012623
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012624 if (!EV.hasIndices())
12625 return ReplaceInstUsesWith(EV, Agg);
12626
12627 if (Constant *C = dyn_cast<Constant>(Agg)) {
12628 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012629 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012630
12631 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012632 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012633
12634 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12635 // Extract the element indexed by the first index out of the constant
12636 Value *V = C->getOperand(*EV.idx_begin());
12637 if (EV.getNumIndices() > 1)
12638 // Extract the remaining indices out of the constant indexed by the
12639 // first index
12640 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12641 else
12642 return ReplaceInstUsesWith(EV, V);
12643 }
12644 return 0; // Can't handle other constants
12645 }
12646 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12647 // We're extracting from an insertvalue instruction, compare the indices
12648 const unsigned *exti, *exte, *insi, *inse;
12649 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12650 exte = EV.idx_end(), inse = IV->idx_end();
12651 exti != exte && insi != inse;
12652 ++exti, ++insi) {
12653 if (*insi != *exti)
12654 // The insert and extract both reference distinctly different elements.
12655 // This means the extract is not influenced by the insert, and we can
12656 // replace the aggregate operand of the extract with the aggregate
12657 // operand of the insert. i.e., replace
12658 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12659 // %E = extractvalue { i32, { i32 } } %I, 0
12660 // with
12661 // %E = extractvalue { i32, { i32 } } %A, 0
12662 return ExtractValueInst::Create(IV->getAggregateOperand(),
12663 EV.idx_begin(), EV.idx_end());
12664 }
12665 if (exti == exte && insi == inse)
12666 // Both iterators are at the end: Index lists are identical. Replace
12667 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12668 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12669 // with "i32 42"
12670 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12671 if (exti == exte) {
12672 // The extract list is a prefix of the insert list. i.e. replace
12673 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12674 // %E = extractvalue { i32, { i32 } } %I, 1
12675 // with
12676 // %X = extractvalue { i32, { i32 } } %A, 1
12677 // %E = insertvalue { i32 } %X, i32 42, 0
12678 // by switching the order of the insert and extract (though the
12679 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012680 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12681 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012682 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12683 insi, inse);
12684 }
12685 if (insi == inse)
12686 // The insert list is a prefix of the extract list
12687 // We can simply remove the common indices from the extract and make it
12688 // operate on the inserted value instead of the insertvalue result.
12689 // i.e., replace
12690 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12691 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12692 // with
12693 // %E extractvalue { i32 } { i32 42 }, 0
12694 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12695 exti, exte);
12696 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012697 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12698 // We're extracting from an intrinsic, see if we're the only user, which
12699 // allows us to simplify multiple result intrinsics to simpler things that
12700 // just get one value..
12701 if (II->hasOneUse()) {
12702 // Check if we're grabbing the overflow bit or the result of a 'with
12703 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12704 // and replace it with a traditional binary instruction.
12705 switch (II->getIntrinsicID()) {
12706 case Intrinsic::uadd_with_overflow:
12707 case Intrinsic::sadd_with_overflow:
12708 if (*EV.idx_begin() == 0) { // Normal result.
12709 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12710 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12711 EraseInstFromFunction(*II);
12712 return BinaryOperator::CreateAdd(LHS, RHS);
12713 }
12714 break;
12715 case Intrinsic::usub_with_overflow:
12716 case Intrinsic::ssub_with_overflow:
12717 if (*EV.idx_begin() == 0) { // Normal result.
12718 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12719 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12720 EraseInstFromFunction(*II);
12721 return BinaryOperator::CreateSub(LHS, RHS);
12722 }
12723 break;
12724 case Intrinsic::umul_with_overflow:
12725 case Intrinsic::smul_with_overflow:
12726 if (*EV.idx_begin() == 0) { // Normal result.
12727 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12728 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12729 EraseInstFromFunction(*II);
12730 return BinaryOperator::CreateMul(LHS, RHS);
12731 }
12732 break;
12733 default:
12734 break;
12735 }
12736 }
12737 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012738 // Can't simplify extracts from other values. Note that nested extracts are
12739 // already simplified implicitely by the above (extract ( extract (insert) )
12740 // will be translated into extract ( insert ( extract ) ) first and then just
12741 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012742 return 0;
12743}
12744
Chris Lattner220b0cf2006-03-05 00:22:33 +000012745/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12746/// is to leave as a vector operation.
12747static bool CheapToScalarize(Value *V, bool isConstant) {
12748 if (isa<ConstantAggregateZero>(V))
12749 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012750 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012751 if (isConstant) return true;
12752 // If all elts are the same, we can extract.
12753 Constant *Op0 = C->getOperand(0);
12754 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12755 if (C->getOperand(i) != Op0)
12756 return false;
12757 return true;
12758 }
12759 Instruction *I = dyn_cast<Instruction>(V);
12760 if (!I) return false;
12761
12762 // Insert element gets simplified to the inserted element or is deleted if
12763 // this is constant idx extract element and its a constant idx insertelt.
12764 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12765 isa<ConstantInt>(I->getOperand(2)))
12766 return true;
12767 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12768 return true;
12769 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12770 if (BO->hasOneUse() &&
12771 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12772 CheapToScalarize(BO->getOperand(1), isConstant)))
12773 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012774 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12775 if (CI->hasOneUse() &&
12776 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12777 CheapToScalarize(CI->getOperand(1), isConstant)))
12778 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012779
12780 return false;
12781}
12782
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012783/// Read and decode a shufflevector mask.
12784///
12785/// It turns undef elements into values that are larger than the number of
12786/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012787static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12788 unsigned NElts = SVI->getType()->getNumElements();
12789 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12790 return std::vector<unsigned>(NElts, 0);
12791 if (isa<UndefValue>(SVI->getOperand(2)))
12792 return std::vector<unsigned>(NElts, 2*NElts);
12793
12794 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012795 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012796 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12797 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012798 Result.push_back(NElts*2); // undef -> 8
12799 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012800 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012801 return Result;
12802}
12803
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012804/// FindScalarElement - Given a vector and an element number, see if the scalar
12805/// value is already around as a register, for example if it were inserted then
12806/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012807static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012808 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012809 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12810 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012811 unsigned Width = PTy->getNumElements();
12812 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012813 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012814
12815 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012816 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012817 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012818 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012819 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012820 return CP->getOperand(EltNo);
12821 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12822 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012823 if (!isa<ConstantInt>(III->getOperand(2)))
12824 return 0;
12825 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012826
12827 // If this is an insert to the element we are looking for, return the
12828 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012829 if (EltNo == IIElt)
12830 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012831
12832 // Otherwise, the insertelement doesn't modify the value, recurse on its
12833 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012834 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012835 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012836 unsigned LHSWidth =
12837 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012838 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012839 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012840 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012841 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012842 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012843 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012844 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012845 }
12846
12847 // Otherwise, we don't know.
12848 return 0;
12849}
12850
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012851Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012852 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012853 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012854 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012855
Dan Gohman07a96762007-07-16 14:29:03 +000012856 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012857 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012858 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012859
Reid Spencer9d6565a2007-02-15 02:26:10 +000012860 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012861 // If vector val is constant with all elements the same, replace EI with
12862 // that element. When the elements are not identical, we cannot replace yet
12863 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012864 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012865 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012866 if (C->getOperand(i) != op0) {
12867 op0 = 0;
12868 break;
12869 }
12870 if (op0)
12871 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012872 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012873
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012874 // If extracting a specified index from the vector, see if we can recursively
12875 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012876 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012877 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012878 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012879
12880 // If this is extracting an invalid index, turn this into undef, to avoid
12881 // crashing the code below.
12882 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012883 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012884
Chris Lattner867b99f2006-10-05 06:55:50 +000012885 // This instruction only demands the single element from the input vector.
12886 // If the input vector has a single use, simplify it based on this use
12887 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012888 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012889 APInt UndefElts(VectorWidth, 0);
12890 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012891 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012892 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012893 EI.setOperand(0, V);
12894 return &EI;
12895 }
12896 }
12897
Owen Andersond672ecb2009-07-03 00:17:18 +000012898 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012899 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012900
12901 // If the this extractelement is directly using a bitcast from a vector of
12902 // the same number of elements, see if we can find the source element from
12903 // it. In this case, we will end up needing to bitcast the scalars.
12904 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12905 if (const VectorType *VT =
12906 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12907 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012908 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12909 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012910 return new BitCastInst(Elt, EI.getType());
12911 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012912 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012913
Chris Lattner73fa49d2006-05-25 22:53:38 +000012914 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012915 // Push extractelement into predecessor operation if legal and
12916 // profitable to do so
12917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12918 if (I->hasOneUse() &&
12919 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12920 Value *newEI0 =
12921 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12922 EI.getName()+".lhs");
12923 Value *newEI1 =
12924 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12925 EI.getName()+".rhs");
12926 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012927 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012928 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012929 // Extracting the inserted element?
12930 if (IE->getOperand(2) == EI.getOperand(1))
12931 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12932 // If the inserted and extracted elements are constants, they must not
12933 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012934 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012935 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012936 EI.setOperand(0, IE->getOperand(0));
12937 return &EI;
12938 }
12939 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12940 // If this is extracting an element from a shufflevector, figure out where
12941 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012942 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12943 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012944 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012945 unsigned LHSWidth =
12946 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12947
12948 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012949 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012950 else if (SrcIdx < LHSWidth*2) {
12951 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012952 Src = SVI->getOperand(1);
12953 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012954 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012955 }
Eric Christophera3500da2009-07-25 02:28:41 +000012956 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012957 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12958 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012959 }
12960 }
Eli Friedman2451a642009-07-18 23:06:53 +000012961 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012962 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012963 return 0;
12964}
12965
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012966/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12967/// elements from either LHS or RHS, return the shuffle mask and true.
12968/// Otherwise, return false.
12969static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012970 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012971 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012972 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12973 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012974 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012975
12976 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012977 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012978 return true;
12979 } else if (V == LHS) {
12980 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012981 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012982 return true;
12983 } else if (V == RHS) {
12984 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012985 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012986 return true;
12987 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12988 // If this is an insert of an extract from some other vector, include it.
12989 Value *VecOp = IEI->getOperand(0);
12990 Value *ScalarOp = IEI->getOperand(1);
12991 Value *IdxOp = IEI->getOperand(2);
12992
Chris Lattnerd929f062006-04-27 21:14:21 +000012993 if (!isa<ConstantInt>(IdxOp))
12994 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012995 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012996
12997 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12998 // Okay, we can handle this if the vector we are insertinting into is
12999 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013000 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013001 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013002 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013003 return true;
13004 }
13005 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13006 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013007 EI->getOperand(0)->getType() == V->getType()) {
13008 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013009 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013010
13011 // This must be extracting from either LHS or RHS.
13012 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13013 // Okay, we can handle this if the vector we are insertinting into is
13014 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013015 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013016 // If so, update the mask to reflect the inserted value.
13017 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013018 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013019 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013020 } else {
13021 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013022 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013023 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013024
13025 }
13026 return true;
13027 }
13028 }
13029 }
13030 }
13031 }
13032 // TODO: Handle shufflevector here!
13033
13034 return false;
13035}
13036
13037/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13038/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13039/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013040static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013041 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013042 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013043 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013044 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013045 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013046
13047 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013048 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013049 return V;
13050 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013051 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013052 return V;
13053 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13054 // If this is an insert of an extract from some other vector, include it.
13055 Value *VecOp = IEI->getOperand(0);
13056 Value *ScalarOp = IEI->getOperand(1);
13057 Value *IdxOp = IEI->getOperand(2);
13058
13059 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13060 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13061 EI->getOperand(0)->getType() == V->getType()) {
13062 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013063 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13064 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013065
13066 // Either the extracted from or inserted into vector must be RHSVec,
13067 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013068 if (EI->getOperand(0) == RHS || RHS == 0) {
13069 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013070 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013071 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013072 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013073 return V;
13074 }
13075
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013076 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013077 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13078 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013079 // Everything but the extracted element is replaced with the RHS.
13080 for (unsigned i = 0; i != NumElts; ++i) {
13081 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013082 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013083 }
13084 return V;
13085 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013086
13087 // If this insertelement is a chain that comes from exactly these two
13088 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013089 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13090 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013091 return EI->getOperand(0);
13092
Chris Lattnerefb47352006-04-15 01:39:45 +000013093 }
13094 }
13095 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013096 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013097
13098 // Otherwise, can't do anything fancy. Return an identity vector.
13099 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013100 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013101 return V;
13102}
13103
13104Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13105 Value *VecOp = IE.getOperand(0);
13106 Value *ScalarOp = IE.getOperand(1);
13107 Value *IdxOp = IE.getOperand(2);
13108
Chris Lattner599ded12007-04-09 01:11:16 +000013109 // Inserting an undef or into an undefined place, remove this.
13110 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13111 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013112
Chris Lattnerefb47352006-04-15 01:39:45 +000013113 // If the inserted element was extracted from some other vector, and if the
13114 // indexes are constant, try to turn this into a shufflevector operation.
13115 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13116 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13117 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013118 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013119 unsigned ExtractedIdx =
13120 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013121 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013122
13123 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13124 return ReplaceInstUsesWith(IE, VecOp);
13125
13126 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013127 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013128
13129 // If we are extracting a value from a vector, then inserting it right
13130 // back into the same place, just use the input vector.
13131 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13132 return ReplaceInstUsesWith(IE, VecOp);
13133
Chris Lattnerefb47352006-04-15 01:39:45 +000013134 // If this insertelement isn't used by some other insertelement, turn it
13135 // (and any insertelements it points to), into one big shuffle.
13136 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13137 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013138 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013139 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013140 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013141 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013142 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013143 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013144 }
13145 }
13146 }
13147
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013148 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13149 APInt UndefElts(VWidth, 0);
13150 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13151 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13152 return &IE;
13153
Chris Lattnerefb47352006-04-15 01:39:45 +000013154 return 0;
13155}
13156
13157
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013158Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13159 Value *LHS = SVI.getOperand(0);
13160 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013161 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013162
13163 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013164
Chris Lattner867b99f2006-10-05 06:55:50 +000013165 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013166 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013167 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013168
Dan Gohman488fbfc2008-09-09 18:11:14 +000013169 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013170
13171 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13172 return 0;
13173
Evan Cheng388df622009-02-03 10:05:09 +000013174 APInt UndefElts(VWidth, 0);
13175 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13176 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013177 LHS = SVI.getOperand(0);
13178 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013179 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013180 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013181
Chris Lattner863bcff2006-05-25 23:48:38 +000013182 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13183 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13184 if (LHS == RHS || isa<UndefValue>(LHS)) {
13185 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013186 // shuffle(undef,undef,mask) -> undef.
13187 return ReplaceInstUsesWith(SVI, LHS);
13188 }
13189
Chris Lattner863bcff2006-05-25 23:48:38 +000013190 // Remap any references to RHS to use LHS.
13191 std::vector<Constant*> Elts;
13192 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013193 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013194 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013195 else {
13196 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013197 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013198 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013199 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013200 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013201 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013202 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013203 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013204 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013205 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013206 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013207 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013208 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013209 LHS = SVI.getOperand(0);
13210 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013211 MadeChange = true;
13212 }
13213
Chris Lattner7b2e27922006-05-26 00:29:06 +000013214 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013215 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013216
Chris Lattner863bcff2006-05-25 23:48:38 +000013217 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13218 if (Mask[i] >= e*2) continue; // Ignore undef values.
13219 // Is this an identity shuffle of the LHS value?
13220 isLHSID &= (Mask[i] == i);
13221
13222 // Is this an identity shuffle of the RHS value?
13223 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013224 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013225
Chris Lattner863bcff2006-05-25 23:48:38 +000013226 // Eliminate identity shuffles.
13227 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13228 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013229
Chris Lattner7b2e27922006-05-26 00:29:06 +000013230 // If the LHS is a shufflevector itself, see if we can combine it with this
13231 // one without producing an unusual shuffle. Here we are really conservative:
13232 // we are absolutely afraid of producing a shuffle mask not in the input
13233 // program, because the code gen may not be smart enough to turn a merged
13234 // shuffle into two specific shuffles: it may produce worse code. As such,
13235 // we only merge two shuffles if the result is one of the two input shuffle
13236 // masks. In this case, merging the shuffles just removes one instruction,
13237 // which we know is safe. This is good for things like turning:
13238 // (splat(splat)) -> splat.
13239 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13240 if (isa<UndefValue>(RHS)) {
13241 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13242
David Greenef941d292009-11-16 21:52:23 +000013243 if (LHSMask.size() == Mask.size()) {
13244 std::vector<unsigned> NewMask;
13245 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013246 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013247 NewMask.push_back(2*e);
13248 else
13249 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013250
David Greenef941d292009-11-16 21:52:23 +000013251 // If the result mask is equal to the src shuffle or this
13252 // shuffle mask, do the replacement.
13253 if (NewMask == LHSMask || NewMask == Mask) {
13254 unsigned LHSInNElts =
13255 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13256 getNumElements();
13257 std::vector<Constant*> Elts;
13258 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13259 if (NewMask[i] >= LHSInNElts*2) {
13260 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13261 } else {
13262 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13263 NewMask[i]));
13264 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013265 }
David Greenef941d292009-11-16 21:52:23 +000013266 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13267 LHSSVI->getOperand(1),
13268 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013269 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013270 }
13271 }
13272 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013273
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013274 return MadeChange ? &SVI : 0;
13275}
13276
13277
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013278
Chris Lattnerea1c4542004-12-08 23:43:58 +000013279
13280/// TryToSinkInstruction - Try to move the specified instruction from its
13281/// current block into the beginning of DestBlock, which can only happen if it's
13282/// safe to move the instruction past all of the instructions between it and the
13283/// end of its block.
13284static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13285 assert(I->hasOneUse() && "Invariants didn't hold!");
13286
Chris Lattner108e9022005-10-27 17:13:11 +000013287 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013288 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013289 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013290
Chris Lattnerea1c4542004-12-08 23:43:58 +000013291 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013292 if (isa<AllocaInst>(I) && I->getParent() ==
13293 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013294 return false;
13295
Chris Lattner96a52a62004-12-09 07:14:34 +000013296 // We can only sink load instructions if there is nothing between the load and
13297 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013298 if (I->mayReadFromMemory()) {
13299 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013300 Scan != E; ++Scan)
13301 if (Scan->mayWriteToMemory())
13302 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013303 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013304
Dan Gohman02dea8b2008-05-23 21:05:58 +000013305 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013306
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013307 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013308 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013309 ++NumSunkInst;
13310 return true;
13311}
13312
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013313
13314/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13315/// all reachable code to the worklist.
13316///
13317/// This has a couple of tricks to make the code faster and more powerful. In
13318/// particular, we constant fold and DCE instructions as we go, to avoid adding
13319/// them to the worklist (this significantly speeds up instcombine on code where
13320/// many instructions are dead or constant). Additionally, if we find a branch
13321/// whose condition is a known constant, we only visit the reachable successors.
13322///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013323static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013324 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013325 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013326 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013327 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013328 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013329 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013330
13331 std::vector<Instruction*> InstrsForInstCombineWorklist;
13332 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013333
Chris Lattner2ee743b2009-10-15 04:59:28 +000013334 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13335
Chris Lattner2c7718a2007-03-23 19:17:18 +000013336 while (!Worklist.empty()) {
13337 BB = Worklist.back();
13338 Worklist.pop_back();
13339
13340 // We have now visited this block! If we've already been here, ignore it.
13341 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013342
Chris Lattner2c7718a2007-03-23 19:17:18 +000013343 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13344 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013345
Chris Lattner2c7718a2007-03-23 19:17:18 +000013346 // DCE instruction if trivially dead.
13347 if (isInstructionTriviallyDead(Inst)) {
13348 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013349 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013350 Inst->eraseFromParent();
13351 continue;
13352 }
13353
13354 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013355 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013356 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013357 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13358 << *Inst << '\n');
13359 Inst->replaceAllUsesWith(C);
13360 ++NumConstProp;
13361 Inst->eraseFromParent();
13362 continue;
13363 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013364
13365
13366
13367 if (TD) {
13368 // See if we can constant fold its operands.
13369 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13370 i != e; ++i) {
13371 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13372 if (CE == 0) continue;
13373
13374 // If we already folded this constant, don't try again.
13375 if (!FoldedConstants.insert(CE))
13376 continue;
13377
Chris Lattner7b550cc2009-11-06 04:27:31 +000013378 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013379 if (NewC && NewC != CE) {
13380 *i = NewC;
13381 MadeIRChange = true;
13382 }
13383 }
13384 }
13385
Devang Patel7fe1dec2008-11-19 18:56:50 +000013386
Chris Lattner67f7d542009-10-12 03:58:40 +000013387 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013388 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013389
13390 // Recursively visit successors. If this is a branch or switch on a
13391 // constant, only visit the reachable successor.
13392 TerminatorInst *TI = BB->getTerminator();
13393 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13394 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13395 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013396 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013397 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013398 continue;
13399 }
13400 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13401 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13402 // See if this is an explicit destination.
13403 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13404 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013405 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013406 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013407 continue;
13408 }
13409
13410 // Otherwise it is the default destination.
13411 Worklist.push_back(SI->getSuccessor(0));
13412 continue;
13413 }
13414 }
13415
13416 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13417 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013418 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013419
13420 // Once we've found all of the instructions to add to instcombine's worklist,
13421 // add them in reverse order. This way instcombine will visit from the top
13422 // of the function down. This jives well with the way that it adds all uses
13423 // of instructions to the worklist after doing a transformation, thus avoiding
13424 // some N^2 behavior in pathological cases.
13425 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13426 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013427
13428 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013429}
13430
Chris Lattnerec9c3582007-03-03 02:04:50 +000013431bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013432 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013433
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013434 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13435 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013436
Chris Lattnerb3d59702005-07-07 20:40:38 +000013437 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013438 // Do a depth-first traversal of the function, populate the worklist with
13439 // the reachable instructions. Ignore blocks that are not reachable. Keep
13440 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013441 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013442 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013443
Chris Lattnerb3d59702005-07-07 20:40:38 +000013444 // Do a quick scan over the function. If we find any blocks that are
13445 // unreachable, remove any instructions inside of them. This prevents
13446 // the instcombine code from having to deal with some bad special cases.
13447 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13448 if (!Visited.count(BB)) {
13449 Instruction *Term = BB->getTerminator();
13450 while (Term != BB->begin()) { // Remove instrs bottom-up
13451 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013452
Chris Lattnerbdff5482009-08-23 04:37:46 +000013453 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013454 // A debug intrinsic shouldn't force another iteration if we weren't
13455 // going to do one without it.
13456 if (!isa<DbgInfoIntrinsic>(I)) {
13457 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013458 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013459 }
Devang Patel228ebd02009-10-13 22:56:32 +000013460
Devang Patel228ebd02009-10-13 22:56:32 +000013461 // If I is not void type then replaceAllUsesWith undef.
13462 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013463 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013464 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013465 I->eraseFromParent();
13466 }
13467 }
13468 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013469
Chris Lattner873ff012009-08-30 05:55:36 +000013470 while (!Worklist.isEmpty()) {
13471 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013472 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013473
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013474 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013475 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013476 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013477 EraseInstFromFunction(*I);
13478 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013479 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013480 continue;
13481 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013482
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013483 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013484 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013485 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013486 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013487
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013488 // Add operands to the worklist.
13489 ReplaceInstUsesWith(*I, C);
13490 ++NumConstProp;
13491 EraseInstFromFunction(*I);
13492 MadeIRChange = true;
13493 continue;
13494 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013495
Chris Lattnerea1c4542004-12-08 23:43:58 +000013496 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013497 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013498 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013499 Instruction *UserInst = cast<Instruction>(I->use_back());
13500 BasicBlock *UserParent;
13501
13502 // Get the block the use occurs in.
13503 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13504 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13505 else
13506 UserParent = UserInst->getParent();
13507
Chris Lattnerea1c4542004-12-08 23:43:58 +000013508 if (UserParent != BB) {
13509 bool UserIsSuccessor = false;
13510 // See if the user is one of our successors.
13511 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13512 if (*SI == UserParent) {
13513 UserIsSuccessor = true;
13514 break;
13515 }
13516
13517 // If the user is one of our immediate successors, and if that successor
13518 // only has us as a predecessors (we'd have to split the critical edge
13519 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013520 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013521 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013522 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013523 }
13524 }
13525
Chris Lattner74381062009-08-30 07:44:24 +000013526 // Now that we have an instruction, try combining it to simplify it.
13527 Builder->SetInsertPoint(I->getParent(), I);
13528
Reid Spencera9b81012007-03-26 17:44:01 +000013529#ifndef NDEBUG
13530 std::string OrigI;
13531#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013532 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013533 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13534
Chris Lattner90ac28c2002-08-02 19:29:35 +000013535 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013536 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013537 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013538 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013539 DEBUG(errs() << "IC: Old = " << *I << '\n'
13540 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013541
Chris Lattnerf523d062004-06-09 05:08:07 +000013542 // Everything uses the new instruction now.
13543 I->replaceAllUsesWith(Result);
13544
13545 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013546 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013547 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013548
Chris Lattner6934a042007-02-11 01:23:03 +000013549 // Move the name to the new instruction first.
13550 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013551
13552 // Insert the new instruction into the basic block...
13553 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013554 BasicBlock::iterator InsertPos = I;
13555
13556 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13557 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13558 ++InsertPos;
13559
13560 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013561
Chris Lattner7a1e9242009-08-30 06:13:40 +000013562 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013563 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013564#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013565 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13566 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013567#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013568
Chris Lattner90ac28c2002-08-02 19:29:35 +000013569 // If the instruction was modified, it's possible that it is now dead.
13570 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013571 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013572 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013573 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013574 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013575 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013576 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013577 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013578 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013579 }
13580 }
13581
Chris Lattner873ff012009-08-30 05:55:36 +000013582 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013583 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013584}
13585
Chris Lattnerec9c3582007-03-03 02:04:50 +000013586
13587bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013588 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013589 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013590 TD = getAnalysisIfAvailable<TargetData>();
13591
Chris Lattner74381062009-08-30 07:44:24 +000013592
13593 /// Builder - This is an IRBuilder that automatically inserts new
13594 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013595 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013596 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013597 InstCombineIRInserter(Worklist));
13598 Builder = &TheBuilder;
13599
Chris Lattnerec9c3582007-03-03 02:04:50 +000013600 bool EverMadeChange = false;
13601
13602 // Iterate while there is work to do.
13603 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013604 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013605 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013606
13607 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013608 return EverMadeChange;
13609}
13610
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013611FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013612 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013613}