blob: f55aff31255e6f3289bf0927deb4494b9943c0fe [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
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// 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"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Duncan Sandsb84abcd2007-09-11 14:35:41 +000042#include "llvm/ParameterAttributes.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000196
Reid Spencere4d87aa2006-12-23 06:05:41 +0000197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000200 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000203 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000215 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000218 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000223 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000224 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000225 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000226 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000227 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000228 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000229 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000232
233 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000235
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000237 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240
Chris Lattner28977af2004-04-05 01:30:19 +0000241 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000242 // InsertNewInstBefore - insert an instruction New before instruction Old
243 // in the program. Add the new instruction to the worklist.
244 //
Chris Lattner955f3312004-09-28 21:48:02 +0000245 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000246 assert(New && New->getParent() == 0 &&
247 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000248 BasicBlock *BB = Old.getParent();
249 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000250 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000251 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000252 }
253
Chris Lattner0c967662004-09-24 15:21:34 +0000254 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255 /// This also adds the cast to the worklist. Finally, this returns the
256 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000257 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000259 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000260
Chris Lattnere2ed0572006-04-06 19:19:17 +0000261 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000262 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000263
Reid Spencer17212df2006-12-12 09:18:51 +0000264 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000265 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000266 return C;
267 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000268
269 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271 }
272
Chris Lattner0c967662004-09-24 15:21:34 +0000273
Chris Lattner8b170942002-08-09 23:47:40 +0000274 // ReplaceInstUsesWith - This method is to be used when an instruction is
275 // found to be dead, replacable with another preexisting expression. Here
276 // we add all uses of I to the worklist, replace all uses of I with the new
277 // value, then return I, so that the inst combiner will know that I was
278 // modified.
279 //
280 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000281 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000282 if (&I != V) {
283 I.replaceAllUsesWith(V);
284 return &I;
285 } else {
286 // If we are replacing the instruction with itself, this must be in a
287 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000288 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000289 return &I;
290 }
Chris Lattner8b170942002-08-09 23:47:40 +0000291 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000292
Chris Lattner6dce1a72006-02-07 06:56:34 +0000293 // UpdateValueUsesWith - This method is to be used when an value is
294 // found to be replacable with another preexisting expression or was
295 // updated. Here we add all uses of I to the worklist, replace all uses of
296 // I with the new value (unless the instruction was just updated), then
297 // return true, so that the inst combiner will know that I was modified.
298 //
299 bool UpdateValueUsesWith(Value *Old, Value *New) {
300 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
301 if (Old != New)
302 Old->replaceAllUsesWith(New);
303 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000304 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000305 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000307 return true;
308 }
309
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000310 // EraseInstFromFunction - When dealing with an instruction that has side
311 // effects or produces a void value, we can't rely on DCE to delete the
312 // instruction. Instead, visit methods should return the value returned by
313 // this function.
314 Instruction *EraseInstFromFunction(Instruction &I) {
315 assert(I.use_empty() && "Cannot erase instruction that is used!");
316 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000317 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000318 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319 return 0; // Don't do anything with FI
320 }
321
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000322 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000323 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324 /// InsertBefore instruction. This is specialized a bit to avoid inserting
325 /// casts that are known to not do anything...
326 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000327 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000329 Instruction *InsertBefore);
330
Reid Spencere4d87aa2006-12-23 06:05:41 +0000331 /// SimplifyCommutative - This performs a few simplifications for
332 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000333 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000334
Reid Spencere4d87aa2006-12-23 06:05:41 +0000335 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336 /// most-complex to least-complex order.
337 bool SimplifyCompare(CmpInst &I);
338
Reid Spencer2ec619a2007-03-23 21:24:59 +0000339 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000341 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
342 APInt& KnownZero, APInt& KnownOne,
343 unsigned Depth = 0);
344
Chris Lattner867b99f2006-10-05 06:55:50 +0000345 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346 uint64_t &UndefElts, unsigned Depth = 0);
347
Chris Lattner4e998b22004-09-29 05:07:12 +0000348 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349 // PHI node as operand #0, see if we can fold the instruction into the PHI
350 // (which is only possible if all operands to the PHI are constants).
351 Instruction *FoldOpIntoPhi(Instruction &I);
352
Chris Lattnerbac32862004-11-14 19:13:23 +0000353 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354 // operator and they all are only used by the PHI, PHI together their
355 // inputs, and do the operation once, to the result of the PHI.
356 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000357 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358
359
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000360 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000362
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000363 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000364 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000365 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000366 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000367 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000368 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000369 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000370 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
Chris Lattnerafe91a52006-06-15 19:07:26 +0000372
Reid Spencerc55b2432006-12-13 18:21:21 +0000373 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000374 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000375
Devang Patel19974732007-05-03 01:11:54 +0000376 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000377 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000378}
379
Chris Lattner4f98c562003-03-10 21:43:22 +0000380// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000381// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000382static unsigned getComplexity(Value *V) {
383 if (isa<Instruction>(V)) {
384 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000385 return 3;
386 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000387 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000388 if (isa<Argument>(V)) return 3;
389 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000390}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000391
Chris Lattnerc8802d22003-03-11 00:12:48 +0000392// isOnlyUse - Return true if this instruction will be deleted if we stop using
393// it.
394static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000395 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000396}
397
Chris Lattner4cb170c2004-02-23 06:38:22 +0000398// getPromotedType - Return the specified type promoted as it would be to pass
399// though a va_arg area...
400static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000401 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402 if (ITy->getBitWidth() < 32)
403 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000404 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000405 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000406}
407
Reid Spencer3da59db2006-11-27 01:05:10 +0000408/// getBitCastOperand - If the specified operand is a CastInst or a constant
409/// expression bitcast, return the operand value, otherwise return null.
410static Value *getBitCastOperand(Value *V) {
411 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000412 return I->getOperand(0);
413 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000414 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000415 return CE->getOperand(0);
416 return 0;
417}
418
Reid Spencer3da59db2006-11-27 01:05:10 +0000419/// This function is a wrapper around CastInst::isEliminableCastPair. It
420/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000421static Instruction::CastOps
422isEliminableCastPair(
423 const CastInst *CI, ///< The first cast instruction
424 unsigned opcode, ///< The opcode of the second cast instruction
425 const Type *DstTy, ///< The target type for the second cast instruction
426 TargetData *TD ///< The target data for pointer size
427) {
428
429 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
430 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000431
Reid Spencer3da59db2006-11-27 01:05:10 +0000432 // Get the opcodes of the two Cast instructions
433 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436 return Instruction::CastOps(
437 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000439}
440
441/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442/// in any code being generated. It does not require codegen if V is simple
443/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000444static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
445 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
Chris Lattner01575b72006-05-25 23:24:33 +0000448 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000449 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000450 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000451 return false;
452 return true;
453}
454
455/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456/// InsertBefore instruction. This is specialized a bit to avoid inserting
457/// casts that are known to not do anything...
458///
Reid Spencer17212df2006-12-12 09:18:51 +0000459Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000461 Instruction *InsertBefore) {
462 if (V->getType() == DestTy) return V;
463 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000464 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000465
Reid Spencer17212df2006-12-12 09:18:51 +0000466 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000467}
468
Chris Lattner4f98c562003-03-10 21:43:22 +0000469// SimplifyCommutative - This performs a few simplifications for commutative
470// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000471//
Chris Lattner4f98c562003-03-10 21:43:22 +0000472// 1. Order operands such that they are listed from right (least complex) to
473// left (most complex). This puts constants before unary operators before
474// binary operators.
475//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000476// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000478//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000479bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000480 bool Changed = false;
481 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000483
Chris Lattner4f98c562003-03-10 21:43:22 +0000484 if (!I.isAssociative()) return Changed;
485 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000486 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000489 Constant *Folded = ConstantExpr::get(I.getOpcode(),
490 cast<Constant>(I.getOperand(1)),
491 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492 I.setOperand(0, Op->getOperand(0));
493 I.setOperand(1, Folded);
494 return true;
495 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497 isOnlyUse(Op) && isOnlyUse(Op1)) {
498 Constant *C1 = cast<Constant>(Op->getOperand(1));
499 Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504 Op1->getOperand(0),
505 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000506 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507 I.setOperand(0, New);
508 I.setOperand(1, Folded);
509 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000513}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000514
Reid Spencere4d87aa2006-12-23 06:05:41 +0000515/// SimplifyCompare - For a CmpInst this function just orders the operands
516/// so that theyare listed from right (least complex) to left (most complex).
517/// This puts constants before unary operators before binary operators.
518bool InstCombiner::SimplifyCompare(CmpInst &I) {
519 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520 return false;
521 I.swapOperands();
522 // Compare instructions are not associative so there's nothing else we can do.
523 return true;
524}
525
Chris Lattner8d969642003-03-10 23:06:50 +0000526// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000528//
Chris Lattner8d969642003-03-10 23:06:50 +0000529static inline Value *dyn_castNegVal(Value *V) {
530 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000531 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000532
Chris Lattner0ce85802004-12-14 20:08:06 +0000533 // Constants can be considered to be negated values if they can be folded.
534 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000536 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000537}
538
Chris Lattner8d969642003-03-10 23:06:50 +0000539static inline Value *dyn_castNotVal(Value *V) {
540 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000541 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000542
543 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000544 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000545 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000546 return 0;
547}
548
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549// dyn_castFoldableMul - If this value is a multiply that can be folded into
550// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000551// non-constant operand of the multiply, and set CST to point to the multiplier.
552// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553//
Chris Lattner50af16a2004-11-13 19:50:12 +0000554static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000555 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000556 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000558 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000559 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000560 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000561 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000562 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000563 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000564 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000565 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000566 return I->getOperand(0);
567 }
568 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000570}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000571
Chris Lattner574da9b2005-01-13 20:14:25 +0000572/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573/// expression, return it.
574static User *dyn_castGetElementPtr(Value *V) {
575 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577 if (CE->getOpcode() == Instruction::GetElementPtr)
578 return cast<User>(V);
579 return false;
580}
581
Reid Spencer7177c3a2007-03-25 05:33:51 +0000582/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000583static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000584 APInt Val(C->getValue());
585 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000586}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000587/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000588static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000589 APInt Val(C->getValue());
590 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000591}
592/// Add - Add two ConstantInts together
593static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594 return ConstantInt::get(C1->getValue() + C2->getValue());
595}
596/// And - Bitwise AND two ConstantInts together
597static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598 return ConstantInt::get(C1->getValue() & C2->getValue());
599}
600/// Subtract - Subtract one ConstantInt from another
601static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602 return ConstantInt::get(C1->getValue() - C2->getValue());
603}
604/// Multiply - Multiply two ConstantInts together
605static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000607}
608
Chris Lattner68d5ff22006-02-09 07:38:58 +0000609/// ComputeMaskedBits - Determine which of the bits specified in Mask are
610/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000611/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
612/// processing.
613/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
614/// we cannot optimize based on the assumption that it is zero without changing
615/// it to be an explicit zero. If we don't change it to zero, other code could
616/// optimized based on the contradictory assumption that it is non-zero.
617/// Because instcombine aggressively folds operations with undef args anyway,
618/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000619static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000620 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000621 assert(V && "No Value?");
622 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000623 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000624 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000625 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000626 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000627 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000628 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
629 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000630 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000631 KnownZero = ~KnownOne & Mask;
632 return;
633 }
634
Reid Spencer3e7594f2007-03-08 01:46:38 +0000635 if (Depth == 6 || Mask == 0)
636 return; // Limit search depth.
637
638 Instruction *I = dyn_cast<Instruction>(V);
639 if (!I) return;
640
Zhou Sheng771dbf72007-03-13 02:23:10 +0000641 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000642 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000643
644 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000645 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000646 // If either the LHS or the RHS are Zero, the result is zero.
647 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000648 APInt Mask2(Mask & ~KnownZero);
649 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000650 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
651 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
652
653 // Output known-1 bits are only known if set in both the LHS & RHS.
654 KnownOne &= KnownOne2;
655 // Output known-0 are known to be clear if zero in either the LHS | RHS.
656 KnownZero |= KnownZero2;
657 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000658 }
659 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000660 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000661 APInt Mask2(Mask & ~KnownOne);
662 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
665
666 // Output known-0 bits are only known if clear in both the LHS & RHS.
667 KnownZero &= KnownZero2;
668 // Output known-1 are known to be set if set in either the LHS | RHS.
669 KnownOne |= KnownOne2;
670 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000671 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000672 case Instruction::Xor: {
673 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
674 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
675 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
676 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
677
678 // Output known-0 bits are known if clear or set in both the LHS & RHS.
679 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
680 // Output known-1 are known to be set if set in only one of the LHS, RHS.
681 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
682 KnownZero = KnownZeroOut;
683 return;
684 }
685 case Instruction::Select:
686 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
687 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
689 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
690
691 // Only known if known in both the LHS and RHS.
692 KnownOne &= KnownOne2;
693 KnownZero &= KnownZero2;
694 return;
695 case Instruction::FPTrunc:
696 case Instruction::FPExt:
697 case Instruction::FPToUI:
698 case Instruction::FPToSI:
699 case Instruction::SIToFP:
700 case Instruction::PtrToInt:
701 case Instruction::UIToFP:
702 case Instruction::IntToPtr:
703 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000704 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000705 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000706 uint32_t SrcBitWidth =
707 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000708 APInt MaskIn(Mask);
709 MaskIn.zext(SrcBitWidth);
710 KnownZero.zext(SrcBitWidth);
711 KnownOne.zext(SrcBitWidth);
712 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000713 KnownZero.trunc(BitWidth);
714 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000715 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000716 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 case Instruction::BitCast: {
718 const Type *SrcTy = I->getOperand(0)->getType();
719 if (SrcTy->isInteger()) {
720 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
721 return;
722 }
723 break;
724 }
725 case Instruction::ZExt: {
726 // Compute the bits in the result that are not present in the input.
727 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000728 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000729
Zhou Shengaa305ab2007-03-28 02:19:03 +0000730 APInt MaskIn(Mask);
731 MaskIn.trunc(SrcBitWidth);
732 KnownZero.trunc(SrcBitWidth);
733 KnownOne.trunc(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
736 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000737 KnownZero.zext(BitWidth);
738 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000739 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 return;
741 }
742 case Instruction::SExt: {
743 // Compute the bits in the result that are not present in the input.
744 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000745 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000746
Zhou Shengaa305ab2007-03-28 02:19:03 +0000747 APInt MaskIn(Mask);
748 MaskIn.trunc(SrcBitWidth);
749 KnownZero.trunc(SrcBitWidth);
750 KnownOne.trunc(SrcBitWidth);
751 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000753 KnownZero.zext(BitWidth);
754 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000755
756 // If the sign bit of the input is known set or clear, then we know the
757 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000758 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000759 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000760 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000761 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000762 return;
763 }
764 case Instruction::Shl:
765 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
766 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000767 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000768 APInt Mask2(Mask.lshr(ShiftAmt));
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000771 KnownZero <<= ShiftAmt;
772 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000773 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774 return;
775 }
776 break;
777 case Instruction::LShr:
778 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
779 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
780 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000781 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000782
783 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000784 APInt Mask2(Mask.shl(ShiftAmt));
785 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000786 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
787 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000789 // high bits known zero.
790 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791 return;
792 }
793 break;
794 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000795 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000796 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
797 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000798 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000799
800 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000801 APInt Mask2(Mask.shl(ShiftAmt));
802 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000803 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
804 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
805 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
806
Zhou Shengaa305ab2007-03-28 02:19:03 +0000807 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
808 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000809 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000810 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000811 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 return;
813 }
814 break;
815 }
816}
817
Reid Spencere7816b52007-03-08 01:52:58 +0000818/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
819/// this predicate to simplify operations downstream. Mask is known to be zero
820/// for bits that V cannot have.
821static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000822 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000823 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
824 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
825 return (KnownZero & Mask) == Mask;
826}
827
Chris Lattner255d8912006-02-11 09:31:47 +0000828/// ShrinkDemandedConstant - Check to see if the specified operand of the
829/// specified instruction is a constant integer. If so, check to see if there
830/// are any bits set in the constant that are not demanded. If so, shrink the
831/// constant and return true.
832static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000833 APInt Demanded) {
834 assert(I && "No instruction?");
835 assert(OpNo < I->getNumOperands() && "Operand index too large");
836
837 // If the operand is not a constant integer, nothing to do.
838 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
839 if (!OpC) return false;
840
841 // If there are no bits set that aren't demanded, nothing to do.
842 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
843 if ((~Demanded & OpC->getValue()) == 0)
844 return false;
845
846 // This instruction is producing bits that are not demanded. Shrink the RHS.
847 Demanded &= OpC->getValue();
848 I->setOperand(OpNo, ConstantInt::get(Demanded));
849 return true;
850}
851
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000852// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
853// set of known zero and one bits, compute the maximum and minimum values that
854// could have the specified known zero and known one bits, returning them in
855// min/max.
856static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000857 const APInt& KnownZero,
858 const APInt& KnownOne,
859 APInt& Min, APInt& Max) {
860 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
861 assert(KnownZero.getBitWidth() == BitWidth &&
862 KnownOne.getBitWidth() == BitWidth &&
863 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
864 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000865 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000866
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000867 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
868 // bit if it is unknown.
869 Min = KnownOne;
870 Max = KnownOne|UnknownBits;
871
Zhou Sheng4acf1552007-03-28 05:15:57 +0000872 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000873 Min.set(BitWidth-1);
874 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000875 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000876}
877
878// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
879// a set of known zero and one bits, compute the maximum and minimum values that
880// could have the specified known zero and known one bits, returning them in
881// min/max.
882static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000883 const APInt &KnownZero,
884 const APInt &KnownOne,
885 APInt &Min, APInt &Max) {
886 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000887 assert(KnownZero.getBitWidth() == BitWidth &&
888 KnownOne.getBitWidth() == BitWidth &&
889 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
890 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000891 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000892
893 // The minimum value is when the unknown bits are all zeros.
894 Min = KnownOne;
895 // The maximum value is when the unknown bits are all ones.
896 Max = KnownOne|UnknownBits;
897}
Chris Lattner255d8912006-02-11 09:31:47 +0000898
Reid Spencer8cb68342007-03-12 17:25:59 +0000899/// SimplifyDemandedBits - This function attempts to replace V with a simpler
900/// value based on the demanded bits. When this function is called, it is known
901/// that only the bits set in DemandedMask of the result of V are ever used
902/// downstream. Consequently, depending on the mask and V, it may be possible
903/// to replace V with a constant or one of its operands. In such cases, this
904/// function does the replacement and returns true. In all other cases, it
905/// returns false after analyzing the expression and setting KnownOne and known
906/// to be one in the expression. KnownZero contains all the bits that are known
907/// to be zero in the expression. These are provided to potentially allow the
908/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
909/// the expression. KnownOne and KnownZero always follow the invariant that
910/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
911/// the bits in KnownOne and KnownZero may only be accurate for those bits set
912/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
913/// and KnownOne must all be the same.
914bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
915 APInt& KnownZero, APInt& KnownOne,
916 unsigned Depth) {
917 assert(V != 0 && "Null pointer of Value???");
918 assert(Depth <= 6 && "Limit Search Depth");
919 uint32_t BitWidth = DemandedMask.getBitWidth();
920 const IntegerType *VTy = cast<IntegerType>(V->getType());
921 assert(VTy->getBitWidth() == BitWidth &&
922 KnownZero.getBitWidth() == BitWidth &&
923 KnownOne.getBitWidth() == BitWidth &&
924 "Value *V, DemandedMask, KnownZero and KnownOne \
925 must have same BitWidth");
926 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
927 // We know all of the bits for a constant!
928 KnownOne = CI->getValue() & DemandedMask;
929 KnownZero = ~KnownOne & DemandedMask;
930 return false;
931 }
932
Zhou Sheng96704452007-03-14 03:21:24 +0000933 KnownZero.clear();
934 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000935 if (!V->hasOneUse()) { // Other users may use these bits.
936 if (Depth != 0) { // Not at the root.
937 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
938 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
939 return false;
940 }
941 // If this is the root being simplified, allow it to have multiple uses,
942 // just set the DemandedMask to all bits.
943 DemandedMask = APInt::getAllOnesValue(BitWidth);
944 } else if (DemandedMask == 0) { // Not demanding any bits from V.
945 if (V != UndefValue::get(VTy))
946 return UpdateValueUsesWith(V, UndefValue::get(VTy));
947 return false;
948 } else if (Depth == 6) { // Limit search depth.
949 return false;
950 }
951
952 Instruction *I = dyn_cast<Instruction>(V);
953 if (!I) return false; // Only analyze instructions.
954
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
956 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
957 switch (I->getOpcode()) {
958 default: break;
959 case Instruction::And:
960 // If either the LHS or the RHS are Zero, the result is zero.
961 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962 RHSKnownZero, RHSKnownOne, Depth+1))
963 return true;
964 assert((RHSKnownZero & RHSKnownOne) == 0 &&
965 "Bits known to be one AND zero?");
966
967 // If something is known zero on the RHS, the bits aren't demanded on the
968 // LHS.
969 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
970 LHSKnownZero, LHSKnownOne, Depth+1))
971 return true;
972 assert((LHSKnownZero & LHSKnownOne) == 0 &&
973 "Bits known to be one AND zero?");
974
975 // If all of the demanded bits are known 1 on one side, return the other.
976 // These bits cannot contribute to the result of the 'and'.
977 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
978 (DemandedMask & ~LHSKnownZero))
979 return UpdateValueUsesWith(I, I->getOperand(0));
980 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
981 (DemandedMask & ~RHSKnownZero))
982 return UpdateValueUsesWith(I, I->getOperand(1));
983
984 // If all of the demanded bits in the inputs are known zeros, return zero.
985 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
986 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
987
988 // If the RHS is a constant, see if we can simplify it.
989 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
990 return UpdateValueUsesWith(I, I);
991
992 // Output known-1 bits are only known if set in both the LHS & RHS.
993 RHSKnownOne &= LHSKnownOne;
994 // Output known-0 are known to be clear if zero in either the LHS | RHS.
995 RHSKnownZero |= LHSKnownZero;
996 break;
997 case Instruction::Or:
998 // If either the LHS or the RHS are One, the result is One.
999 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1000 RHSKnownZero, RHSKnownOne, Depth+1))
1001 return true;
1002 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1003 "Bits known to be one AND zero?");
1004 // If something is known one on the RHS, the bits aren't demanded on the
1005 // LHS.
1006 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1007 LHSKnownZero, LHSKnownOne, Depth+1))
1008 return true;
1009 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1010 "Bits known to be one AND zero?");
1011
1012 // If all of the demanded bits are known zero on one side, return the other.
1013 // These bits cannot contribute to the result of the 'or'.
1014 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1015 (DemandedMask & ~LHSKnownOne))
1016 return UpdateValueUsesWith(I, I->getOperand(0));
1017 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1018 (DemandedMask & ~RHSKnownOne))
1019 return UpdateValueUsesWith(I, I->getOperand(1));
1020
1021 // If all of the potentially set bits on one side are known to be set on
1022 // the other side, just use the 'other' side.
1023 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1024 (DemandedMask & (~RHSKnownZero)))
1025 return UpdateValueUsesWith(I, I->getOperand(0));
1026 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1027 (DemandedMask & (~LHSKnownZero)))
1028 return UpdateValueUsesWith(I, I->getOperand(1));
1029
1030 // If the RHS is a constant, see if we can simplify it.
1031 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1032 return UpdateValueUsesWith(I, I);
1033
1034 // Output known-0 bits are only known if clear in both the LHS & RHS.
1035 RHSKnownZero &= LHSKnownZero;
1036 // Output known-1 are known to be set if set in either the LHS | RHS.
1037 RHSKnownOne |= LHSKnownOne;
1038 break;
1039 case Instruction::Xor: {
1040 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1041 RHSKnownZero, RHSKnownOne, Depth+1))
1042 return true;
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1045 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1046 LHSKnownZero, LHSKnownOne, Depth+1))
1047 return true;
1048 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1049 "Bits known to be one AND zero?");
1050
1051 // If all of the demanded bits are known zero on one side, return the other.
1052 // These bits cannot contribute to the result of the 'xor'.
1053 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1054 return UpdateValueUsesWith(I, I->getOperand(0));
1055 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1056 return UpdateValueUsesWith(I, I->getOperand(1));
1057
1058 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1059 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1060 (RHSKnownOne & LHSKnownOne);
1061 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1062 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1063 (RHSKnownOne & LHSKnownZero);
1064
1065 // If all of the demanded bits are known to be zero on one side or the
1066 // other, turn this into an *inclusive* or.
1067 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1068 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1069 Instruction *Or =
1070 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1071 I->getName());
1072 InsertNewInstBefore(Or, *I);
1073 return UpdateValueUsesWith(I, Or);
1074 }
1075
1076 // If all of the demanded bits on one side are known, and all of the set
1077 // bits on that side are also known to be set on the other side, turn this
1078 // into an AND, as we know the bits will be cleared.
1079 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1080 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1081 // all known
1082 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1083 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1084 Instruction *And =
1085 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1086 InsertNewInstBefore(And, *I);
1087 return UpdateValueUsesWith(I, And);
1088 }
1089 }
1090
1091 // If the RHS is a constant, see if we can simplify it.
1092 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1093 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1094 return UpdateValueUsesWith(I, I);
1095
1096 RHSKnownZero = KnownZeroOut;
1097 RHSKnownOne = KnownOneOut;
1098 break;
1099 }
1100 case Instruction::Select:
1101 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1102 RHSKnownZero, RHSKnownOne, Depth+1))
1103 return true;
1104 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1105 LHSKnownZero, LHSKnownOne, Depth+1))
1106 return true;
1107 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1108 "Bits known to be one AND zero?");
1109 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1110 "Bits known to be one AND zero?");
1111
1112 // If the operands are constants, see if we can simplify them.
1113 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1114 return UpdateValueUsesWith(I, I);
1115 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1116 return UpdateValueUsesWith(I, I);
1117
1118 // Only known if known in both the LHS and RHS.
1119 RHSKnownOne &= LHSKnownOne;
1120 RHSKnownZero &= LHSKnownZero;
1121 break;
1122 case Instruction::Trunc: {
1123 uint32_t truncBf =
1124 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 DemandedMask.zext(truncBf);
1126 RHSKnownZero.zext(truncBf);
1127 RHSKnownOne.zext(truncBf);
1128 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 return true;
1131 DemandedMask.trunc(BitWidth);
1132 RHSKnownZero.trunc(BitWidth);
1133 RHSKnownOne.trunc(BitWidth);
1134 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1135 "Bits known to be one AND zero?");
1136 break;
1137 }
1138 case Instruction::BitCast:
1139 if (!I->getOperand(0)->getType()->isInteger())
1140 return false;
1141
1142 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143 RHSKnownZero, RHSKnownOne, Depth+1))
1144 return true;
1145 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1146 "Bits known to be one AND zero?");
1147 break;
1148 case Instruction::ZExt: {
1149 // Compute the bits in the result that are not present in the input.
1150 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001151 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001152
Zhou Shengd48653a2007-03-29 04:45:55 +00001153 DemandedMask.trunc(SrcBitWidth);
1154 RHSKnownZero.trunc(SrcBitWidth);
1155 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001156 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 return true;
1159 DemandedMask.zext(BitWidth);
1160 RHSKnownZero.zext(BitWidth);
1161 RHSKnownOne.zext(BitWidth);
1162 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1163 "Bits known to be one AND zero?");
1164 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 break;
1167 }
1168 case Instruction::SExt: {
1169 // Compute the bits in the result that are not present in the input.
1170 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001171 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001172
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001175
Zhou Sheng01542f32007-03-29 02:26:30 +00001176 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001177 // If any of the sign extended bits are demanded, we know that the sign
1178 // bit is demanded.
1179 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001180 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
Zhou Shengd48653a2007-03-29 04:45:55 +00001182 InputDemandedBits.trunc(SrcBitWidth);
1183 RHSKnownZero.trunc(SrcBitWidth);
1184 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001185 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1186 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 return true;
1188 InputDemandedBits.zext(BitWidth);
1189 RHSKnownZero.zext(BitWidth);
1190 RHSKnownOne.zext(BitWidth);
1191 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1192 "Bits known to be one AND zero?");
1193
1194 // If the sign bit of the input is known set or clear, then we know the
1195 // top bits of the result.
1196
1197 // If the input sign bit is known zero, or if the NewBits are not demanded
1198 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001199 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001200 {
1201 // Convert to ZExt cast
1202 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1203 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001204 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001206 }
1207 break;
1208 }
1209 case Instruction::Add: {
1210 // Figure out what the input bits are. If the top bits of the and result
1211 // are not demanded, then the add doesn't demand them from its input
1212 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001213 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 // If there is a constant on the RHS, there are a variety of xformations
1216 // we can do.
1217 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218 // If null, this should be simplified elsewhere. Some of the xforms here
1219 // won't work if the RHS is zero.
1220 if (RHS->isZero())
1221 break;
1222
1223 // If the top bit of the output is demanded, demand everything from the
1224 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001226
1227 // Find information about known zero/one bits in the input.
1228 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1229 LHSKnownZero, LHSKnownOne, Depth+1))
1230 return true;
1231
1232 // If the RHS of the add has bits set that can't affect the input, reduce
1233 // the constant.
1234 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1235 return UpdateValueUsesWith(I, I);
1236
1237 // Avoid excess work.
1238 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1239 break;
1240
1241 // Turn it into OR if input bits are zero.
1242 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1243 Instruction *Or =
1244 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1245 I->getName());
1246 InsertNewInstBefore(Or, *I);
1247 return UpdateValueUsesWith(I, Or);
1248 }
1249
1250 // We can say something about the output known-zero and known-one bits,
1251 // depending on potential carries from the input constant and the
1252 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1253 // bits set and the RHS constant is 0x01001, then we know we have a known
1254 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1255
1256 // To compute this, we first compute the potential carry bits. These are
1257 // the bits which may be modified. I'm not aware of a better way to do
1258 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001259 const APInt& RHSVal = RHS->getValue();
1260 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001261
1262 // Now that we know which bits have carries, compute the known-1/0 sets.
1263
1264 // Bits are known one if they are known zero in one operand and one in the
1265 // other, and there is no input carry.
1266 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1267 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1268
1269 // Bits are known zero if they are known zero in both operands and there
1270 // is no input carry.
1271 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1272 } else {
1273 // If the high-bits of this ADD are not demanded, then it does not demand
1274 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 // Right fill the mask of bits for this ADD to demand the most
1277 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001278 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1280 LHSKnownZero, LHSKnownOne, Depth+1))
1281 return true;
1282 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1283 LHSKnownZero, LHSKnownOne, Depth+1))
1284 return true;
1285 }
1286 }
1287 break;
1288 }
1289 case Instruction::Sub:
1290 // If the high-bits of this SUB are not demanded, then it does not demand
1291 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 // Right fill the mask of bits for this SUB to demand the most
1294 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001295 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1298 LHSKnownZero, LHSKnownOne, Depth+1))
1299 return true;
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1301 LHSKnownZero, LHSKnownOne, Depth+1))
1302 return true;
1303 }
1304 break;
1305 case Instruction::Shl:
1306 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001307 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1309 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 RHSKnownZero, RHSKnownOne, Depth+1))
1311 return true;
1312 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1313 "Bits known to be one AND zero?");
1314 RHSKnownZero <<= ShiftAmt;
1315 RHSKnownOne <<= ShiftAmt;
1316 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001317 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001318 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001319 }
1320 break;
1321 case Instruction::LShr:
1322 // For a logical shift right
1323 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001324 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001327 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1328 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 RHSKnownZero, RHSKnownOne, Depth+1))
1330 return true;
1331 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1332 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1334 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001335 if (ShiftAmt) {
1336 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001337 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001338 RHSKnownZero |= HighBits; // high bits known zero.
1339 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 }
1341 break;
1342 case Instruction::AShr:
1343 // If this is an arithmetic shift right and only the low-bit is set, we can
1344 // always convert this into a logical shr, even if the shift amount is
1345 // variable. The low bit of the shift cannot be an input sign bit unless
1346 // the shift amount is >= the size of the datatype, which is undefined.
1347 if (DemandedMask == 1) {
1348 // Perform the logical shift right.
1349 Value *NewVal = BinaryOperator::createLShr(
1350 I->getOperand(0), I->getOperand(1), I->getName());
1351 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1352 return UpdateValueUsesWith(I, NewVal);
1353 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001354
1355 // If the sign bit is the only bit demanded by this ashr, then there is no
1356 // need to do it, the shift doesn't change the high bit.
1357 if (DemandedMask.isSignBit())
1358 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001359
1360 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001361 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001362
Reid Spencer8cb68342007-03-12 17:25:59 +00001363 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001364 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001365 // If any of the "high bits" are demanded, we should set the sign bit as
1366 // demanded.
1367 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1368 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001369 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001370 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 RHSKnownZero, RHSKnownOne, Depth+1))
1372 return true;
1373 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1374 "Bits known to be one AND zero?");
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));
Reid Spencer8cb68342007-03-12 17:25:59 +00001377 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1378 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1379
1380 // Handle the sign bits.
1381 APInt SignBit(APInt::getSignBit(BitWidth));
1382 // Adjust to where it is now in the mask.
1383 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1384
1385 // If the input sign bit is known to be zero, or if none of the top bits
1386 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001387 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 (HighBits & ~DemandedMask) == HighBits) {
1389 // Perform the logical shift right.
1390 Value *NewVal = BinaryOperator::createLShr(
1391 I->getOperand(0), SA, I->getName());
1392 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1393 return UpdateValueUsesWith(I, NewVal);
1394 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1395 RHSKnownOne |= HighBits;
1396 }
1397 }
1398 break;
1399 }
1400
1401 // If the client is only demanding bits that we know, return the known
1402 // constant.
1403 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1404 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1405 return false;
1406}
1407
Chris Lattner867b99f2006-10-05 06:55:50 +00001408
1409/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1410/// 64 or fewer elements. DemandedElts contains the set of elements that are
1411/// actually used by the caller. This method analyzes which elements of the
1412/// operand are undef and returns that information in UndefElts.
1413///
1414/// If the information about demanded elements can be used to simplify the
1415/// operation, the operation is simplified, then the resultant value is
1416/// returned. This returns null if no change was made.
1417Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1418 uint64_t &UndefElts,
1419 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001420 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001421 assert(VWidth <= 64 && "Vector too wide to analyze!");
1422 uint64_t EltMask = ~0ULL >> (64-VWidth);
1423 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1424 "Invalid DemandedElts!");
1425
1426 if (isa<UndefValue>(V)) {
1427 // If the entire vector is undefined, just return this info.
1428 UndefElts = EltMask;
1429 return 0;
1430 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1431 UndefElts = EltMask;
1432 return UndefValue::get(V->getType());
1433 }
1434
1435 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001436 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1437 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 Constant *Undef = UndefValue::get(EltTy);
1439
1440 std::vector<Constant*> Elts;
1441 for (unsigned i = 0; i != VWidth; ++i)
1442 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1443 Elts.push_back(Undef);
1444 UndefElts |= (1ULL << i);
1445 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1446 Elts.push_back(Undef);
1447 UndefElts |= (1ULL << i);
1448 } else { // Otherwise, defined.
1449 Elts.push_back(CP->getOperand(i));
1450 }
1451
1452 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 return NewCP != CP ? NewCP : 0;
1455 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001456 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001458 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 Constant *Zero = Constant::getNullValue(EltTy);
1460 Constant *Undef = UndefValue::get(EltTy);
1461 std::vector<Constant*> Elts;
1462 for (unsigned i = 0; i != VWidth; ++i)
1463 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1464 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001465 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 }
1467
1468 if (!V->hasOneUse()) { // Other users may use these bits.
1469 if (Depth != 0) { // Not at the root.
1470 // TODO: Just compute the UndefElts information recursively.
1471 return false;
1472 }
1473 return false;
1474 } else if (Depth == 10) { // Limit search depth.
1475 return false;
1476 }
1477
1478 Instruction *I = dyn_cast<Instruction>(V);
1479 if (!I) return false; // Only analyze instructions.
1480
1481 bool MadeChange = false;
1482 uint64_t UndefElts2;
1483 Value *TmpV;
1484 switch (I->getOpcode()) {
1485 default: break;
1486
1487 case Instruction::InsertElement: {
1488 // If this is a variable index, we don't know which element it overwrites.
1489 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001490 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 if (Idx == 0) {
1492 // Note that we can't propagate undef elt info, because we don't know
1493 // which elt is getting updated.
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1495 UndefElts2, Depth+1);
1496 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1497 break;
1498 }
1499
1500 // If this is inserting an element that isn't demanded, remove this
1501 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001502 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1504 return AddSoonDeadInstToWorklist(*I, 0);
1505
1506 // Otherwise, the element inserted overwrites whatever was there, so the
1507 // input demanded set is simpler than the output set.
1508 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1509 DemandedElts & ~(1ULL << IdxNo),
1510 UndefElts, Depth+1);
1511 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512
1513 // The inserted element is defined.
1514 UndefElts |= 1ULL << IdxNo;
1515 break;
1516 }
Chris Lattner69878332007-04-14 22:29:23 +00001517 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001518 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001519 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1520 if (!VTy) break;
1521 unsigned InVWidth = VTy->getNumElements();
1522 uint64_t InputDemandedElts = 0;
1523 unsigned Ratio;
1524
1525 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001526 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001527 // elements as are demanded of us.
1528 Ratio = 1;
1529 InputDemandedElts = DemandedElts;
1530 } else if (VWidth > InVWidth) {
1531 // Untested so far.
1532 break;
1533
1534 // If there are more elements in the result than there are in the source,
1535 // then an input element is live if any of the corresponding output
1536 // elements are live.
1537 Ratio = VWidth/InVWidth;
1538 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1539 if (DemandedElts & (1ULL << OutIdx))
1540 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1541 }
1542 } else {
1543 // Untested so far.
1544 break;
1545
1546 // If there are more elements in the source than there are in the result,
1547 // then an input element is live if the corresponding output element is
1548 // live.
1549 Ratio = InVWidth/VWidth;
1550 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1551 if (DemandedElts & (1ULL << InIdx/Ratio))
1552 InputDemandedElts |= 1ULL << InIdx;
1553 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001554
Chris Lattner69878332007-04-14 22:29:23 +00001555 // div/rem demand all inputs, because they don't want divide by zero.
1556 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1557 UndefElts2, Depth+1);
1558 if (TmpV) {
1559 I->setOperand(0, TmpV);
1560 MadeChange = true;
1561 }
1562
1563 UndefElts = UndefElts2;
1564 if (VWidth > InVWidth) {
1565 assert(0 && "Unimp");
1566 // If there are more elements in the result than there are in the source,
1567 // then an output element is undef if the corresponding input element is
1568 // undef.
1569 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1570 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1571 UndefElts |= 1ULL << OutIdx;
1572 } else if (VWidth < InVWidth) {
1573 assert(0 && "Unimp");
1574 // If there are more elements in the source than there are in the result,
1575 // then a result element is undef if all of the corresponding input
1576 // elements are undef.
1577 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1578 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1579 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1580 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1581 }
1582 break;
1583 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001584 case Instruction::And:
1585 case Instruction::Or:
1586 case Instruction::Xor:
1587 case Instruction::Add:
1588 case Instruction::Sub:
1589 case Instruction::Mul:
1590 // div/rem demand all inputs, because they don't want divide by zero.
1591 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1592 UndefElts, Depth+1);
1593 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1594 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1595 UndefElts2, Depth+1);
1596 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1597
1598 // Output elements are undefined if both are undefined. Consider things
1599 // like undef&0. The result is known zero, not undef.
1600 UndefElts &= UndefElts2;
1601 break;
1602
1603 case Instruction::Call: {
1604 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1605 if (!II) break;
1606 switch (II->getIntrinsicID()) {
1607 default: break;
1608
1609 // Binary vector operations that work column-wise. A dest element is a
1610 // function of the corresponding input elements from the two inputs.
1611 case Intrinsic::x86_sse_sub_ss:
1612 case Intrinsic::x86_sse_mul_ss:
1613 case Intrinsic::x86_sse_min_ss:
1614 case Intrinsic::x86_sse_max_ss:
1615 case Intrinsic::x86_sse2_sub_sd:
1616 case Intrinsic::x86_sse2_mul_sd:
1617 case Intrinsic::x86_sse2_min_sd:
1618 case Intrinsic::x86_sse2_max_sd:
1619 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1620 UndefElts, Depth+1);
1621 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1622 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1623 UndefElts2, Depth+1);
1624 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1625
1626 // If only the low elt is demanded and this is a scalarizable intrinsic,
1627 // scalarize it now.
1628 if (DemandedElts == 1) {
1629 switch (II->getIntrinsicID()) {
1630 default: break;
1631 case Intrinsic::x86_sse_sub_ss:
1632 case Intrinsic::x86_sse_mul_ss:
1633 case Intrinsic::x86_sse2_sub_sd:
1634 case Intrinsic::x86_sse2_mul_sd:
1635 // TODO: Lower MIN/MAX/ABS/etc
1636 Value *LHS = II->getOperand(1);
1637 Value *RHS = II->getOperand(2);
1638 // Extract the element as scalars.
1639 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1640 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1641
1642 switch (II->getIntrinsicID()) {
1643 default: assert(0 && "Case stmts out of sync!");
1644 case Intrinsic::x86_sse_sub_ss:
1645 case Intrinsic::x86_sse2_sub_sd:
1646 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1647 II->getName()), *II);
1648 break;
1649 case Intrinsic::x86_sse_mul_ss:
1650 case Intrinsic::x86_sse2_mul_sd:
1651 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1652 II->getName()), *II);
1653 break;
1654 }
1655
1656 Instruction *New =
1657 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1658 II->getName());
1659 InsertNewInstBefore(New, *II);
1660 AddSoonDeadInstToWorklist(*II, 0);
1661 return New;
1662 }
1663 }
1664
1665 // Output elements are undefined if both are undefined. Consider things
1666 // like undef&0. The result is known zero, not undef.
1667 UndefElts &= UndefElts2;
1668 break;
1669 }
1670 break;
1671 }
1672 }
1673 return MadeChange ? I : 0;
1674}
1675
Nick Lewycky455e1762007-09-06 02:40:25 +00001676/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001677/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001678/// @brief Determine if the icmp Predicate is true when both operands are equal
1679static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001680 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1681 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1682 pred == ICmpInst::ICMP_SLE;
1683}
1684
Nick Lewycky455e1762007-09-06 02:40:25 +00001685/// @returns true if the specified compare instruction is
1686/// true when both operands are equal...
1687/// @brief Determine if the ICmpInst returns true when both operands are equal
1688static bool isTrueWhenEqual(ICmpInst &ICI) {
1689 return isTrueWhenEqual(ICI.getPredicate());
1690}
1691
Chris Lattner564a7272003-08-13 19:01:45 +00001692/// AssociativeOpt - Perform an optimization on an associative operator. This
1693/// function is designed to check a chain of associative operators for a
1694/// potential to apply a certain optimization. Since the optimization may be
1695/// applicable if the expression was reassociated, this checks the chain, then
1696/// reassociates the expression as necessary to expose the optimization
1697/// opportunity. This makes use of a special Functor, which must define
1698/// 'shouldApply' and 'apply' methods.
1699///
1700template<typename Functor>
1701Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1702 unsigned Opcode = Root.getOpcode();
1703 Value *LHS = Root.getOperand(0);
1704
1705 // Quick check, see if the immediate LHS matches...
1706 if (F.shouldApply(LHS))
1707 return F.apply(Root);
1708
1709 // Otherwise, if the LHS is not of the same opcode as the root, return.
1710 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001711 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001712 // Should we apply this transform to the RHS?
1713 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1714
1715 // If not to the RHS, check to see if we should apply to the LHS...
1716 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1717 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1718 ShouldApply = true;
1719 }
1720
1721 // If the functor wants to apply the optimization to the RHS of LHSI,
1722 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1723 if (ShouldApply) {
1724 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001725
Chris Lattner564a7272003-08-13 19:01:45 +00001726 // Now all of the instructions are in the current basic block, go ahead
1727 // and perform the reassociation.
1728 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1729
1730 // First move the selected RHS to the LHS of the root...
1731 Root.setOperand(0, LHSI->getOperand(1));
1732
1733 // Make what used to be the LHS of the root be the user of the root...
1734 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001735 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001736 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1737 return 0;
1738 }
Chris Lattner65725312004-04-16 18:08:07 +00001739 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001740 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001741 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1742 BasicBlock::iterator ARI = &Root; ++ARI;
1743 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1744 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001745
1746 // Now propagate the ExtraOperand down the chain of instructions until we
1747 // get to LHSI.
1748 while (TmpLHSI != LHSI) {
1749 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001750 // Move the instruction to immediately before the chain we are
1751 // constructing to avoid breaking dominance properties.
1752 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1753 BB->getInstList().insert(ARI, NextLHSI);
1754 ARI = NextLHSI;
1755
Chris Lattner564a7272003-08-13 19:01:45 +00001756 Value *NextOp = NextLHSI->getOperand(1);
1757 NextLHSI->setOperand(1, ExtraOperand);
1758 TmpLHSI = NextLHSI;
1759 ExtraOperand = NextOp;
1760 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001761
Chris Lattner564a7272003-08-13 19:01:45 +00001762 // Now that the instructions are reassociated, have the functor perform
1763 // the transformation...
1764 return F.apply(Root);
1765 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001766
Chris Lattner564a7272003-08-13 19:01:45 +00001767 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1768 }
1769 return 0;
1770}
1771
1772
1773// AddRHS - Implements: X + X --> X << 1
1774struct AddRHS {
1775 Value *RHS;
1776 AddRHS(Value *rhs) : RHS(rhs) {}
1777 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1778 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001779 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001780 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001781 }
1782};
1783
1784// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1785// iff C1&C2 == 0
1786struct AddMaskingAnd {
1787 Constant *C2;
1788 AddMaskingAnd(Constant *c) : C2(c) {}
1789 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001790 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001791 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001792 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001793 }
1794 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001795 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001796 }
1797};
1798
Chris Lattner6e7ba452005-01-01 16:22:27 +00001799static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001800 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001801 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001802 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001803 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001804
Reid Spencer3da59db2006-11-27 01:05:10 +00001805 return IC->InsertNewInstBefore(CastInst::create(
1806 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001807 }
1808
Chris Lattner2eefe512004-04-09 19:05:30 +00001809 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001810 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1811 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001812
Chris Lattner2eefe512004-04-09 19:05:30 +00001813 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1814 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001815 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1816 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001817 }
1818
1819 Value *Op0 = SO, *Op1 = ConstOperand;
1820 if (!ConstIsRHS)
1821 std::swap(Op0, Op1);
1822 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001823 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1824 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001825 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1826 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1827 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001828 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001829 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001830 abort();
1831 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001832 return IC->InsertNewInstBefore(New, I);
1833}
1834
1835// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1836// constant as the other operand, try to fold the binary operator into the
1837// select arguments. This also works for Cast instructions, which obviously do
1838// not have a second operand.
1839static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1840 InstCombiner *IC) {
1841 // Don't modify shared select instructions
1842 if (!SI->hasOneUse()) return 0;
1843 Value *TV = SI->getOperand(1);
1844 Value *FV = SI->getOperand(2);
1845
1846 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001847 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001848 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001849
Chris Lattner6e7ba452005-01-01 16:22:27 +00001850 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1851 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1852
1853 return new SelectInst(SI->getCondition(), SelectTrueVal,
1854 SelectFalseVal);
1855 }
1856 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001857}
1858
Chris Lattner4e998b22004-09-29 05:07:12 +00001859
1860/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1861/// node as operand #0, see if we can fold the instruction into the PHI (which
1862/// is only possible if all operands to the PHI are constants).
1863Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1864 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001865 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001866 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001867
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001868 // Check to see if all of the operands of the PHI are constants. If there is
1869 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001870 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001871 BasicBlock *NonConstBB = 0;
1872 for (unsigned i = 0; i != NumPHIValues; ++i)
1873 if (!isa<Constant>(PN->getIncomingValue(i))) {
1874 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001875 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001876 NonConstBB = PN->getIncomingBlock(i);
1877
1878 // If the incoming non-constant value is in I's block, we have an infinite
1879 // loop.
1880 if (NonConstBB == I.getParent())
1881 return 0;
1882 }
1883
1884 // If there is exactly one non-constant value, we can insert a copy of the
1885 // operation in that block. However, if this is a critical edge, we would be
1886 // inserting the computation one some other paths (e.g. inside a loop). Only
1887 // do this if the pred block is unconditionally branching into the phi block.
1888 if (NonConstBB) {
1889 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1890 if (!BI || !BI->isUnconditional()) return 0;
1891 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001892
1893 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001894 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001895 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001896 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001897 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001898
1899 // Next, add all of the operands to the PHI.
1900 if (I.getNumOperands() == 2) {
1901 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001902 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001903 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001904 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001905 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1906 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1907 else
1908 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001909 } else {
1910 assert(PN->getIncomingBlock(i) == NonConstBB);
1911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1912 InV = BinaryOperator::create(BO->getOpcode(),
1913 PN->getIncomingValue(i), C, "phitmp",
1914 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001915 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1916 InV = CmpInst::create(CI->getOpcode(),
1917 CI->getPredicate(),
1918 PN->getIncomingValue(i), C, "phitmp",
1919 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001920 else
1921 assert(0 && "Unknown binop!");
1922
Chris Lattnerdbab3862007-03-02 21:28:56 +00001923 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001924 }
1925 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001926 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001927 } else {
1928 CastInst *CI = cast<CastInst>(&I);
1929 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001930 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001931 Value *InV;
1932 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001933 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001934 } else {
1935 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001936 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1937 I.getType(), "phitmp",
1938 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001939 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001940 }
1941 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001942 }
1943 }
1944 return ReplaceInstUsesWith(I, NewPN);
1945}
1946
Chris Lattner2454a2e2008-01-29 06:52:45 +00001947
1948/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1949/// value is never equal to -0.0.
1950///
1951/// Note that this function will need to be revisited when we support nondefault
1952/// rounding modes!
1953///
1954static bool CannotBeNegativeZero(const Value *V) {
1955 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1956 return !CFP->getValueAPF().isNegZero();
1957
1958 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1959 if (const Instruction *I = dyn_cast<Instruction>(V)) {
1960 if (I->getOpcode() == Instruction::Add &&
1961 isa<ConstantFP>(I->getOperand(1)) &&
1962 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1963 return true;
1964
1965 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1966 if (II->getIntrinsicID() == Intrinsic::sqrt)
1967 return CannotBeNegativeZero(II->getOperand(1));
1968
1969 if (const CallInst *CI = dyn_cast<CallInst>(I))
1970 if (const Function *F = CI->getCalledFunction()) {
1971 if (F->isDeclaration()) {
1972 switch (F->getNameLen()) {
1973 case 3: // abs(x) != -0.0
1974 if (!strcmp(F->getNameStart(), "abs")) return true;
1975 break;
1976 case 4: // abs[lf](x) != -0.0
1977 if (!strcmp(F->getNameStart(), "absf")) return true;
1978 if (!strcmp(F->getNameStart(), "absl")) return true;
1979 break;
1980 }
1981 }
1982 }
1983 }
1984
1985 return false;
1986}
1987
1988
Chris Lattner7e708292002-06-25 16:13:24 +00001989Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001990 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001991 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001992
Chris Lattner66331a42004-04-10 22:01:55 +00001993 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001994 // X + undef -> undef
1995 if (isa<UndefValue>(RHS))
1996 return ReplaceInstUsesWith(I, RHS);
1997
Chris Lattner66331a42004-04-10 22:01:55 +00001998 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001999 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002000 if (RHSC->isNullValue())
2001 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002002 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002003 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2004 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002005 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002006 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002007
Chris Lattner66331a42004-04-10 22:01:55 +00002008 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002009 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002010 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002011 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002012 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002013 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002014
2015 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2016 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002017 if (!isa<VectorType>(I.getType())) {
2018 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2019 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2020 KnownZero, KnownOne))
2021 return &I;
2022 }
Chris Lattner66331a42004-04-10 22:01:55 +00002023 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002024
2025 if (isa<PHINode>(LHS))
2026 if (Instruction *NV = FoldOpIntoPhi(I))
2027 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002028
Chris Lattner4f637d42006-01-06 17:59:59 +00002029 ConstantInt *XorRHS = 0;
2030 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002031 if (isa<ConstantInt>(RHSC) &&
2032 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002033 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002034 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002035
Zhou Sheng4351c642007-04-02 08:20:41 +00002036 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002037 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2038 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002039 do {
2040 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002041 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2042 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002043 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2044 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002045 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002046 if (!MaskedValueIsZero(XorLHS,
2047 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002048 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002049 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002050 }
2051 }
2052 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002053 C0080Val = APIntOps::lshr(C0080Val, Size);
2054 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2055 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002056
Reid Spencer35c38852007-03-28 01:36:16 +00002057 // FIXME: This shouldn't be necessary. When the backends can handle types
2058 // with funny bit widths then this whole cascade of if statements should
2059 // be removed. It is just here to get the size of the "middle" type back
2060 // up to something that the back ends can handle.
2061 const Type *MiddleType = 0;
2062 switch (Size) {
2063 default: break;
2064 case 32: MiddleType = Type::Int32Ty; break;
2065 case 16: MiddleType = Type::Int16Ty; break;
2066 case 8: MiddleType = Type::Int8Ty; break;
2067 }
2068 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002069 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002070 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002071 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002072 }
2073 }
Chris Lattner66331a42004-04-10 22:01:55 +00002074 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002075
Chris Lattner564a7272003-08-13 19:01:45 +00002076 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002077 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002078 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002079
2080 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2081 if (RHSI->getOpcode() == Instruction::Sub)
2082 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2083 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2084 }
2085 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2086 if (LHSI->getOpcode() == Instruction::Sub)
2087 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2088 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2089 }
Robert Bocchino71698282004-07-27 21:02:21 +00002090 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002091
Chris Lattner5c4afb92002-05-08 22:46:53 +00002092 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00002093 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002094 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002095
2096 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002097 if (!isa<Constant>(RHS))
2098 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002099 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002100
Misha Brukmanfd939082005-04-21 23:48:37 +00002101
Chris Lattner50af16a2004-11-13 19:50:12 +00002102 ConstantInt *C2;
2103 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2104 if (X == RHS) // X*C + X --> X * (C+1)
2105 return BinaryOperator::createMul(RHS, AddOne(C2));
2106
2107 // X*C1 + X*C2 --> X * (C1+C2)
2108 ConstantInt *C1;
2109 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002110 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002111 }
2112
2113 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002114 if (dyn_castFoldableMul(RHS, C2) == LHS)
2115 return BinaryOperator::createMul(LHS, AddOne(C2));
2116
Chris Lattnere617c9e2007-01-05 02:17:46 +00002117 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002118 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2119 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002120
Chris Lattnerad3448c2003-02-18 19:57:07 +00002121
Chris Lattner564a7272003-08-13 19:01:45 +00002122 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002123 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002124 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2125 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002126
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002127 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002128 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002129 Value *W, *X, *Y, *Z;
2130 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2131 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2132 if (W != Y) {
2133 if (W == Z) {
2134 std::swap(Y, Z);
2135 } else if (Y == X) {
2136 std::swap(W, X);
2137 } else if (X == Z) {
2138 std::swap(Y, Z);
2139 std::swap(W, X);
2140 }
2141 }
2142
2143 if (W == Y) {
2144 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2145 LHS->getName()), I);
2146 return BinaryOperator::createMul(W, NewAdd);
2147 }
2148 }
2149 }
2150
Chris Lattner6b032052003-10-02 15:11:26 +00002151 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002152 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002153 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2154 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002155
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002156 // (X & FF00) + xx00 -> (X+xx00) & FF00
2157 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002158 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002159 if (Anded == CRHS) {
2160 // See if all bits from the first bit set in the Add RHS up are included
2161 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002162 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002163
2164 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002165 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002166
2167 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002168 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002169
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002170 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2171 // Okay, the xform is safe. Insert the new add pronto.
2172 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2173 LHS->getName()), I);
2174 return BinaryOperator::createAnd(NewAdd, C2);
2175 }
2176 }
2177 }
2178
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002179 // Try to fold constant add into select arguments.
2180 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002181 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002182 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002183 }
2184
Reid Spencer1628cec2006-10-26 06:15:43 +00002185 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002186 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002187 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002188 CastInst *CI = dyn_cast<CastInst>(LHS);
2189 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002190 if (!CI) {
2191 CI = dyn_cast<CastInst>(RHS);
2192 Other = LHS;
2193 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002194 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002195 (CI->getType()->getPrimitiveSizeInBits() ==
2196 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002197 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002198 unsigned AS =
2199 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002200 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2201 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002202 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002203 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002204 }
2205 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002206
Chris Lattner42790482007-12-20 01:56:58 +00002207 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002208 {
2209 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2210 Value *Other = RHS;
2211 if (!SI) {
2212 SI = dyn_cast<SelectInst>(RHS);
2213 Other = LHS;
2214 }
Chris Lattner42790482007-12-20 01:56:58 +00002215 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002216 Value *TV = SI->getTrueValue();
2217 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002218 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002219
2220 // Can we fold the add into the argument of the select?
2221 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002222 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2223 A == Other) // Fold the add into the true select value.
2224 return new SelectInst(SI->getCondition(), N, A);
2225 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2226 A == Other) // Fold the add into the false select value.
2227 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002228 }
2229 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002230
2231 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2232 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2233 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2234 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002235
Chris Lattner7e708292002-06-25 16:13:24 +00002236 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002237}
2238
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002239// isSignBit - Return true if the value represented by the constant only has the
2240// highest order bit set.
2241static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002242 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002243 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002244}
2245
Chris Lattner7e708292002-06-25 16:13:24 +00002246Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002247 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002248
Chris Lattner233f7dc2002-08-12 21:17:25 +00002249 if (Op0 == Op1) // sub X, X -> 0
2250 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002251
Chris Lattner233f7dc2002-08-12 21:17:25 +00002252 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002253 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002254 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002255
Chris Lattnere87597f2004-10-16 18:11:37 +00002256 if (isa<UndefValue>(Op0))
2257 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2258 if (isa<UndefValue>(Op1))
2259 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2260
Chris Lattnerd65460f2003-11-05 01:06:05 +00002261 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2262 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002263 if (C->isAllOnesValue())
2264 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002265
Chris Lattnerd65460f2003-11-05 01:06:05 +00002266 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002267 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002268 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002269 return BinaryOperator::createAdd(X, AddOne(C));
2270
Chris Lattner76b7a062007-01-15 07:02:54 +00002271 // -(X >>u 31) -> (X >>s 31)
2272 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002273 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002274 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002275 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002276 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002277 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002278 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002279 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002280 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002281 return BinaryOperator::create(Instruction::AShr,
2282 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002283 }
2284 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002285 }
2286 else if (SI->getOpcode() == Instruction::AShr) {
2287 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2288 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002289 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002290 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002291 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002292 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002293 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002294 }
2295 }
2296 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002297 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002298
2299 // Try to fold constant sub into select arguments.
2300 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002301 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002302 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002303
2304 if (isa<PHINode>(Op0))
2305 if (Instruction *NV = FoldOpIntoPhi(I))
2306 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002307 }
2308
Chris Lattner43d84d62005-04-07 16:15:25 +00002309 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2310 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002311 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002312 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002313 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002314 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002315 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002316 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2317 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2318 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002319 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002320 Op1I->getOperand(0));
2321 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002322 }
2323
Chris Lattnerfd059242003-10-15 16:48:29 +00002324 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002325 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2326 // is not used by anyone else...
2327 //
Chris Lattner0517e722004-02-02 20:09:56 +00002328 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002329 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002330 // Swap the two operands of the subexpr...
2331 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2332 Op1I->setOperand(0, IIOp1);
2333 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002334
Chris Lattnera2881962003-02-18 19:28:33 +00002335 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002336 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002337 }
2338
2339 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2340 //
2341 if (Op1I->getOpcode() == Instruction::And &&
2342 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2343 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2344
Chris Lattnerf523d062004-06-09 05:08:07 +00002345 Value *NewNot =
2346 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002347 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002348 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002349
Reid Spencerac5209e2006-10-16 23:08:08 +00002350 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002351 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002352 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002353 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002354 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002355 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002356 ConstantExpr::getNeg(DivRHS));
2357
Chris Lattnerad3448c2003-02-18 19:57:07 +00002358 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002359 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002360 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002361 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002362 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002363 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002364
2365 // X - ((X / Y) * Y) --> X % Y
2366 if (Op1I->getOpcode() == Instruction::Mul)
2367 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2368 if (Op0 == I->getOperand(0) &&
2369 Op1I->getOperand(1) == I->getOperand(1)) {
2370 if (I->getOpcode() == Instruction::SDiv)
2371 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2372 if (I->getOpcode() == Instruction::UDiv)
2373 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2374 }
Chris Lattner40371712002-05-09 01:29:19 +00002375 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002376 }
Chris Lattnera2881962003-02-18 19:28:33 +00002377
Chris Lattner9919e3d2006-12-02 00:13:08 +00002378 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002379 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2380 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002381 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2382 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2383 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2384 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002385 } else if (Op0I->getOpcode() == Instruction::Sub) {
2386 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2387 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002388 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002389
Chris Lattner50af16a2004-11-13 19:50:12 +00002390 ConstantInt *C1;
2391 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002392 if (X == Op1) // X*C - X --> X * (C-1)
2393 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002394
Chris Lattner50af16a2004-11-13 19:50:12 +00002395 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2396 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002397 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002398 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002399 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002400}
2401
Chris Lattnera0141b92007-07-15 20:42:37 +00002402/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2403/// comparison only checks the sign bit. If it only checks the sign bit, set
2404/// TrueIfSigned if the result of the comparison is true when the input value is
2405/// signed.
2406static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2407 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002408 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002409 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2410 TrueIfSigned = true;
2411 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002412 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2413 TrueIfSigned = true;
2414 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002415 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2416 TrueIfSigned = false;
2417 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002418 case ICmpInst::ICMP_UGT:
2419 // True if LHS u> RHS and RHS == high-bit-mask - 1
2420 TrueIfSigned = true;
2421 return RHS->getValue() ==
2422 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2423 case ICmpInst::ICMP_UGE:
2424 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2425 TrueIfSigned = true;
2426 return RHS->getValue() ==
2427 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002428 default:
2429 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002430 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002431}
2432
Chris Lattner7e708292002-06-25 16:13:24 +00002433Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002434 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002435 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002436
Chris Lattnere87597f2004-10-16 18:11:37 +00002437 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2438 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2439
Chris Lattner233f7dc2002-08-12 21:17:25 +00002440 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002441 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2442 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002443
2444 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002445 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002446 if (SI->getOpcode() == Instruction::Shl)
2447 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002448 return BinaryOperator::createMul(SI->getOperand(0),
2449 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002450
Zhou Sheng843f07672007-04-19 05:39:12 +00002451 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002452 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2453 if (CI->equalsInt(1)) // X * 1 == X
2454 return ReplaceInstUsesWith(I, Op0);
2455 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002456 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002457
Zhou Sheng97b52c22007-03-29 01:57:21 +00002458 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002459 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002460 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002461 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002462 }
Robert Bocchino71698282004-07-27 21:02:21 +00002463 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002464 if (Op1F->isNullValue())
2465 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002466
Chris Lattnera2881962003-02-18 19:28:33 +00002467 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2468 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002469 // We need a better interface for long double here.
2470 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2471 if (Op1F->isExactlyValue(1.0))
2472 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002473 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002474
2475 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2476 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2477 isa<ConstantInt>(Op0I->getOperand(1))) {
2478 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2479 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2480 Op1, "tmp");
2481 InsertNewInstBefore(Add, I);
2482 Value *C1C2 = ConstantExpr::getMul(Op1,
2483 cast<Constant>(Op0I->getOperand(1)));
2484 return BinaryOperator::createAdd(Add, C1C2);
2485
2486 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002487
2488 // Try to fold constant mul into select arguments.
2489 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002490 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002491 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002492
2493 if (isa<PHINode>(Op0))
2494 if (Instruction *NV = FoldOpIntoPhi(I))
2495 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002496 }
2497
Chris Lattnera4f445b2003-03-10 23:23:04 +00002498 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2499 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002500 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002501
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002502 // If one of the operands of the multiply is a cast from a boolean value, then
2503 // we know the bool is either zero or one, so this is a 'masking' multiply.
2504 // See if we can simplify things based on how the boolean was originally
2505 // formed.
2506 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002507 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002508 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002509 BoolCast = CI;
2510 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002511 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002512 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002513 BoolCast = CI;
2514 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002515 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002516 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2517 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002518 bool TIS = false;
2519
Reid Spencere4d87aa2006-12-23 06:05:41 +00002520 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002521 // multiply into a shift/and combination.
2522 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002523 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2524 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002525 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002526 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002527 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002528 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002529 InsertNewInstBefore(
2530 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002531 BoolCast->getOperand(0)->getName()+
2532 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002533
2534 // If the multiply type is not the same as the source type, sign extend
2535 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002536 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002537 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2538 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002539 Instruction::CastOps opcode =
2540 (SrcBits == DstBits ? Instruction::BitCast :
2541 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2542 V = InsertCastBefore(opcode, V, I.getType(), I);
2543 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002544
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002545 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002546 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002547 }
2548 }
2549 }
2550
Chris Lattner7e708292002-06-25 16:13:24 +00002551 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002552}
2553
Reid Spencer1628cec2006-10-26 06:15:43 +00002554/// This function implements the transforms on div instructions that work
2555/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2556/// used by the visitors to those instructions.
2557/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002558Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002559 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002560
Reid Spencer1628cec2006-10-26 06:15:43 +00002561 // undef / X -> 0
2562 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002563 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002564
2565 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002566 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002567 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002568
Chris Lattner25feae52008-01-28 00:58:18 +00002569 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2570 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002571 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002572 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2573 // the same basic block, then we replace the select with Y, and the
2574 // condition of the select with false (if the cond value is in the same BB).
2575 // If the select has uses other than the div, this allows them to be
2576 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2577 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002578 if (ST->isNullValue()) {
2579 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2580 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002581 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002582 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2583 I.setOperand(1, SI->getOperand(2));
2584 else
2585 UpdateValueUsesWith(SI, SI->getOperand(2));
2586 return &I;
2587 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002588
Chris Lattner25feae52008-01-28 00:58:18 +00002589 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2590 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002591 if (ST->isNullValue()) {
2592 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2593 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002594 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002595 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2596 I.setOperand(1, SI->getOperand(1));
2597 else
2598 UpdateValueUsesWith(SI, SI->getOperand(1));
2599 return &I;
2600 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002601 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002602
Reid Spencer1628cec2006-10-26 06:15:43 +00002603 return 0;
2604}
Misha Brukmanfd939082005-04-21 23:48:37 +00002605
Reid Spencer1628cec2006-10-26 06:15:43 +00002606/// This function implements the transforms common to both integer division
2607/// instructions (udiv and sdiv). It is called by the visitors to those integer
2608/// division instructions.
2609/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002610Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002611 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2612
2613 if (Instruction *Common = commonDivTransforms(I))
2614 return Common;
2615
2616 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2617 // div X, 1 == X
2618 if (RHS->equalsInt(1))
2619 return ReplaceInstUsesWith(I, Op0);
2620
2621 // (X / C1) / C2 -> X / (C1*C2)
2622 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2623 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2624 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2625 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002626 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002627 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002628
Reid Spencerbca0e382007-03-23 20:05:17 +00002629 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002630 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2631 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2632 return R;
2633 if (isa<PHINode>(Op0))
2634 if (Instruction *NV = FoldOpIntoPhi(I))
2635 return NV;
2636 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002637 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002638
Chris Lattnera2881962003-02-18 19:28:33 +00002639 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002640 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002641 if (LHS->equalsInt(0))
2642 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2643
Reid Spencer1628cec2006-10-26 06:15:43 +00002644 return 0;
2645}
2646
2647Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650 // Handle the integer div common cases
2651 if (Instruction *Common = commonIDivTransforms(I))
2652 return Common;
2653
2654 // X udiv C^2 -> X >> C
2655 // Check to see if this is an unsigned division with an exact power of 2,
2656 // if so, convert to a right shift.
2657 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002658 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002659 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002660 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002661 }
2662
2663 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002664 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002665 if (RHSI->getOpcode() == Instruction::Shl &&
2666 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002667 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002668 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002669 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002670 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002671 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002672 Constant *C2V = ConstantInt::get(NTy, C2);
2673 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002674 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002675 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002676 }
2677 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002678 }
2679
Reid Spencer1628cec2006-10-26 06:15:43 +00002680 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2681 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002682 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002683 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002684 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002685 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002686 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002687 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002688 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002689 // Construct the "on true" case of the select
2690 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2691 Instruction *TSI = BinaryOperator::createLShr(
2692 Op0, TC, SI->getName()+".t");
2693 TSI = InsertNewInstBefore(TSI, I);
2694
2695 // Construct the "on false" case of the select
2696 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2697 Instruction *FSI = BinaryOperator::createLShr(
2698 Op0, FC, SI->getName()+".f");
2699 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002700
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002701 // construct the select instruction and return it.
2702 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002703 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002704 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002705 return 0;
2706}
2707
Reid Spencer1628cec2006-10-26 06:15:43 +00002708Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2709 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2710
2711 // Handle the integer div common cases
2712 if (Instruction *Common = commonIDivTransforms(I))
2713 return Common;
2714
2715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2716 // sdiv X, -1 == -X
2717 if (RHS->isAllOnesValue())
2718 return BinaryOperator::createNeg(Op0);
2719
2720 // -X/C -> X/-C
2721 if (Value *LHSNeg = dyn_castNegVal(Op0))
2722 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2723 }
2724
2725 // If the sign bits of both operands are zero (i.e. we can prove they are
2726 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002727 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002728 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002729 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002730 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002731 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2732 }
2733 }
2734
2735 return 0;
2736}
2737
2738Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2739 return commonDivTransforms(I);
2740}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002741
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002742/// GetFactor - If we can prove that the specified value is at least a multiple
2743/// of some factor, return that factor.
2744static Constant *GetFactor(Value *V) {
2745 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2746 return CI;
2747
2748 // Unless we can be tricky, we know this is a multiple of 1.
2749 Constant *Result = ConstantInt::get(V->getType(), 1);
2750
2751 Instruction *I = dyn_cast<Instruction>(V);
2752 if (!I) return Result;
2753
2754 if (I->getOpcode() == Instruction::Mul) {
2755 // Handle multiplies by a constant, etc.
2756 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2757 GetFactor(I->getOperand(1)));
2758 } else if (I->getOpcode() == Instruction::Shl) {
2759 // (X<<C) -> X * (1 << C)
2760 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2761 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2762 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2763 }
2764 } else if (I->getOpcode() == Instruction::And) {
2765 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2766 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002767 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner148083a2007-11-23 22:35:18 +00002768 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002769 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002770 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002771 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002772 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002773 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002774 if (!CI->isIntegerCast())
2775 return Result;
2776 Value *Op = CI->getOperand(0);
2777 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002778 }
2779 return Result;
2780}
2781
Reid Spencer0a783f72006-11-02 01:53:59 +00002782/// This function implements the transforms on rem instructions that work
2783/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2784/// is used by the visitors to those instructions.
2785/// @brief Transforms common to all three rem instructions
2786Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002787 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002788
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002789 // 0 % X == 0, we don't need to preserve faults!
2790 if (Constant *LHS = dyn_cast<Constant>(Op0))
2791 if (LHS->isNullValue())
2792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2793
2794 if (isa<UndefValue>(Op0)) // undef % X -> 0
2795 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2796 if (isa<UndefValue>(Op1))
2797 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002798
2799 // Handle cases involving: rem X, (select Cond, Y, Z)
2800 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2801 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2802 // the same basic block, then we replace the select with Y, and the
2803 // condition of the select with false (if the cond value is in the same
2804 // BB). If the select has uses other than the div, this allows them to be
2805 // simplified also.
2806 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2807 if (ST->isNullValue()) {
2808 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2809 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002810 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002811 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2812 I.setOperand(1, SI->getOperand(2));
2813 else
2814 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002815 return &I;
2816 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002817 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2818 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2819 if (ST->isNullValue()) {
2820 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2821 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002822 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002823 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2824 I.setOperand(1, SI->getOperand(1));
2825 else
2826 UpdateValueUsesWith(SI, SI->getOperand(1));
2827 return &I;
2828 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002829 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002830
Reid Spencer0a783f72006-11-02 01:53:59 +00002831 return 0;
2832}
2833
2834/// This function implements the transforms common to both integer remainder
2835/// instructions (urem and srem). It is called by the visitors to those integer
2836/// remainder instructions.
2837/// @brief Common integer remainder transforms
2838Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2839 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2840
2841 if (Instruction *common = commonRemTransforms(I))
2842 return common;
2843
Chris Lattner857e8cd2004-12-12 21:48:58 +00002844 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002845 // X % 0 == undef, we don't need to preserve faults!
2846 if (RHS->equalsInt(0))
2847 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2848
Chris Lattnera2881962003-02-18 19:28:33 +00002849 if (RHS->equalsInt(1)) // X % 1 == 0
2850 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2851
Chris Lattner97943922006-02-28 05:49:21 +00002852 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2853 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2854 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2855 return R;
2856 } else if (isa<PHINode>(Op0I)) {
2857 if (Instruction *NV = FoldOpIntoPhi(I))
2858 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002859 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002860 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2861 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002862 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002863 }
Chris Lattnera2881962003-02-18 19:28:33 +00002864 }
2865
Reid Spencer0a783f72006-11-02 01:53:59 +00002866 return 0;
2867}
2868
2869Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2870 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2871
2872 if (Instruction *common = commonIRemTransforms(I))
2873 return common;
2874
2875 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2876 // X urem C^2 -> X and C
2877 // Check to see if this is an unsigned remainder with an exact power of 2,
2878 // if so, convert to a bitwise and.
2879 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002880 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002881 return BinaryOperator::createAnd(Op0, SubOne(C));
2882 }
2883
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002884 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002885 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2886 if (RHSI->getOpcode() == Instruction::Shl &&
2887 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002888 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002889 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2890 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2891 "tmp"), I);
2892 return BinaryOperator::createAnd(Op0, Add);
2893 }
2894 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002895 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002896
Reid Spencer0a783f72006-11-02 01:53:59 +00002897 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2898 // where C1&C2 are powers of two.
2899 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2900 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2901 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2902 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002903 if ((STO->getValue().isPowerOf2()) &&
2904 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002905 Value *TrueAnd = InsertNewInstBefore(
2906 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2907 Value *FalseAnd = InsertNewInstBefore(
2908 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2909 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2910 }
2911 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002912 }
2913
Chris Lattner3f5b8772002-05-06 16:14:14 +00002914 return 0;
2915}
2916
Reid Spencer0a783f72006-11-02 01:53:59 +00002917Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2918 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2919
Dan Gohmancff55092007-11-05 23:16:33 +00002920 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002921 if (Instruction *common = commonIRemTransforms(I))
2922 return common;
2923
2924 if (Value *RHSNeg = dyn_castNegVal(Op1))
2925 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002926 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002927 // X % -Y -> X % Y
2928 AddUsesToWorkList(I);
2929 I.setOperand(1, RHSNeg);
2930 return &I;
2931 }
2932
Dan Gohmancff55092007-11-05 23:16:33 +00002933 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002934 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002935 if (I.getType()->isInteger()) {
2936 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2937 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2938 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2939 return BinaryOperator::createURem(Op0, Op1, I.getName());
2940 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002941 }
2942
2943 return 0;
2944}
2945
2946Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002947 return commonRemTransforms(I);
2948}
2949
Chris Lattner8b170942002-08-09 23:47:40 +00002950// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002951static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002952 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002953 if (!isSigned)
2954 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2955 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002956}
2957
2958// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002959static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002960 if (!isSigned)
2961 return C->getValue() == 1; // unsigned
2962
2963 // Calculate 1111111111000000000000
2964 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2965 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002966}
2967
Chris Lattner457dd822004-06-09 07:59:58 +00002968// isOneBitSet - Return true if there is exactly one bit set in the specified
2969// constant.
2970static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002971 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002972}
2973
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002974// isHighOnes - Return true if the constant is of the form 1+0+.
2975// This is the same as lowones(~X).
2976static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002977 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002978}
2979
Reid Spencere4d87aa2006-12-23 06:05:41 +00002980/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002981/// are carefully arranged to allow folding of expressions such as:
2982///
2983/// (A < B) | (A > B) --> (A != B)
2984///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002985/// Note that this is only valid if the first and second predicates have the
2986/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002987///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002988/// Three bits are used to represent the condition, as follows:
2989/// 0 A > B
2990/// 1 A == B
2991/// 2 A < B
2992///
2993/// <=> Value Definition
2994/// 000 0 Always false
2995/// 001 1 A > B
2996/// 010 2 A == B
2997/// 011 3 A >= B
2998/// 100 4 A < B
2999/// 101 5 A != B
3000/// 110 6 A <= B
3001/// 111 7 Always true
3002///
3003static unsigned getICmpCode(const ICmpInst *ICI) {
3004 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003005 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003006 case ICmpInst::ICMP_UGT: return 1; // 001
3007 case ICmpInst::ICMP_SGT: return 1; // 001
3008 case ICmpInst::ICMP_EQ: return 2; // 010
3009 case ICmpInst::ICMP_UGE: return 3; // 011
3010 case ICmpInst::ICMP_SGE: return 3; // 011
3011 case ICmpInst::ICMP_ULT: return 4; // 100
3012 case ICmpInst::ICMP_SLT: return 4; // 100
3013 case ICmpInst::ICMP_NE: return 5; // 101
3014 case ICmpInst::ICMP_ULE: return 6; // 110
3015 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003016 // True -> 7
3017 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003019 return 0;
3020 }
3021}
3022
Reid Spencere4d87aa2006-12-23 06:05:41 +00003023/// getICmpValue - This is the complement of getICmpCode, which turns an
3024/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003025/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003026/// of predicate to use in new icmp instructions.
3027static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3028 switch (code) {
3029 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003030 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003031 case 1:
3032 if (sign)
3033 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3034 else
3035 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3036 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3037 case 3:
3038 if (sign)
3039 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3040 else
3041 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3042 case 4:
3043 if (sign)
3044 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3045 else
3046 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3047 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3048 case 6:
3049 if (sign)
3050 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3051 else
3052 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003053 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003054 }
3055}
3056
Reid Spencere4d87aa2006-12-23 06:05:41 +00003057static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3058 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3059 (ICmpInst::isSignedPredicate(p1) &&
3060 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3061 (ICmpInst::isSignedPredicate(p2) &&
3062 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3063}
3064
3065namespace {
3066// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3067struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003068 InstCombiner &IC;
3069 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003070 ICmpInst::Predicate pred;
3071 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3072 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3073 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003074 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003075 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3076 if (PredicatesFoldable(pred, ICI->getPredicate()))
3077 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3078 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003079 return false;
3080 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003081 Instruction *apply(Instruction &Log) const {
3082 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3083 if (ICI->getOperand(0) != LHS) {
3084 assert(ICI->getOperand(1) == LHS);
3085 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003086 }
3087
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003088 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003089 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003090 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003091 unsigned Code;
3092 switch (Log.getOpcode()) {
3093 case Instruction::And: Code = LHSCode & RHSCode; break;
3094 case Instruction::Or: Code = LHSCode | RHSCode; break;
3095 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003096 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003097 }
3098
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003099 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3100 ICmpInst::isSignedPredicate(ICI->getPredicate());
3101
3102 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003103 if (Instruction *I = dyn_cast<Instruction>(RV))
3104 return I;
3105 // Otherwise, it's a constant boolean value...
3106 return IC.ReplaceInstUsesWith(Log, RV);
3107 }
3108};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003109} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003110
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003111// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3112// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003113// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003114Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003115 ConstantInt *OpRHS,
3116 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003117 BinaryOperator &TheAnd) {
3118 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003119 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003120 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003121 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003122
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003123 switch (Op->getOpcode()) {
3124 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003125 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003126 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003127 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003128 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003129 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003130 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003131 }
3132 break;
3133 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003134 if (Together == AndRHS) // (X | C) & C --> C
3135 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003136
Chris Lattner6e7ba452005-01-01 16:22:27 +00003137 if (Op->hasOneUse() && Together != OpRHS) {
3138 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003139 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003140 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003141 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003142 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003143 }
3144 break;
3145 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003146 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003147 // Adding a one to a single bit bit-field should be turned into an XOR
3148 // of the bit. First thing to check is to see if this AND is with a
3149 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003150 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003151
3152 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003153 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003154 // Ok, at this point, we know that we are masking the result of the
3155 // ADD down to exactly one bit. If the constant we are adding has
3156 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003157 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003158
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003159 // Check to see if any bits below the one bit set in AndRHSV are set.
3160 if ((AddRHS & (AndRHSV-1)) == 0) {
3161 // If not, the only thing that can effect the output of the AND is
3162 // the bit specified by AndRHSV. If that bit is set, the effect of
3163 // the XOR is to toggle the bit. If it is clear, then the ADD has
3164 // no effect.
3165 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3166 TheAnd.setOperand(0, X);
3167 return &TheAnd;
3168 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003169 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003170 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003171 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003172 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003173 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003174 }
3175 }
3176 }
3177 }
3178 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003179
3180 case Instruction::Shl: {
3181 // We know that the AND will not produce any of the bits shifted in, so if
3182 // the anded constant includes them, clear them now!
3183 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003184 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003185 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003186 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3187 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003188
Zhou Sheng290bec52007-03-29 08:15:12 +00003189 if (CI->getValue() == ShlMask) {
3190 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003191 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3192 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003193 TheAnd.setOperand(1, CI);
3194 return &TheAnd;
3195 }
3196 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003197 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003198 case Instruction::LShr:
3199 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003200 // We know that the AND will not produce any of the bits shifted in, so if
3201 // the anded constant includes them, clear them now! This only applies to
3202 // unsigned shifts, because a signed shr may bring in set bits!
3203 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003204 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003205 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003206 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3207 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003208
Zhou Sheng290bec52007-03-29 08:15:12 +00003209 if (CI->getValue() == ShrMask) {
3210 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003211 return ReplaceInstUsesWith(TheAnd, Op);
3212 } else if (CI != AndRHS) {
3213 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3214 return &TheAnd;
3215 }
3216 break;
3217 }
3218 case Instruction::AShr:
3219 // Signed shr.
3220 // See if this is shifting in some sign extension, then masking it out
3221 // with an and.
3222 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003223 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003224 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003225 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3226 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003227 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003228 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003229 // Make the argument unsigned.
3230 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003231 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003232 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003233 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003234 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003235 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003236 }
3237 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003238 }
3239 return 0;
3240}
3241
Chris Lattner8b170942002-08-09 23:47:40 +00003242
Chris Lattnera96879a2004-09-29 17:40:11 +00003243/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3244/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003245/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3246/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003247/// insert new instructions.
3248Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003249 bool isSigned, bool Inside,
3250 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003251 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003252 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003253 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003254
Chris Lattnera96879a2004-09-29 17:40:11 +00003255 if (Inside) {
3256 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003257 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003258
Reid Spencere4d87aa2006-12-23 06:05:41 +00003259 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003260 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003261 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003262 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3263 return new ICmpInst(pred, V, Hi);
3264 }
3265
3266 // Emit V-Lo <u Hi-Lo
3267 Constant *NegLo = ConstantExpr::getNeg(Lo);
3268 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003269 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003270 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3271 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003272 }
3273
3274 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003275 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003276
Reid Spencere4e40032007-03-21 23:19:50 +00003277 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003278 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003279 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003280 ICmpInst::Predicate pred = (isSigned ?
3281 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3282 return new ICmpInst(pred, V, Hi);
3283 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003284
Reid Spencere4e40032007-03-21 23:19:50 +00003285 // Emit V-Lo >u Hi-1-Lo
3286 // Note that Hi has already had one subtracted from it, above.
3287 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003288 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003289 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003290 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3291 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003292}
3293
Chris Lattner7203e152005-09-18 07:22:02 +00003294// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3295// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3296// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3297// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003298static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003299 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003300 uint32_t BitWidth = Val->getType()->getBitWidth();
3301 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003302
3303 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003304 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003305 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003306 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003307 return true;
3308}
3309
Chris Lattner7203e152005-09-18 07:22:02 +00003310/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3311/// where isSub determines whether the operator is a sub. If we can fold one of
3312/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003313///
3314/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3315/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3316/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3317///
3318/// return (A +/- B).
3319///
3320Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003321 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003322 Instruction &I) {
3323 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3324 if (!LHSI || LHSI->getNumOperands() != 2 ||
3325 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3326
3327 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3328
3329 switch (LHSI->getOpcode()) {
3330 default: return 0;
3331 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003332 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003333 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003334 if ((Mask->getValue().countLeadingZeros() +
3335 Mask->getValue().countPopulation()) ==
3336 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003337 break;
3338
3339 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3340 // part, we don't need any explicit masks to take them out of A. If that
3341 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003342 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003343 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003344 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003345 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003346 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003347 break;
3348 }
3349 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003350 return 0;
3351 case Instruction::Or:
3352 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003353 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003354 if ((Mask->getValue().countLeadingZeros() +
3355 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003356 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003357 break;
3358 return 0;
3359 }
3360
3361 Instruction *New;
3362 if (isSub)
3363 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3364 else
3365 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3366 return InsertNewInstBefore(New, I);
3367}
3368
Chris Lattner7e708292002-06-25 16:13:24 +00003369Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003370 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003372
Chris Lattnere87597f2004-10-16 18:11:37 +00003373 if (isa<UndefValue>(Op1)) // X & undef -> 0
3374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3375
Chris Lattner6e7ba452005-01-01 16:22:27 +00003376 // and X, X = X
3377 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003378 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003379
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003380 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003381 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003382 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003383 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3384 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3385 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003386 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003387 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003388 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003389 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003390 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003391 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003392 } else if (isa<ConstantAggregateZero>(Op1)) {
3393 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003394 }
3395 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003396
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003397 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003398 const APInt& AndRHSMask = AndRHS->getValue();
3399 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003400
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003401 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003402 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003403 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003404 Value *Op0LHS = Op0I->getOperand(0);
3405 Value *Op0RHS = Op0I->getOperand(1);
3406 switch (Op0I->getOpcode()) {
3407 case Instruction::Xor:
3408 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003409 // If the mask is only needed on one incoming arm, push it up.
3410 if (Op0I->hasOneUse()) {
3411 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3412 // Not masking anything out for the LHS, move to RHS.
3413 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3414 Op0RHS->getName()+".masked");
3415 InsertNewInstBefore(NewRHS, I);
3416 return BinaryOperator::create(
3417 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003418 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003419 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003420 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3421 // Not masking anything out for the RHS, move to LHS.
3422 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3423 Op0LHS->getName()+".masked");
3424 InsertNewInstBefore(NewLHS, I);
3425 return BinaryOperator::create(
3426 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3427 }
3428 }
3429
Chris Lattner6e7ba452005-01-01 16:22:27 +00003430 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003431 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003432 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3433 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3434 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3435 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3436 return BinaryOperator::createAnd(V, AndRHS);
3437 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3438 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003439 break;
3440
3441 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003442 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3443 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3444 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3445 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3446 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003447 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003448 }
3449
Chris Lattner58403262003-07-23 19:25:52 +00003450 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003451 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003452 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003453 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003454 // If this is an integer truncation or change from signed-to-unsigned, and
3455 // if the source is an and/or with immediate, transform it. This
3456 // frequently occurs for bitfield accesses.
3457 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003458 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003459 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003460 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003461 if (CastOp->getOpcode() == Instruction::And) {
3462 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003463 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3464 // This will fold the two constants together, which may allow
3465 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003466 Instruction *NewCast = CastInst::createTruncOrBitCast(
3467 CastOp->getOperand(0), I.getType(),
3468 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003469 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003470 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003471 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003472 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003473 return BinaryOperator::createAnd(NewCast, C3);
3474 } else if (CastOp->getOpcode() == Instruction::Or) {
3475 // Change: and (cast (or X, C1) to T), C2
3476 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003477 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003478 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3479 return ReplaceInstUsesWith(I, AndRHS);
3480 }
3481 }
Chris Lattner06782f82003-07-23 19:36:21 +00003482 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003483
3484 // Try to fold constant and into select arguments.
3485 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003486 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003487 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003488 if (isa<PHINode>(Op0))
3489 if (Instruction *NV = FoldOpIntoPhi(I))
3490 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003491 }
3492
Chris Lattner8d969642003-03-10 23:06:50 +00003493 Value *Op0NotVal = dyn_castNotVal(Op0);
3494 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003495
Chris Lattner5b62aa72004-06-18 06:07:51 +00003496 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3497 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3498
Misha Brukmancb6267b2004-07-30 12:50:08 +00003499 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003500 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003501 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3502 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003503 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003504 return BinaryOperator::createNot(Or);
3505 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003506
3507 {
Chris Lattner003b6202007-06-15 05:58:24 +00003508 Value *A = 0, *B = 0, *C = 0, *D = 0;
3509 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003510 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3511 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003512
3513 // (A|B) & ~(A&B) -> A^B
3514 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3515 if ((A == C && B == D) || (A == D && B == C))
3516 return BinaryOperator::createXor(A, B);
3517 }
3518 }
3519
3520 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003521 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3522 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003523
3524 // ~(A&B) & (A|B) -> A^B
3525 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3526 if ((A == C && B == D) || (A == D && B == C))
3527 return BinaryOperator::createXor(A, B);
3528 }
3529 }
Chris Lattner64daab52006-04-01 08:03:55 +00003530
3531 if (Op0->hasOneUse() &&
3532 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3533 if (A == Op1) { // (A^B)&A -> A&(A^B)
3534 I.swapOperands(); // Simplify below
3535 std::swap(Op0, Op1);
3536 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3537 cast<BinaryOperator>(Op0)->swapOperands();
3538 I.swapOperands(); // Simplify below
3539 std::swap(Op0, Op1);
3540 }
3541 }
3542 if (Op1->hasOneUse() &&
3543 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3544 if (B == Op0) { // B&(A^B) -> B&(B^A)
3545 cast<BinaryOperator>(Op1)->swapOperands();
3546 std::swap(A, B);
3547 }
3548 if (A == Op0) { // A&(A^B) -> A & ~B
3549 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3550 InsertNewInstBefore(NotB, I);
3551 return BinaryOperator::createAnd(A, NotB);
3552 }
3553 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003554 }
3555
Reid Spencere4d87aa2006-12-23 06:05:41 +00003556 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3557 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3558 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003559 return R;
3560
Chris Lattner955f3312004-09-28 21:48:02 +00003561 Value *LHSVal, *RHSVal;
3562 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003563 ICmpInst::Predicate LHSCC, RHSCC;
3564 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3565 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3566 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3567 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3568 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3569 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3570 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003571 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3572
3573 // Don't try to fold ICMP_SLT + ICMP_ULT.
3574 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3575 ICmpInst::isSignedPredicate(LHSCC) ==
3576 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003577 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003578 ICmpInst::Predicate GT;
3579 if (ICmpInst::isSignedPredicate(LHSCC) ||
3580 (ICmpInst::isEquality(LHSCC) &&
3581 ICmpInst::isSignedPredicate(RHSCC)))
3582 GT = ICmpInst::ICMP_SGT;
3583 else
3584 GT = ICmpInst::ICMP_UGT;
3585
Reid Spencere4d87aa2006-12-23 06:05:41 +00003586 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3587 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003588 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003589 std::swap(LHS, RHS);
3590 std::swap(LHSCst, RHSCst);
3591 std::swap(LHSCC, RHSCC);
3592 }
3593
Reid Spencere4d87aa2006-12-23 06:05:41 +00003594 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003595 // comparing a value against two constants and and'ing the result
3596 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003597 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3598 // (from the FoldICmpLogical check above), that the two constants
3599 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003600 assert(LHSCst != RHSCst && "Compares not folded above?");
3601
3602 switch (LHSCC) {
3603 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003604 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003605 switch (RHSCC) {
3606 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003607 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3608 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3609 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003610 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003611 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3612 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3613 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003614 return ReplaceInstUsesWith(I, LHS);
3615 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003616 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003617 switch (RHSCC) {
3618 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003619 case ICmpInst::ICMP_ULT:
3620 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3621 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3622 break; // (X != 13 & X u< 15) -> no change
3623 case ICmpInst::ICMP_SLT:
3624 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3625 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3626 break; // (X != 13 & X s< 15) -> no change
3627 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3628 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3629 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003630 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003631 case ICmpInst::ICMP_NE:
3632 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003633 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3634 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3635 LHSVal->getName()+".off");
3636 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003637 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3638 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003639 }
3640 break; // (X != 13 & X != 15) -> no change
3641 }
3642 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003644 switch (RHSCC) {
3645 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3647 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003648 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3650 break;
3651 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3652 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003653 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3655 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003656 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 break;
3658 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003659 switch (RHSCC) {
3660 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3662 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003663 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3665 break;
3666 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3667 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003668 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3670 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003671 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 break;
3673 case ICmpInst::ICMP_UGT:
3674 switch (RHSCC) {
3675 default: assert(0 && "Unknown integer condition code!");
3676 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3677 return ReplaceInstUsesWith(I, LHS);
3678 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3679 return ReplaceInstUsesWith(I, RHS);
3680 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3681 break;
3682 case ICmpInst::ICMP_NE:
3683 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3684 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3685 break; // (X u> 13 & X != 15) -> no change
3686 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3687 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3688 true, I);
3689 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3690 break;
3691 }
3692 break;
3693 case ICmpInst::ICMP_SGT:
3694 switch (RHSCC) {
3695 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003696 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3698 return ReplaceInstUsesWith(I, RHS);
3699 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3700 break;
3701 case ICmpInst::ICMP_NE:
3702 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3703 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3704 break; // (X s> 13 & X != 15) -> no change
3705 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3706 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3707 true, I);
3708 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3709 break;
3710 }
3711 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003712 }
3713 }
3714 }
3715
Chris Lattner6fc205f2006-05-05 06:39:07 +00003716 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003717 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3718 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3719 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3720 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003721 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003722 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003723 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3724 I.getType(), TD) &&
3725 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3726 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003727 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3728 Op1C->getOperand(0),
3729 I.getName());
3730 InsertNewInstBefore(NewOp, I);
3731 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3732 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003733 }
Chris Lattnere511b742006-11-14 07:46:50 +00003734
3735 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003736 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3737 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3738 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003739 SI0->getOperand(1) == SI1->getOperand(1) &&
3740 (SI0->hasOneUse() || SI1->hasOneUse())) {
3741 Instruction *NewOp =
3742 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3743 SI1->getOperand(0),
3744 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003745 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3746 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003747 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003748 }
3749
Chris Lattner99c65742007-10-24 05:38:08 +00003750 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3751 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3752 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3753 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3754 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3755 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3756 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3757 // If either of the constants are nans, then the whole thing returns
3758 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003759 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003760 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3761 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3762 RHS->getOperand(0));
3763 }
3764 }
3765 }
3766
Chris Lattner7e708292002-06-25 16:13:24 +00003767 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003768}
3769
Chris Lattnerafe91a52006-06-15 19:07:26 +00003770/// CollectBSwapParts - Look to see if the specified value defines a single byte
3771/// in the result. If it does, and if the specified byte hasn't been filled in
3772/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003773static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003774 Instruction *I = dyn_cast<Instruction>(V);
3775 if (I == 0) return true;
3776
3777 // If this is an or instruction, it is an inner node of the bswap.
3778 if (I->getOpcode() == Instruction::Or)
3779 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3780 CollectBSwapParts(I->getOperand(1), ByteValues);
3781
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003782 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003783 // If this is a shift by a constant int, and it is "24", then its operand
3784 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003785 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003786 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003787 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003788 8*(ByteValues.size()-1))
3789 return true;
3790
3791 unsigned DestNo;
3792 if (I->getOpcode() == Instruction::Shl) {
3793 // X << 24 defines the top byte with the lowest of the input bytes.
3794 DestNo = ByteValues.size()-1;
3795 } else {
3796 // X >>u 24 defines the low byte with the highest of the input bytes.
3797 DestNo = 0;
3798 }
3799
3800 // If the destination byte value is already defined, the values are or'd
3801 // together, which isn't a bswap (unless it's an or of the same bits).
3802 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3803 return true;
3804 ByteValues[DestNo] = I->getOperand(0);
3805 return false;
3806 }
3807
3808 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3809 // don't have this.
3810 Value *Shift = 0, *ShiftLHS = 0;
3811 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3812 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3813 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3814 return true;
3815 Instruction *SI = cast<Instruction>(Shift);
3816
3817 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003818 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3819 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003820 return true;
3821
3822 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3823 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003824 if (AndAmt->getValue().getActiveBits() > 64)
3825 return true;
3826 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003827 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003828 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003829 break;
3830 // Unknown mask for bswap.
3831 if (DestByte == ByteValues.size()) return true;
3832
Reid Spencerb83eb642006-10-20 07:07:24 +00003833 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003834 unsigned SrcByte;
3835 if (SI->getOpcode() == Instruction::Shl)
3836 SrcByte = DestByte - ShiftBytes;
3837 else
3838 SrcByte = DestByte + ShiftBytes;
3839
3840 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3841 if (SrcByte != ByteValues.size()-DestByte-1)
3842 return true;
3843
3844 // If the destination byte value is already defined, the values are or'd
3845 // together, which isn't a bswap (unless it's an or of the same bits).
3846 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3847 return true;
3848 ByteValues[DestByte] = SI->getOperand(0);
3849 return false;
3850}
3851
3852/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3853/// If so, insert the new bswap intrinsic and return it.
3854Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003855 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3856 if (!ITy || ITy->getBitWidth() % 16)
3857 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003858
3859 /// ByteValues - For each byte of the result, we keep track of which value
3860 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003861 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003862 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003863
3864 // Try to find all the pieces corresponding to the bswap.
3865 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3866 CollectBSwapParts(I.getOperand(1), ByteValues))
3867 return 0;
3868
3869 // Check to see if all of the bytes come from the same value.
3870 Value *V = ByteValues[0];
3871 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3872
3873 // Check to make sure that all of the bytes come from the same value.
3874 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3875 if (ByteValues[i] != V)
3876 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003877 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003878 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003879 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003880 return new CallInst(F, V);
3881}
3882
3883
Chris Lattner7e708292002-06-25 16:13:24 +00003884Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003885 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003886 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003887
Chris Lattner42593e62007-03-24 23:56:43 +00003888 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003889 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003890
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003891 // or X, X = X
3892 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003893 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003894
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003895 // See if we can simplify any instructions used by the instruction whose sole
3896 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003897 if (!isa<VectorType>(I.getType())) {
3898 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3899 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3900 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3901 KnownZero, KnownOne))
3902 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003903 } else if (isa<ConstantAggregateZero>(Op1)) {
3904 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3905 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3906 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3907 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003908 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003909
3910
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003911
Chris Lattner3f5b8772002-05-06 16:14:14 +00003912 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003913 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003914 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003915 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3916 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003917 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003918 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003919 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003920 return BinaryOperator::createAnd(Or,
3921 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003922 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003923
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003924 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3925 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003926 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003927 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003928 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003929 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003930 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003931 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003932
3933 // Try to fold constant and into select arguments.
3934 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003935 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003936 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003937 if (isa<PHINode>(Op0))
3938 if (Instruction *NV = FoldOpIntoPhi(I))
3939 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003940 }
3941
Chris Lattner4f637d42006-01-06 17:59:59 +00003942 Value *A = 0, *B = 0;
3943 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003944
3945 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3946 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3947 return ReplaceInstUsesWith(I, Op1);
3948 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3949 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3950 return ReplaceInstUsesWith(I, Op0);
3951
Chris Lattner6423d4c2006-07-10 20:25:24 +00003952 // (A | B) | C and A | (B | C) -> bswap if possible.
3953 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003954 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003955 match(Op1, m_Or(m_Value(), m_Value())) ||
3956 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3957 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003958 if (Instruction *BSwap = MatchBSwap(I))
3959 return BSwap;
3960 }
3961
Chris Lattner6e4c6492005-05-09 04:58:36 +00003962 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3963 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003964 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003965 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3966 InsertNewInstBefore(NOr, I);
3967 NOr->takeName(Op0);
3968 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003969 }
3970
3971 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3972 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003973 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003974 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3975 InsertNewInstBefore(NOr, I);
3976 NOr->takeName(Op0);
3977 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003978 }
3979
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003980 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003981 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003982 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3983 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003984 Value *V1 = 0, *V2 = 0, *V3 = 0;
3985 C1 = dyn_cast<ConstantInt>(C);
3986 C2 = dyn_cast<ConstantInt>(D);
3987 if (C1 && C2) { // (A & C1)|(B & C2)
3988 // If we have: ((V + N) & C1) | (V & C2)
3989 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3990 // replace with V+N.
3991 if (C1->getValue() == ~C2->getValue()) {
3992 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3993 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3994 // Add commutes, try both ways.
3995 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3996 return ReplaceInstUsesWith(I, A);
3997 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3998 return ReplaceInstUsesWith(I, A);
3999 }
4000 // Or commutes, try both ways.
4001 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4002 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4003 // Add commutes, try both ways.
4004 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4005 return ReplaceInstUsesWith(I, B);
4006 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4007 return ReplaceInstUsesWith(I, B);
4008 }
4009 }
Chris Lattner044e5332007-04-08 08:01:49 +00004010 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004011 }
4012
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004013 // Check to see if we have any common things being and'ed. If so, find the
4014 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004015 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4016 if (A == B) // (A & C)|(A & D) == A & (C|D)
4017 V1 = A, V2 = C, V3 = D;
4018 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4019 V1 = A, V2 = B, V3 = C;
4020 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4021 V1 = C, V2 = A, V3 = D;
4022 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4023 V1 = C, V2 = A, V3 = B;
4024
4025 if (V1) {
4026 Value *Or =
4027 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4028 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004029 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004030 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004031 }
Chris Lattnere511b742006-11-14 07:46:50 +00004032
4033 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004034 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4035 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4036 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004037 SI0->getOperand(1) == SI1->getOperand(1) &&
4038 (SI0->hasOneUse() || SI1->hasOneUse())) {
4039 Instruction *NewOp =
4040 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4041 SI1->getOperand(0),
4042 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004043 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4044 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004045 }
4046 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004047
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004048 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4049 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004050 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004051 } else {
4052 A = 0;
4053 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004054 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004055 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4056 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004057 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004058
Misha Brukmancb6267b2004-07-30 12:50:08 +00004059 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004060 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4061 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4062 I.getName()+".demorgan"), I);
4063 return BinaryOperator::createNot(And);
4064 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004065 }
Chris Lattnera2881962003-02-18 19:28:33 +00004066
Reid Spencere4d87aa2006-12-23 06:05:41 +00004067 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4068 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4069 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004070 return R;
4071
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004072 Value *LHSVal, *RHSVal;
4073 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004074 ICmpInst::Predicate LHSCC, RHSCC;
4075 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4076 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4077 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4078 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4079 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4080 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4081 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004082 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4083 // We can't fold (ugt x, C) | (sgt x, C2).
4084 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004085 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004086 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004087 bool NeedsSwap;
4088 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004089 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004090 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004091 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004092
4093 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004094 std::swap(LHS, RHS);
4095 std::swap(LHSCst, RHSCst);
4096 std::swap(LHSCC, RHSCC);
4097 }
4098
Reid Spencere4d87aa2006-12-23 06:05:41 +00004099 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004100 // comparing a value against two constants and or'ing the result
4101 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004102 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4103 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004104 // equal.
4105 assert(LHSCst != RHSCst && "Compares not folded above?");
4106
4107 switch (LHSCC) {
4108 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004109 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004110 switch (RHSCC) {
4111 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004112 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004113 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4114 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4115 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4116 LHSVal->getName()+".off");
4117 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004118 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004119 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004120 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004121 break; // (X == 13 | X == 15) -> no change
4122 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4123 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004124 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004125 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4126 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4127 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004128 return ReplaceInstUsesWith(I, RHS);
4129 }
4130 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004131 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004132 switch (RHSCC) {
4133 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004134 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4135 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4136 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004137 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004138 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4139 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4140 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004141 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004142 }
4143 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004144 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004145 switch (RHSCC) {
4146 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004147 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004148 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004149 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004150 // If RHSCst is [us]MAXINT, it is always false. Not handling
4151 // this can cause overflow.
4152 if (RHSCst->isMaxValue(false))
4153 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4155 false, I);
4156 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4157 break;
4158 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4159 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004160 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004161 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4162 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004163 }
4164 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004165 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004166 switch (RHSCC) {
4167 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004168 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4169 break;
4170 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004171 // If RHSCst is [us]MAXINT, it is always false. Not handling
4172 // this can cause overflow.
4173 if (RHSCst->isMaxValue(true))
4174 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004175 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4176 false, I);
4177 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4178 break;
4179 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4180 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4181 return ReplaceInstUsesWith(I, RHS);
4182 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4183 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004184 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004185 break;
4186 case ICmpInst::ICMP_UGT:
4187 switch (RHSCC) {
4188 default: assert(0 && "Unknown integer condition code!");
4189 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4190 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4191 return ReplaceInstUsesWith(I, LHS);
4192 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4193 break;
4194 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4195 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004196 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004197 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4198 break;
4199 }
4200 break;
4201 case ICmpInst::ICMP_SGT:
4202 switch (RHSCC) {
4203 default: assert(0 && "Unknown integer condition code!");
4204 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4205 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4206 return ReplaceInstUsesWith(I, LHS);
4207 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4208 break;
4209 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4210 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004211 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004212 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4213 break;
4214 }
4215 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004216 }
4217 }
4218 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004219
4220 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004221 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004222 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004223 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4224 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004225 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004226 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004227 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4228 I.getType(), TD) &&
4229 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4230 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004231 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4232 Op1C->getOperand(0),
4233 I.getName());
4234 InsertNewInstBefore(NewOp, I);
4235 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4236 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004237 }
Chris Lattner99c65742007-10-24 05:38:08 +00004238 }
4239
4240
4241 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4242 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4243 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4244 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4245 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4246 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4247 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4248 // If either of the constants are nans, then the whole thing returns
4249 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004250 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004251 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4252
4253 // Otherwise, no need to compare the two constants, compare the
4254 // rest.
4255 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4256 RHS->getOperand(0));
4257 }
4258 }
4259 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004260
Chris Lattner7e708292002-06-25 16:13:24 +00004261 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004262}
4263
Chris Lattnerc317d392004-02-16 01:20:27 +00004264// XorSelf - Implements: X ^ X --> 0
4265struct XorSelf {
4266 Value *RHS;
4267 XorSelf(Value *rhs) : RHS(rhs) {}
4268 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4269 Instruction *apply(BinaryOperator &Xor) const {
4270 return &Xor;
4271 }
4272};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004273
4274
Chris Lattner7e708292002-06-25 16:13:24 +00004275Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004276 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004277 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004278
Chris Lattnere87597f2004-10-16 18:11:37 +00004279 if (isa<UndefValue>(Op1))
4280 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4281
Chris Lattnerc317d392004-02-16 01:20:27 +00004282 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4283 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004284 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004286 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004287
4288 // See if we can simplify any instructions used by the instruction whose sole
4289 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004290 if (!isa<VectorType>(I.getType())) {
4291 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4292 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4293 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4294 KnownZero, KnownOne))
4295 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004296 } else if (isa<ConstantAggregateZero>(Op1)) {
4297 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004298 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004299
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004300 // Is this a ~ operation?
4301 if (Value *NotOp = dyn_castNotVal(&I)) {
4302 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4303 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4304 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4305 if (Op0I->getOpcode() == Instruction::And ||
4306 Op0I->getOpcode() == Instruction::Or) {
4307 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4308 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4309 Instruction *NotY =
4310 BinaryOperator::createNot(Op0I->getOperand(1),
4311 Op0I->getOperand(1)->getName()+".not");
4312 InsertNewInstBefore(NotY, I);
4313 if (Op0I->getOpcode() == Instruction::And)
4314 return BinaryOperator::createOr(Op0NotVal, NotY);
4315 else
4316 return BinaryOperator::createAnd(Op0NotVal, NotY);
4317 }
4318 }
4319 }
4320 }
4321
4322
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004323 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004324 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4325 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4326 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004327 return new ICmpInst(ICI->getInversePredicate(),
4328 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004329
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004330 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4331 return new FCmpInst(FCI->getInversePredicate(),
4332 FCI->getOperand(0), FCI->getOperand(1));
4333 }
4334
Reid Spencere4d87aa2006-12-23 06:05:41 +00004335 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004336 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004337 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4338 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004339 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4340 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004341 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004342 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004343 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004344
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004345 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004346 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004347 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004348 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004349 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4350 return BinaryOperator::createSub(
4351 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004352 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004353 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004354 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004355 // (X + C) ^ signbit -> (X + C + signbit)
4356 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4357 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004358
Chris Lattner7c4049c2004-01-12 19:35:11 +00004359 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004360 } else if (Op0I->getOpcode() == Instruction::Or) {
4361 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004362 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004363 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4364 // Anything in both C1 and C2 is known to be zero, remove it from
4365 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004366 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004367 NewRHS = ConstantExpr::getAnd(NewRHS,
4368 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004369 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004370 I.setOperand(0, Op0I->getOperand(0));
4371 I.setOperand(1, NewRHS);
4372 return &I;
4373 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004374 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004375 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004376
4377 // Try to fold constant and into select arguments.
4378 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004379 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004380 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004381 if (isa<PHINode>(Op0))
4382 if (Instruction *NV = FoldOpIntoPhi(I))
4383 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004384 }
4385
Chris Lattner8d969642003-03-10 23:06:50 +00004386 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004387 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004388 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004389
Chris Lattner8d969642003-03-10 23:06:50 +00004390 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004391 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004392 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004393
Chris Lattner318bf792007-03-18 22:51:34 +00004394
4395 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4396 if (Op1I) {
4397 Value *A, *B;
4398 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4399 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004400 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004401 I.swapOperands();
4402 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004403 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004404 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004405 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004406 }
Chris Lattner318bf792007-03-18 22:51:34 +00004407 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4408 if (Op0 == A) // A^(A^B) == B
4409 return ReplaceInstUsesWith(I, B);
4410 else if (Op0 == B) // A^(B^A) == B
4411 return ReplaceInstUsesWith(I, A);
4412 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004413 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004414 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004415 std::swap(A, B);
4416 }
Chris Lattner318bf792007-03-18 22:51:34 +00004417 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004418 I.swapOperands(); // Simplified below.
4419 std::swap(Op0, Op1);
4420 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004421 }
Chris Lattner318bf792007-03-18 22:51:34 +00004422 }
4423
4424 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4425 if (Op0I) {
4426 Value *A, *B;
4427 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4428 if (A == Op1) // (B|A)^B == (A|B)^B
4429 std::swap(A, B);
4430 if (B == Op1) { // (A|B)^B == A & ~B
4431 Instruction *NotB =
4432 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4433 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004434 }
Chris Lattner318bf792007-03-18 22:51:34 +00004435 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4436 if (Op1 == A) // (A^B)^A == B
4437 return ReplaceInstUsesWith(I, B);
4438 else if (Op1 == B) // (B^A)^A == B
4439 return ReplaceInstUsesWith(I, A);
4440 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4441 if (A == Op1) // (A&B)^A -> (B&A)^A
4442 std::swap(A, B);
4443 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004444 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004445 Instruction *N =
4446 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004447 return BinaryOperator::createAnd(N, Op1);
4448 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004449 }
Chris Lattner318bf792007-03-18 22:51:34 +00004450 }
4451
4452 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4453 if (Op0I && Op1I && Op0I->isShift() &&
4454 Op0I->getOpcode() == Op1I->getOpcode() &&
4455 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4456 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4457 Instruction *NewOp =
4458 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4459 Op1I->getOperand(0),
4460 Op0I->getName()), I);
4461 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4462 Op1I->getOperand(1));
4463 }
4464
4465 if (Op0I && Op1I) {
4466 Value *A, *B, *C, *D;
4467 // (A & B)^(A | B) -> A ^ B
4468 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4469 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4470 if ((A == C && B == D) || (A == D && B == C))
4471 return BinaryOperator::createXor(A, B);
4472 }
4473 // (A | B)^(A & B) -> A ^ B
4474 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4475 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4476 if ((A == C && B == D) || (A == D && B == C))
4477 return BinaryOperator::createXor(A, B);
4478 }
4479
4480 // (A & B)^(C & D)
4481 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4482 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4483 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4484 // (X & Y)^(X & Y) -> (Y^Z) & X
4485 Value *X = 0, *Y = 0, *Z = 0;
4486 if (A == C)
4487 X = A, Y = B, Z = D;
4488 else if (A == D)
4489 X = A, Y = B, Z = C;
4490 else if (B == C)
4491 X = B, Y = A, Z = D;
4492 else if (B == D)
4493 X = B, Y = A, Z = C;
4494
4495 if (X) {
4496 Instruction *NewOp =
4497 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4498 return BinaryOperator::createAnd(NewOp, X);
4499 }
4500 }
4501 }
4502
Reid Spencere4d87aa2006-12-23 06:05:41 +00004503 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4504 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4505 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004506 return R;
4507
Chris Lattner6fc205f2006-05-05 06:39:07 +00004508 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004509 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004510 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004511 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4512 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004513 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004514 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004515 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4516 I.getType(), TD) &&
4517 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4518 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004519 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4520 Op1C->getOperand(0),
4521 I.getName());
4522 InsertNewInstBefore(NewOp, I);
4523 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4524 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004525 }
Chris Lattner99c65742007-10-24 05:38:08 +00004526 }
Chris Lattner7e708292002-06-25 16:13:24 +00004527 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004528}
4529
Chris Lattnera96879a2004-09-29 17:40:11 +00004530/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4531/// overflowed for this type.
4532static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004533 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004534 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004535
Reid Spencere4e40032007-03-21 23:19:50 +00004536 if (IsSigned)
4537 if (In2->getValue().isNegative())
4538 return Result->getValue().sgt(In1->getValue());
4539 else
4540 return Result->getValue().slt(In1->getValue());
4541 else
4542 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004543}
4544
Chris Lattner574da9b2005-01-13 20:14:25 +00004545/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4546/// code necessary to compute the offset from the base pointer (without adding
4547/// in the base pointer). Return the result as a signed integer of intptr size.
4548static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4549 TargetData &TD = IC.getTargetData();
4550 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004551 const Type *IntPtrTy = TD.getIntPtrType();
4552 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004553
4554 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004555 unsigned IntPtrWidth = TD.getPointerSize()*8;
4556 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004557
Chris Lattner574da9b2005-01-13 20:14:25 +00004558 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4559 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004560 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004561 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4562 if (OpC->isZero()) continue;
4563
4564 // Handle a struct index, which adds its field offset to the pointer.
4565 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4566 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4567
4568 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4569 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004570 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004571 Result = IC.InsertNewInstBefore(
4572 BinaryOperator::createAdd(Result,
4573 ConstantInt::get(IntPtrTy, Size),
4574 GEP->getName()+".offs"), I);
4575 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004576 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004577
4578 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4579 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4580 Scale = ConstantExpr::getMul(OC, Scale);
4581 if (Constant *RC = dyn_cast<Constant>(Result))
4582 Result = ConstantExpr::getAdd(RC, Scale);
4583 else {
4584 // Emit an add instruction.
4585 Result = IC.InsertNewInstBefore(
4586 BinaryOperator::createAdd(Result, Scale,
4587 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004588 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004589 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004590 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004591 // Convert to correct type.
4592 if (Op->getType() != IntPtrTy) {
4593 if (Constant *OpC = dyn_cast<Constant>(Op))
4594 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4595 else
4596 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4597 Op->getName()+".c"), I);
4598 }
4599 if (Size != 1) {
4600 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4601 if (Constant *OpC = dyn_cast<Constant>(Op))
4602 Op = ConstantExpr::getMul(OpC, Scale);
4603 else // We'll let instcombine(mul) convert this to a shl if possible.
4604 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4605 GEP->getName()+".idx"), I);
4606 }
4607
4608 // Emit an add instruction.
4609 if (isa<Constant>(Op) && isa<Constant>(Result))
4610 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4611 cast<Constant>(Result));
4612 else
4613 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4614 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004615 }
4616 return Result;
4617}
4618
Reid Spencere4d87aa2006-12-23 06:05:41 +00004619/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004620/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004621Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4622 ICmpInst::Predicate Cond,
4623 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004624 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004625
4626 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4627 if (isa<PointerType>(CI->getOperand(0)->getType()))
4628 RHS = CI->getOperand(0);
4629
Chris Lattner574da9b2005-01-13 20:14:25 +00004630 Value *PtrBase = GEPLHS->getOperand(0);
4631 if (PtrBase == RHS) {
4632 // As an optimization, we don't actually have to compute the actual value of
Reid Spencere4d87aa2006-12-23 06:05:41 +00004633 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4634 // each index is zero or not.
4635 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004636 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00004637 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4638 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00004639 bool EmitIt = true;
4640 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4641 if (isa<UndefValue>(C)) // undef index -> undef.
4642 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4643 if (C->isNullValue())
4644 EmitIt = false;
Duncan Sands514ab342007-11-01 20:53:16 +00004645 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Chris Lattnerad5fec12005-01-28 19:32:01 +00004646 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00004647 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00004648 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer579dca12007-01-12 04:24:46 +00004649 ConstantInt::get(Type::Int1Ty,
4650 Cond == ICmpInst::ICMP_NE));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004651 }
4652
4653 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004654 Instruction *Comp =
Reid Spencere4d87aa2006-12-23 06:05:41 +00004655 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattnere9d782b2005-01-13 22:25:21 +00004656 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4657 if (InVal == 0)
4658 InVal = Comp;
4659 else {
4660 InVal = InsertNewInstBefore(InVal, I);
4661 InsertNewInstBefore(Comp, I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004662 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattnere9d782b2005-01-13 22:25:21 +00004663 InVal = BinaryOperator::createOr(InVal, Comp);
4664 else // True if all are equal
4665 InVal = BinaryOperator::createAnd(InVal, Comp);
4666 }
4667 }
4668 }
4669
4670 if (InVal)
4671 return InVal;
4672 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00004673 // No comparison is needed here, all indexes = 0
Reid Spencer579dca12007-01-12 04:24:46 +00004674 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4675 Cond == ICmpInst::ICMP_EQ));
Chris Lattnere9d782b2005-01-13 22:25:21 +00004676 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004677
Reid Spencere4d87aa2006-12-23 06:05:41 +00004678 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004679 // the result to fold to a constant!
4680 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4681 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4682 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004683 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4684 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004685 }
4686 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004687 // If the base pointers are different, but the indices are the same, just
4688 // compare the base pointer.
4689 if (PtrBase != GEPRHS->getOperand(0)) {
4690 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004691 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004692 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004693 if (IndicesTheSame)
4694 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4695 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4696 IndicesTheSame = false;
4697 break;
4698 }
4699
4700 // If all indices are the same, just compare the base pointers.
4701 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004702 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4703 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004704
4705 // Otherwise, the base pointers are different and the indices are
4706 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004707 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004708 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004709
Chris Lattnere9d782b2005-01-13 22:25:21 +00004710 // If one of the GEPs has all zero indices, recurse.
4711 bool AllZeros = true;
4712 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4713 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4714 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4715 AllZeros = false;
4716 break;
4717 }
4718 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004719 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4720 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004721
4722 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004723 AllZeros = true;
4724 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4725 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4726 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4727 AllZeros = false;
4728 break;
4729 }
4730 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004731 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004732
Chris Lattner4401c9c2005-01-14 00:20:05 +00004733 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4734 // If the GEPs only differ by one index, compare it.
4735 unsigned NumDifferences = 0; // Keep track of # differences.
4736 unsigned DiffOperand = 0; // The operand that differs.
4737 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4738 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004739 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4740 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004741 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004742 NumDifferences = 2;
4743 break;
4744 } else {
4745 if (NumDifferences++) break;
4746 DiffOperand = i;
4747 }
4748 }
4749
4750 if (NumDifferences == 0) // SAME GEP?
4751 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004752 ConstantInt::get(Type::Int1Ty,
4753 isTrueWhenEqual(Cond)));
4754
Chris Lattner4401c9c2005-01-14 00:20:05 +00004755 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004756 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4757 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004758 // Make sure we do a signed comparison here.
4759 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004760 }
4761 }
4762
Reid Spencere4d87aa2006-12-23 06:05:41 +00004763 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004764 // the result to fold to a constant!
4765 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4766 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4767 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4768 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4769 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004770 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004771 }
4772 }
4773 return 0;
4774}
4775
Reid Spencere4d87aa2006-12-23 06:05:41 +00004776Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4777 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004778 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004779
Chris Lattner58e97462007-01-14 19:42:17 +00004780 // Fold trivial predicates.
4781 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4782 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4783 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4784 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4785
4786 // Simplify 'fcmp pred X, X'
4787 if (Op0 == Op1) {
4788 switch (I.getPredicate()) {
4789 default: assert(0 && "Unknown predicate!");
4790 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4791 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4792 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4793 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4794 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4795 case FCmpInst::FCMP_OLT: // True if ordered and less than
4796 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4797 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4798
4799 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4800 case FCmpInst::FCMP_ULT: // True if unordered or less than
4801 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4802 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4803 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4804 I.setPredicate(FCmpInst::FCMP_UNO);
4805 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4806 return &I;
4807
4808 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4809 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4810 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4811 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4812 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4813 I.setPredicate(FCmpInst::FCMP_ORD);
4814 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4815 return &I;
4816 }
4817 }
4818
Reid Spencere4d87aa2006-12-23 06:05:41 +00004819 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004820 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004821
Reid Spencere4d87aa2006-12-23 06:05:41 +00004822 // Handle fcmp with constant RHS
4823 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4824 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4825 switch (LHSI->getOpcode()) {
4826 case Instruction::PHI:
4827 if (Instruction *NV = FoldOpIntoPhi(I))
4828 return NV;
4829 break;
4830 case Instruction::Select:
4831 // If either operand of the select is a constant, we can fold the
4832 // comparison into the select arms, which will cause one to be
4833 // constant folded and the select turned into a bitwise or.
4834 Value *Op1 = 0, *Op2 = 0;
4835 if (LHSI->hasOneUse()) {
4836 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4837 // Fold the known value into the constant operand.
4838 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4839 // Insert a new FCmp of the other select operand.
4840 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4841 LHSI->getOperand(2), RHSC,
4842 I.getName()), I);
4843 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4844 // Fold the known value into the constant operand.
4845 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4846 // Insert a new FCmp of the other select operand.
4847 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4848 LHSI->getOperand(1), RHSC,
4849 I.getName()), I);
4850 }
4851 }
4852
4853 if (Op1)
4854 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4855 break;
4856 }
4857 }
4858
4859 return Changed ? &I : 0;
4860}
4861
4862Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4863 bool Changed = SimplifyCompare(I);
4864 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4865 const Type *Ty = Op0->getType();
4866
4867 // icmp X, X
4868 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004869 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4870 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004871
4872 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004873 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004874
Reid Spencere4d87aa2006-12-23 06:05:41 +00004875 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004876 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004877 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4878 isa<ConstantPointerNull>(Op0)) &&
4879 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004880 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004881 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4882 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004883
Reid Spencere4d87aa2006-12-23 06:05:41 +00004884 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004885 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004886 switch (I.getPredicate()) {
4887 default: assert(0 && "Invalid icmp instruction!");
4888 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004889 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004890 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004891 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004892 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004893 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004894 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004895
Reid Spencere4d87aa2006-12-23 06:05:41 +00004896 case ICmpInst::ICMP_UGT:
4897 case ICmpInst::ICMP_SGT:
4898 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004899 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004900 case ICmpInst::ICMP_ULT:
4901 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004902 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4903 InsertNewInstBefore(Not, I);
4904 return BinaryOperator::createAnd(Not, Op1);
4905 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004906 case ICmpInst::ICMP_UGE:
4907 case ICmpInst::ICMP_SGE:
4908 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004909 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 case ICmpInst::ICMP_ULE:
4911 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004912 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4913 InsertNewInstBefore(Not, I);
4914 return BinaryOperator::createOr(Not, Op1);
4915 }
4916 }
Chris Lattner8b170942002-08-09 23:47:40 +00004917 }
4918
Chris Lattner2be51ae2004-06-09 04:24:29 +00004919 // See if we are doing a comparison between a constant and an instruction that
4920 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004922 Value *A, *B;
4923
Chris Lattnerb6566012008-01-05 01:18:20 +00004924 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4925 if (I.isEquality() && CI->isNullValue() &&
4926 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4927 // (icmp cond A B) if cond is equality
4928 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004929 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004930
Reid Spencere4d87aa2006-12-23 06:05:41 +00004931 switch (I.getPredicate()) {
4932 default: break;
4933 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4934 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004935 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004936 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4937 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4938 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4939 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004940 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4941 if (CI->isMinValue(true))
4942 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4943 ConstantInt::getAllOnesValue(Op0->getType()));
4944
Reid Spencere4d87aa2006-12-23 06:05:41 +00004945 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004946
Reid Spencere4d87aa2006-12-23 06:05:41 +00004947 case ICmpInst::ICMP_SLT:
4948 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004949 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004950 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4951 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4952 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4953 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4954 break;
4955
4956 case ICmpInst::ICMP_UGT:
4957 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004959 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4960 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4961 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4962 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004963
4964 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4965 if (CI->isMaxValue(true))
4966 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4967 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004968 break;
4969
4970 case ICmpInst::ICMP_SGT:
4971 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004972 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004973 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4974 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4975 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4976 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4977 break;
4978
4979 case ICmpInst::ICMP_ULE:
4980 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004981 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004982 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4983 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4984 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4985 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4986 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004987
Reid Spencere4d87aa2006-12-23 06:05:41 +00004988 case ICmpInst::ICMP_SLE:
4989 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004990 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004991 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4992 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4993 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4994 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4995 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004996
Reid Spencere4d87aa2006-12-23 06:05:41 +00004997 case ICmpInst::ICMP_UGE:
4998 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004999 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5001 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5002 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5003 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5004 break;
5005
5006 case ICmpInst::ICMP_SGE:
5007 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005008 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005009 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5010 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5011 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5012 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5013 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005014 }
5015
Reid Spencere4d87aa2006-12-23 06:05:41 +00005016 // If we still have a icmp le or icmp ge instruction, turn it into the
5017 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005018 // already been handled above, this requires little checking.
5019 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005020 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005021 default: break;
5022 case ICmpInst::ICMP_ULE:
5023 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5024 case ICmpInst::ICMP_SLE:
5025 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5026 case ICmpInst::ICMP_UGE:
5027 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5028 case ICmpInst::ICMP_SGE:
5029 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005030 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005031
5032 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005033 // in the input. If this comparison is a normal comparison, it demands all
5034 // bits, if it is a sign bit comparison, it only demands the sign bit.
5035
5036 bool UnusedBit;
5037 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5038
Reid Spencer0460fb32007-03-22 20:36:03 +00005039 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5040 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005041 if (SimplifyDemandedBits(Op0,
5042 isSignBit ? APInt::getSignBit(BitWidth)
5043 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005044 KnownZero, KnownOne, 0))
5045 return &I;
5046
5047 // Given the known and unknown bits, compute a range that the LHS could be
5048 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005049 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005050 // Compute the Min, Max and RHS values based on the known bits. For the
5051 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005052 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5053 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005054 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005055 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5056 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005057 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005058 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5059 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005060 }
5061 switch (I.getPredicate()) { // LE/GE have been folded already.
5062 default: assert(0 && "Unknown icmp opcode!");
5063 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005064 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005065 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005066 break;
5067 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005068 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005069 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005070 break;
5071 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005072 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005073 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005074 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005075 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005076 break;
5077 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005078 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005079 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005080 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005081 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005082 break;
5083 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005084 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005085 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005086 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005087 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005088 break;
5089 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005090 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005091 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005092 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005093 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005095 }
5096 }
5097
Reid Spencere4d87aa2006-12-23 06:05:41 +00005098 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005099 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005100 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005101 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005102 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5103 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005104 }
5105
Chris Lattner01deb9d2007-04-03 17:43:25 +00005106 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005107 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5108 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5109 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005110 case Instruction::GetElementPtr:
5111 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005112 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005113 bool isAllZeros = true;
5114 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5115 if (!isa<Constant>(LHSI->getOperand(i)) ||
5116 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5117 isAllZeros = false;
5118 break;
5119 }
5120 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005121 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005122 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5123 }
5124 break;
5125
Chris Lattner6970b662005-04-23 15:31:55 +00005126 case Instruction::PHI:
5127 if (Instruction *NV = FoldOpIntoPhi(I))
5128 return NV;
5129 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005130 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005131 // If either operand of the select is a constant, we can fold the
5132 // comparison into the select arms, which will cause one to be
5133 // constant folded and the select turned into a bitwise or.
5134 Value *Op1 = 0, *Op2 = 0;
5135 if (LHSI->hasOneUse()) {
5136 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5137 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005138 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5139 // Insert a new ICmp of the other select operand.
5140 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5141 LHSI->getOperand(2), RHSC,
5142 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005143 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5144 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005145 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5146 // Insert a new ICmp of the other select operand.
5147 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5148 LHSI->getOperand(1), RHSC,
5149 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005150 }
5151 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005152
Chris Lattner6970b662005-04-23 15:31:55 +00005153 if (Op1)
5154 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5155 break;
5156 }
Chris Lattner4802d902007-04-06 18:57:34 +00005157 case Instruction::Malloc:
5158 // If we have (malloc != null), and if the malloc has a single use, we
5159 // can assume it is successful and remove the malloc.
5160 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5161 AddToWorkList(LHSI);
5162 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5163 !isTrueWhenEqual(I)));
5164 }
5165 break;
5166 }
Chris Lattner6970b662005-04-23 15:31:55 +00005167 }
5168
Reid Spencere4d87aa2006-12-23 06:05:41 +00005169 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005170 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005172 return NI;
5173 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5175 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005176 return NI;
5177
Reid Spencere4d87aa2006-12-23 06:05:41 +00005178 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005179 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5180 // now.
5181 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5182 if (isa<PointerType>(Op0->getType()) &&
5183 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005184 // We keep moving the cast from the left operand over to the right
5185 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005186 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005187
Chris Lattner57d86372007-01-06 01:45:59 +00005188 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5189 // so eliminate it as well.
5190 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5191 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005192
Chris Lattnerde90b762003-11-03 04:25:02 +00005193 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005194 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005195 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005196 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005197 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005198 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005199 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005200 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005201 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005202 }
Chris Lattner57d86372007-01-06 01:45:59 +00005203 }
5204
5205 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005206 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005207 // This comes up when you have code like
5208 // int X = A < B;
5209 // if (X) ...
5210 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005211 // with a constant or another cast from the same type.
5212 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005214 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005215 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005216
Chris Lattner65b72ba2006-09-18 04:22:48 +00005217 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005218 Value *A, *B, *C, *D;
5219 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5220 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5221 Value *OtherVal = A == Op1 ? B : A;
5222 return new ICmpInst(I.getPredicate(), OtherVal,
5223 Constant::getNullValue(A->getType()));
5224 }
5225
5226 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5227 // A^c1 == C^c2 --> A == C^(c1^c2)
5228 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5229 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5230 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005231 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005232 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5233 return new ICmpInst(I.getPredicate(), A,
5234 InsertNewInstBefore(Xor, I));
5235 }
5236
5237 // A^B == A^D -> B == D
5238 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5239 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5240 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5241 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5242 }
5243 }
5244
5245 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5246 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005247 // A == (A^B) -> B == 0
5248 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005249 return new ICmpInst(I.getPredicate(), OtherVal,
5250 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005251 }
5252 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005253 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005254 return new ICmpInst(I.getPredicate(), B,
5255 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005256 }
5257 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005258 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005259 return new ICmpInst(I.getPredicate(), B,
5260 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005261 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005262
Chris Lattner9c2328e2006-11-14 06:06:06 +00005263 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5264 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5265 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5266 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5267 Value *X = 0, *Y = 0, *Z = 0;
5268
5269 if (A == C) {
5270 X = B; Y = D; Z = A;
5271 } else if (A == D) {
5272 X = B; Y = C; Z = A;
5273 } else if (B == C) {
5274 X = A; Y = D; Z = B;
5275 } else if (B == D) {
5276 X = A; Y = C; Z = B;
5277 }
5278
5279 if (X) { // Build (X^Y) & Z
5280 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5281 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5282 I.setOperand(0, Op1);
5283 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5284 return &I;
5285 }
5286 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005287 }
Chris Lattner7e708292002-06-25 16:13:24 +00005288 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005289}
5290
Chris Lattner562ef782007-06-20 23:46:26 +00005291
5292/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5293/// and CmpRHS are both known to be integer constants.
5294Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5295 ConstantInt *DivRHS) {
5296 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5297 const APInt &CmpRHSV = CmpRHS->getValue();
5298
5299 // FIXME: If the operand types don't match the type of the divide
5300 // then don't attempt this transform. The code below doesn't have the
5301 // logic to deal with a signed divide and an unsigned compare (and
5302 // vice versa). This is because (x /s C1) <s C2 produces different
5303 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5304 // (x /u C1) <u C2. Simply casting the operands and result won't
5305 // work. :( The if statement below tests that condition and bails
5306 // if it finds it.
5307 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5308 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5309 return 0;
5310 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005311 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005312
5313 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5314 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5315 // C2 (CI). By solving for X we can turn this into a range check
5316 // instead of computing a divide.
5317 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5318
5319 // Determine if the product overflows by seeing if the product is
5320 // not equal to the divide. Make sure we do the same kind of divide
5321 // as in the LHS instruction that we're folding.
5322 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5323 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5324
5325 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005326 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005327
Chris Lattner1dbfd482007-06-21 18:11:19 +00005328 // Figure out the interval that is being checked. For example, a comparison
5329 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5330 // Compute this interval based on the constants involved and the signedness of
5331 // the compare/divide. This computes a half-open interval, keeping track of
5332 // whether either value in the interval overflows. After analysis each
5333 // overflow variable is set to 0 if it's corresponding bound variable is valid
5334 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5335 int LoOverflow = 0, HiOverflow = 0;
5336 ConstantInt *LoBound = 0, *HiBound = 0;
5337
5338
Chris Lattner562ef782007-06-20 23:46:26 +00005339 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005340 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005341 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005342 HiOverflow = LoOverflow = ProdOV;
5343 if (!HiOverflow)
5344 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Chris Lattner562ef782007-06-20 23:46:26 +00005345 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5346 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005347 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005348 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5349 HiBound = DivRHS;
5350 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005351 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5352 HiOverflow = LoOverflow = ProdOV;
5353 if (!HiOverflow)
5354 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005355 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005356 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005357 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5358 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005359 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005360 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005361 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005362 }
5363 } else { // Divisor is < 0.
5364 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005365 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005366 LoBound = AddOne(DivRHS);
5367 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005368 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5369 HiOverflow = 1; // [INTMIN+1, overflow)
5370 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5371 }
Chris Lattner562ef782007-06-20 23:46:26 +00005372 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005373 // e.g. X/-5 op 3 --> [-19, -14)
5374 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005375 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005376 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005377 HiBound = AddOne(Prod);
5378 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005379 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005380 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005381 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005382 HiBound = Subtract(Prod, DivRHS);
5383 }
5384
Chris Lattner1dbfd482007-06-21 18:11:19 +00005385 // Dividing by a negative swaps the condition. LT <-> GT
5386 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005387 }
5388
5389 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005390 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005391 default: assert(0 && "Unhandled icmp opcode!");
5392 case ICmpInst::ICMP_EQ:
5393 if (LoOverflow && HiOverflow)
5394 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5395 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005396 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005397 ICmpInst::ICMP_UGE, X, LoBound);
5398 else if (LoOverflow)
5399 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5400 ICmpInst::ICMP_ULT, X, HiBound);
5401 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005402 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005403 case ICmpInst::ICMP_NE:
5404 if (LoOverflow && HiOverflow)
5405 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5406 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005407 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005408 ICmpInst::ICMP_ULT, X, LoBound);
5409 else if (LoOverflow)
5410 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5411 ICmpInst::ICMP_UGE, X, HiBound);
5412 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005413 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005414 case ICmpInst::ICMP_ULT:
5415 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005416 if (LoOverflow == +1) // Low bound is greater than input range.
5417 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5418 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005419 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005420 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005421 case ICmpInst::ICMP_UGT:
5422 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005423 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005424 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005425 else if (HiOverflow == -1) // High bound less than input range.
5426 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5427 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005428 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5429 else
5430 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5431 }
5432}
5433
5434
Chris Lattner01deb9d2007-04-03 17:43:25 +00005435/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5436///
5437Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5438 Instruction *LHSI,
5439 ConstantInt *RHS) {
5440 const APInt &RHSV = RHS->getValue();
5441
5442 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005443 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005444 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5445 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5446 // fold the xor.
5447 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5448 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5449 Value *CompareVal = LHSI->getOperand(0);
5450
5451 // If the sign bit of the XorCST is not set, there is no change to
5452 // the operation, just stop using the Xor.
5453 if (!XorCST->getValue().isNegative()) {
5454 ICI.setOperand(0, CompareVal);
5455 AddToWorkList(LHSI);
5456 return &ICI;
5457 }
5458
5459 // Was the old condition true if the operand is positive?
5460 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5461
5462 // If so, the new one isn't.
5463 isTrueIfPositive ^= true;
5464
5465 if (isTrueIfPositive)
5466 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5467 else
5468 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5469 }
5470 }
5471 break;
5472 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5473 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5474 LHSI->getOperand(0)->hasOneUse()) {
5475 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5476
5477 // If the LHS is an AND of a truncating cast, we can widen the
5478 // and/compare to be the input width without changing the value
5479 // produced, eliminating a cast.
5480 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5481 // We can do this transformation if either the AND constant does not
5482 // have its sign bit set or if it is an equality comparison.
5483 // Extending a relational comparison when we're checking the sign
5484 // bit would not work.
5485 if (Cast->hasOneUse() &&
5486 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5487 RHSV.isPositive())) {
5488 uint32_t BitWidth =
5489 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5490 APInt NewCST = AndCST->getValue();
5491 NewCST.zext(BitWidth);
5492 APInt NewCI = RHSV;
5493 NewCI.zext(BitWidth);
5494 Instruction *NewAnd =
5495 BinaryOperator::createAnd(Cast->getOperand(0),
5496 ConstantInt::get(NewCST),LHSI->getName());
5497 InsertNewInstBefore(NewAnd, ICI);
5498 return new ICmpInst(ICI.getPredicate(), NewAnd,
5499 ConstantInt::get(NewCI));
5500 }
5501 }
5502
5503 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5504 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5505 // happens a LOT in code produced by the C front-end, for bitfield
5506 // access.
5507 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5508 if (Shift && !Shift->isShift())
5509 Shift = 0;
5510
5511 ConstantInt *ShAmt;
5512 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5513 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5514 const Type *AndTy = AndCST->getType(); // Type of the and.
5515
5516 // We can fold this as long as we can't shift unknown bits
5517 // into the mask. This can only happen with signed shift
5518 // rights, as they sign-extend.
5519 if (ShAmt) {
5520 bool CanFold = Shift->isLogicalShift();
5521 if (!CanFold) {
5522 // To test for the bad case of the signed shr, see if any
5523 // of the bits shifted in could be tested after the mask.
5524 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5525 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5526
5527 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5528 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5529 AndCST->getValue()) == 0)
5530 CanFold = true;
5531 }
5532
5533 if (CanFold) {
5534 Constant *NewCst;
5535 if (Shift->getOpcode() == Instruction::Shl)
5536 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5537 else
5538 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5539
5540 // Check to see if we are shifting out any of the bits being
5541 // compared.
5542 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5543 // If we shifted bits out, the fold is not going to work out.
5544 // As a special case, check to see if this means that the
5545 // result is always true or false now.
5546 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5547 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5548 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5549 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5550 } else {
5551 ICI.setOperand(1, NewCst);
5552 Constant *NewAndCST;
5553 if (Shift->getOpcode() == Instruction::Shl)
5554 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5555 else
5556 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5557 LHSI->setOperand(1, NewAndCST);
5558 LHSI->setOperand(0, Shift->getOperand(0));
5559 AddToWorkList(Shift); // Shift is dead.
5560 AddUsesToWorkList(ICI);
5561 return &ICI;
5562 }
5563 }
5564 }
5565
5566 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5567 // preferable because it allows the C<<Y expression to be hoisted out
5568 // of a loop if Y is invariant and X is not.
5569 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5570 ICI.isEquality() && !Shift->isArithmeticShift() &&
5571 isa<Instruction>(Shift->getOperand(0))) {
5572 // Compute C << Y.
5573 Value *NS;
5574 if (Shift->getOpcode() == Instruction::LShr) {
5575 NS = BinaryOperator::createShl(AndCST,
5576 Shift->getOperand(1), "tmp");
5577 } else {
5578 // Insert a logical shift.
5579 NS = BinaryOperator::createLShr(AndCST,
5580 Shift->getOperand(1), "tmp");
5581 }
5582 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5583
5584 // Compute X & (C << Y).
5585 Instruction *NewAnd =
5586 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5587 InsertNewInstBefore(NewAnd, ICI);
5588
5589 ICI.setOperand(0, NewAnd);
5590 return &ICI;
5591 }
5592 }
5593 break;
5594
Chris Lattnera0141b92007-07-15 20:42:37 +00005595 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5596 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5597 if (!ShAmt) break;
5598
5599 uint32_t TypeBits = RHSV.getBitWidth();
5600
5601 // Check that the shift amount is in range. If not, don't perform
5602 // undefined shifts. When the shift is visited it will be
5603 // simplified.
5604 if (ShAmt->uge(TypeBits))
5605 break;
5606
5607 if (ICI.isEquality()) {
5608 // If we are comparing against bits always shifted out, the
5609 // comparison cannot succeed.
5610 Constant *Comp =
5611 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5612 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5613 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5614 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5615 return ReplaceInstUsesWith(ICI, Cst);
5616 }
5617
5618 if (LHSI->hasOneUse()) {
5619 // Otherwise strength reduce the shift into an and.
5620 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5621 Constant *Mask =
5622 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005623
Chris Lattnera0141b92007-07-15 20:42:37 +00005624 Instruction *AndI =
5625 BinaryOperator::createAnd(LHSI->getOperand(0),
5626 Mask, LHSI->getName()+".mask");
5627 Value *And = InsertNewInstBefore(AndI, ICI);
5628 return new ICmpInst(ICI.getPredicate(), And,
5629 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005630 }
5631 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005632
5633 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5634 bool TrueIfSigned = false;
5635 if (LHSI->hasOneUse() &&
5636 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5637 // (X << 31) <s 0 --> (X&1) != 0
5638 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5639 (TypeBits-ShAmt->getZExtValue()-1));
5640 Instruction *AndI =
5641 BinaryOperator::createAnd(LHSI->getOperand(0),
5642 Mask, LHSI->getName()+".mask");
5643 Value *And = InsertNewInstBefore(AndI, ICI);
5644
5645 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5646 And, Constant::getNullValue(And->getType()));
5647 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005648 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005649 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005650
5651 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005652 case Instruction::AShr: {
5653 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5654 if (!ShAmt) break;
5655
5656 if (ICI.isEquality()) {
5657 // Check that the shift amount is in range. If not, don't perform
5658 // undefined shifts. When the shift is visited it will be
5659 // simplified.
5660 uint32_t TypeBits = RHSV.getBitWidth();
5661 if (ShAmt->uge(TypeBits))
5662 break;
5663 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5664
5665 // If we are comparing against bits always shifted out, the
5666 // comparison cannot succeed.
5667 APInt Comp = RHSV << ShAmtVal;
5668 if (LHSI->getOpcode() == Instruction::LShr)
5669 Comp = Comp.lshr(ShAmtVal);
5670 else
5671 Comp = Comp.ashr(ShAmtVal);
5672
5673 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5674 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5675 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5676 return ReplaceInstUsesWith(ICI, Cst);
5677 }
5678
5679 if (LHSI->hasOneUse() || RHSV == 0) {
5680 // Otherwise strength reduce the shift into an and.
5681 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5682 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005683
Chris Lattnera0141b92007-07-15 20:42:37 +00005684 Instruction *AndI =
5685 BinaryOperator::createAnd(LHSI->getOperand(0),
5686 Mask, LHSI->getName()+".mask");
5687 Value *And = InsertNewInstBefore(AndI, ICI);
5688 return new ICmpInst(ICI.getPredicate(), And,
5689 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005690 }
5691 }
5692 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005693 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005694
5695 case Instruction::SDiv:
5696 case Instruction::UDiv:
5697 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5698 // Fold this div into the comparison, producing a range check.
5699 // Determine, based on the divide type, what the range is being
5700 // checked. If there is an overflow on the low or high side, remember
5701 // it, otherwise compute the range [low, hi) bounding the new value.
5702 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005703 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5704 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5705 DivRHS))
5706 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005707 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005708
5709 case Instruction::Add:
5710 // Fold: icmp pred (add, X, C1), C2
5711
5712 if (!ICI.isEquality()) {
5713 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5714 if (!LHSC) break;
5715 const APInt &LHSV = LHSC->getValue();
5716
5717 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5718 .subtract(LHSV);
5719
5720 if (ICI.isSignedPredicate()) {
5721 if (CR.getLower().isSignBit()) {
5722 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5723 ConstantInt::get(CR.getUpper()));
5724 } else if (CR.getUpper().isSignBit()) {
5725 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5726 ConstantInt::get(CR.getLower()));
5727 }
5728 } else {
5729 if (CR.getLower().isMinValue()) {
5730 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5731 ConstantInt::get(CR.getUpper()));
5732 } else if (CR.getUpper().isMinValue()) {
5733 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5734 ConstantInt::get(CR.getLower()));
5735 }
5736 }
5737 }
5738 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005739 }
5740
5741 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5742 if (ICI.isEquality()) {
5743 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5744
5745 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5746 // the second operand is a constant, simplify a bit.
5747 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5748 switch (BO->getOpcode()) {
5749 case Instruction::SRem:
5750 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5751 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5752 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5753 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5754 Instruction *NewRem =
5755 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5756 BO->getName());
5757 InsertNewInstBefore(NewRem, ICI);
5758 return new ICmpInst(ICI.getPredicate(), NewRem,
5759 Constant::getNullValue(BO->getType()));
5760 }
5761 }
5762 break;
5763 case Instruction::Add:
5764 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5765 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5766 if (BO->hasOneUse())
5767 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5768 Subtract(RHS, BOp1C));
5769 } else if (RHSV == 0) {
5770 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5771 // efficiently invertible, or if the add has just this one use.
5772 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5773
5774 if (Value *NegVal = dyn_castNegVal(BOp1))
5775 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5776 else if (Value *NegVal = dyn_castNegVal(BOp0))
5777 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5778 else if (BO->hasOneUse()) {
5779 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5780 InsertNewInstBefore(Neg, ICI);
5781 Neg->takeName(BO);
5782 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5783 }
5784 }
5785 break;
5786 case Instruction::Xor:
5787 // For the xor case, we can xor two constants together, eliminating
5788 // the explicit xor.
5789 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5790 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5791 ConstantExpr::getXor(RHS, BOC));
5792
5793 // FALLTHROUGH
5794 case Instruction::Sub:
5795 // Replace (([sub|xor] A, B) != 0) with (A != B)
5796 if (RHSV == 0)
5797 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5798 BO->getOperand(1));
5799 break;
5800
5801 case Instruction::Or:
5802 // If bits are being or'd in that are not present in the constant we
5803 // are comparing against, then the comparison could never succeed!
5804 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5805 Constant *NotCI = ConstantExpr::getNot(RHS);
5806 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5807 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5808 isICMP_NE));
5809 }
5810 break;
5811
5812 case Instruction::And:
5813 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5814 // If bits are being compared against that are and'd out, then the
5815 // comparison can never succeed!
5816 if ((RHSV & ~BOC->getValue()) != 0)
5817 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5818 isICMP_NE));
5819
5820 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5821 if (RHS == BOC && RHSV.isPowerOf2())
5822 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5823 ICmpInst::ICMP_NE, LHSI,
5824 Constant::getNullValue(RHS->getType()));
5825
5826 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5827 if (isSignBit(BOC)) {
5828 Value *X = BO->getOperand(0);
5829 Constant *Zero = Constant::getNullValue(X->getType());
5830 ICmpInst::Predicate pred = isICMP_NE ?
5831 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5832 return new ICmpInst(pred, X, Zero);
5833 }
5834
5835 // ((X & ~7) == 0) --> X < 8
5836 if (RHSV == 0 && isHighOnes(BOC)) {
5837 Value *X = BO->getOperand(0);
5838 Constant *NegX = ConstantExpr::getNeg(BOC);
5839 ICmpInst::Predicate pred = isICMP_NE ?
5840 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5841 return new ICmpInst(pred, X, NegX);
5842 }
5843 }
5844 default: break;
5845 }
5846 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5847 // Handle icmp {eq|ne} <intrinsic>, intcst.
5848 if (II->getIntrinsicID() == Intrinsic::bswap) {
5849 AddToWorkList(II);
5850 ICI.setOperand(0, II->getOperand(1));
5851 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5852 return &ICI;
5853 }
5854 }
5855 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005856 // If the LHS is a cast from an integral value of the same size,
5857 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005858 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5859 Value *CastOp = Cast->getOperand(0);
5860 const Type *SrcTy = CastOp->getType();
5861 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5862 if (SrcTy->isInteger() &&
5863 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5864 // If this is an unsigned comparison, try to make the comparison use
5865 // smaller constant values.
5866 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5867 // X u< 128 => X s> -1
5868 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5869 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5870 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5871 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5872 // X u> 127 => X s< 0
5873 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5874 Constant::getNullValue(SrcTy));
5875 }
5876 }
5877 }
5878 }
5879 return 0;
5880}
5881
5882/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5883/// We only handle extending casts so far.
5884///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5886 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005887 Value *LHSCIOp = LHSCI->getOperand(0);
5888 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005890 Value *RHSCIOp;
5891
Chris Lattner8c756c12007-05-05 22:41:33 +00005892 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5893 // integer type is the same size as the pointer type.
5894 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5895 getTargetData().getPointerSizeInBits() ==
5896 cast<IntegerType>(DestTy)->getBitWidth()) {
5897 Value *RHSOp = 0;
5898 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005899 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005900 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5901 RHSOp = RHSC->getOperand(0);
5902 // If the pointer types don't match, insert a bitcast.
5903 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005904 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005905 }
5906
5907 if (RHSOp)
5908 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5909 }
5910
5911 // The code below only handles extension cast instructions, so far.
5912 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005913 if (LHSCI->getOpcode() != Instruction::ZExt &&
5914 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005915 return 0;
5916
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5918 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005919
Reid Spencere4d87aa2006-12-23 06:05:41 +00005920 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005921 // Not an extension from the same type?
5922 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 if (RHSCIOp->getType() != LHSCIOp->getType())
5924 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005925
Nick Lewycky4189a532008-01-28 03:48:02 +00005926 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00005927 // and the other is a zext), then we can't handle this.
5928 if (CI->getOpcode() != LHSCI->getOpcode())
5929 return 0;
5930
Nick Lewycky4189a532008-01-28 03:48:02 +00005931 // Deal with equality cases early.
5932 if (ICI.isEquality())
5933 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5934
5935 // A signed comparison of sign extended values simplifies into a
5936 // signed comparison.
5937 if (isSignedCmp && isSignedExt)
5938 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5939
5940 // The other three cases all fold into an unsigned comparison.
5941 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005942 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005943
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944 // If we aren't dealing with a constant on the RHS, exit early
5945 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5946 if (!CI)
5947 return 0;
5948
5949 // Compute the constant that would happen if we truncated to SrcTy then
5950 // reextended to DestTy.
5951 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5952 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5953
5954 // If the re-extended constant didn't change...
5955 if (Res2 == CI) {
5956 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5957 // For example, we might have:
5958 // %A = sext short %X to uint
5959 // %B = icmp ugt uint %A, 1330
5960 // It is incorrect to transform this into
5961 // %B = icmp ugt short %X, 1330
5962 // because %A may have negative value.
5963 //
5964 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5965 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005966 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005967 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5968 else
5969 return 0;
5970 }
5971
5972 // The re-extended constant changed so the constant cannot be represented
5973 // in the shorter type. Consequently, we cannot emit a simple comparison.
5974
5975 // First, handle some easy cases. We know the result cannot be equal at this
5976 // point so handle the ICI.isEquality() cases
5977 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005978 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005979 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005980 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981
5982 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5983 // should have been folded away previously and not enter in here.
5984 Value *Result;
5985 if (isSignedCmp) {
5986 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005987 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005988 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005990 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991 } else {
5992 // We're performing an unsigned comparison.
5993 if (isSignedExt) {
5994 // We're performing an unsigned comp with a sign extended value.
5995 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005996 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5998 NegOne, ICI.getName()), ICI);
5999 } else {
6000 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006001 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006002 }
6003 }
6004
6005 // Finally, return the value computed.
6006 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6007 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6008 return ReplaceInstUsesWith(ICI, Result);
6009 } else {
6010 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6011 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6012 "ICmp should be folded!");
6013 if (Constant *CI = dyn_cast<Constant>(Result))
6014 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6015 else
6016 return BinaryOperator::createNot(Result);
6017 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006018}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006019
Reid Spencer832254e2007-02-02 02:16:23 +00006020Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6021 return commonShiftTransforms(I);
6022}
6023
6024Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6025 return commonShiftTransforms(I);
6026}
6027
6028Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006029 if (Instruction *R = commonShiftTransforms(I))
6030 return R;
6031
6032 Value *Op0 = I.getOperand(0);
6033
6034 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6035 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6036 if (CSI->isAllOnesValue())
6037 return ReplaceInstUsesWith(I, CSI);
6038
6039 // See if we can turn a signed shr into an unsigned shr.
6040 if (MaskedValueIsZero(Op0,
6041 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6042 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6043
6044 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006045}
6046
6047Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6048 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006050
6051 // shl X, 0 == X and shr X, 0 == X
6052 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006053 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006054 Op0 == Constant::getNullValue(Op0->getType()))
6055 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006056
Reid Spencere4d87aa2006-12-23 06:05:41 +00006057 if (isa<UndefValue>(Op0)) {
6058 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006059 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006060 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006061 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6062 }
6063 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006064 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6065 return ReplaceInstUsesWith(I, Op0);
6066 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006067 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006068 }
6069
Chris Lattner2eefe512004-04-09 19:05:30 +00006070 // Try to fold constant and into select arguments.
6071 if (isa<Constant>(Op0))
6072 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006073 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006074 return R;
6075
Reid Spencerb83eb642006-10-20 07:07:24 +00006076 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006077 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6078 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006079 return 0;
6080}
6081
Reid Spencerb83eb642006-10-20 07:07:24 +00006082Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006083 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006084 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006085
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006086 // See if we can simplify any instructions used by the instruction whose sole
6087 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006088 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6089 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6090 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006091 KnownZero, KnownOne))
6092 return &I;
6093
Chris Lattner4d5542c2006-01-06 07:12:35 +00006094 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6095 // of a signed value.
6096 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006097 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006098 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006099 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6100 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006101 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006102 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006103 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006104 }
6105
6106 // ((X*C1) << C2) == (X * (C1 << C2))
6107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6108 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6109 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6110 return BinaryOperator::createMul(BO->getOperand(0),
6111 ConstantExpr::getShl(BOOp, Op1));
6112
6113 // Try to fold constant and into select arguments.
6114 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6115 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6116 return R;
6117 if (isa<PHINode>(Op0))
6118 if (Instruction *NV = FoldOpIntoPhi(I))
6119 return NV;
6120
Chris Lattner8999dd32007-12-22 09:07:47 +00006121 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6122 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6123 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6124 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6125 // place. Don't try to do this transformation in this case. Also, we
6126 // require that the input operand is a shift-by-constant so that we have
6127 // confidence that the shifts will get folded together. We could do this
6128 // xform in more cases, but it is unlikely to be profitable.
6129 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6130 isa<ConstantInt>(TrOp->getOperand(1))) {
6131 // Okay, we'll do this xform. Make the shift of shift.
6132 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6133 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6134 I.getName());
6135 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6136
6137 // For logical shifts, the truncation has the effect of making the high
6138 // part of the register be zeros. Emulate this by inserting an AND to
6139 // clear the top bits as needed. This 'and' will usually be zapped by
6140 // other xforms later if dead.
6141 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6142 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6143 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6144
6145 // The mask we constructed says what the trunc would do if occurring
6146 // between the shifts. We want to know the effect *after* the second
6147 // shift. We know that it is a logical shift by a constant, so adjust the
6148 // mask as appropriate.
6149 if (I.getOpcode() == Instruction::Shl)
6150 MaskV <<= Op1->getZExtValue();
6151 else {
6152 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6153 MaskV = MaskV.lshr(Op1->getZExtValue());
6154 }
6155
6156 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6157 TI->getName());
6158 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6159
6160 // Return the value truncated to the interesting size.
6161 return new TruncInst(And, I.getType());
6162 }
6163 }
6164
Chris Lattner4d5542c2006-01-06 07:12:35 +00006165 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006166 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6167 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6168 Value *V1, *V2;
6169 ConstantInt *CC;
6170 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006171 default: break;
6172 case Instruction::Add:
6173 case Instruction::And:
6174 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006175 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006176 // These operators commute.
6177 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006178 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6179 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006180 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006181 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006182 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006183 Op0BO->getName());
6184 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006185 Instruction *X =
6186 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6187 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006188 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006189 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006190 return BinaryOperator::createAnd(X, ConstantInt::get(
6191 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006192 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006193
Chris Lattner150f12a2005-09-18 06:30:59 +00006194 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006195 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006196 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006197 match(Op0BOOp1,
6198 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006199 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6200 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006201 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006202 Op0BO->getOperand(0), Op1,
6203 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006204 InsertNewInstBefore(YS, I); // (Y << C)
6205 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006206 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006207 V1->getName()+".mask");
6208 InsertNewInstBefore(XM, I); // X & (CC << C)
6209
6210 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6211 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006212 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006213
Reid Spencera07cb7d2007-02-02 14:41:37 +00006214 // FALL THROUGH.
6215 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006216 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006217 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6218 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006219 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006220 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006221 Op0BO->getOperand(1), Op1,
6222 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006223 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006224 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006225 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006226 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006227 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006228 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006229 return BinaryOperator::createAnd(X, ConstantInt::get(
6230 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006231 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006232
Chris Lattner13d4ab42006-05-31 21:14:00 +00006233 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006234 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6235 match(Op0BO->getOperand(0),
6236 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006237 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006238 cast<BinaryOperator>(Op0BO->getOperand(0))
6239 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006240 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006241 Op0BO->getOperand(1), Op1,
6242 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006243 InsertNewInstBefore(YS, I); // (Y << C)
6244 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006245 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006246 V1->getName()+".mask");
6247 InsertNewInstBefore(XM, I); // X & (CC << C)
6248
Chris Lattner13d4ab42006-05-31 21:14:00 +00006249 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006250 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006251
Chris Lattner11021cb2005-09-18 05:12:10 +00006252 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006253 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006254 }
6255
6256
6257 // If the operand is an bitwise operator with a constant RHS, and the
6258 // shift is the only use, we can pull it out of the shift.
6259 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6260 bool isValid = true; // Valid only for And, Or, Xor
6261 bool highBitSet = false; // Transform if high bit of constant set?
6262
6263 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006264 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006265 case Instruction::Add:
6266 isValid = isLeftShift;
6267 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006268 case Instruction::Or:
6269 case Instruction::Xor:
6270 highBitSet = false;
6271 break;
6272 case Instruction::And:
6273 highBitSet = true;
6274 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006275 }
6276
6277 // If this is a signed shift right, and the high bit is modified
6278 // by the logical operation, do not perform the transformation.
6279 // The highBitSet boolean indicates the value of the high bit of
6280 // the constant which would cause it to be modified for this
6281 // operation.
6282 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006283 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006284 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006285
6286 if (isValid) {
6287 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6288
6289 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006290 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006291 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006292 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006293
6294 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6295 NewRHS);
6296 }
6297 }
6298 }
6299 }
6300
Chris Lattnerad0124c2006-01-06 07:52:12 +00006301 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006302 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6303 if (ShiftOp && !ShiftOp->isShift())
6304 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006305
Reid Spencerb83eb642006-10-20 07:07:24 +00006306 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006307 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006308 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6309 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006310 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6311 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6312 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006313
Zhou Sheng4351c642007-04-02 08:20:41 +00006314 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006315 if (AmtSum > TypeBits)
6316 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006317
6318 const IntegerType *Ty = cast<IntegerType>(I.getType());
6319
6320 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006321 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006322 return BinaryOperator::create(I.getOpcode(), X,
6323 ConstantInt::get(Ty, AmtSum));
6324 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6325 I.getOpcode() == Instruction::AShr) {
6326 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6327 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6328 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6329 I.getOpcode() == Instruction::LShr) {
6330 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6331 Instruction *Shift =
6332 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6333 InsertNewInstBefore(Shift, I);
6334
Zhou Shenge9e03f62007-03-28 15:02:20 +00006335 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006336 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006337 }
6338
Chris Lattnerb87056f2007-02-05 00:57:54 +00006339 // Okay, if we get here, one shift must be left, and the other shift must be
6340 // right. See if the amounts are equal.
6341 if (ShiftAmt1 == ShiftAmt2) {
6342 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6343 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006344 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006345 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006346 }
6347 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6348 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006349 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006350 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006351 }
6352 // We can simplify ((X << C) >>s C) into a trunc + sext.
6353 // NOTE: we could do this for any C, but that would make 'unusual' integer
6354 // types. For now, just stick to ones well-supported by the code
6355 // generators.
6356 const Type *SExtType = 0;
6357 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006358 case 1 :
6359 case 8 :
6360 case 16 :
6361 case 32 :
6362 case 64 :
6363 case 128:
6364 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6365 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006366 default: break;
6367 }
6368 if (SExtType) {
6369 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6370 InsertNewInstBefore(NewTrunc, I);
6371 return new SExtInst(NewTrunc, Ty);
6372 }
6373 // Otherwise, we can't handle it yet.
6374 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006375 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006376
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006377 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006378 if (I.getOpcode() == Instruction::Shl) {
6379 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6380 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006381 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006382 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006383 InsertNewInstBefore(Shift, I);
6384
Reid Spencer55702aa2007-03-25 21:11:44 +00006385 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6386 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006387 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006388
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006389 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006390 if (I.getOpcode() == Instruction::LShr) {
6391 assert(ShiftOp->getOpcode() == Instruction::Shl);
6392 Instruction *Shift =
6393 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6394 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006395
Reid Spencerd5e30f02007-03-26 17:18:58 +00006396 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006397 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006398 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006399
6400 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6401 } else {
6402 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006403 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006404
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006405 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006406 if (I.getOpcode() == Instruction::Shl) {
6407 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6408 ShiftOp->getOpcode() == Instruction::AShr);
6409 Instruction *Shift =
6410 BinaryOperator::create(ShiftOp->getOpcode(), X,
6411 ConstantInt::get(Ty, ShiftDiff));
6412 InsertNewInstBefore(Shift, I);
6413
Reid Spencer55702aa2007-03-25 21:11:44 +00006414 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006415 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006416 }
6417
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006418 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006419 if (I.getOpcode() == Instruction::LShr) {
6420 assert(ShiftOp->getOpcode() == Instruction::Shl);
6421 Instruction *Shift =
6422 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6423 InsertNewInstBefore(Shift, I);
6424
Reid Spencer68d27cf2007-03-26 23:45:51 +00006425 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006426 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006427 }
6428
6429 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006430 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006431 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006432 return 0;
6433}
6434
Chris Lattnera1be5662002-05-02 17:06:02 +00006435
Chris Lattnercfd65102005-10-29 04:36:15 +00006436/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6437/// expression. If so, decompose it, returning some value X, such that Val is
6438/// X*Scale+Offset.
6439///
6440static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006441 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006442 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006443 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006444 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006445 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006446 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006447 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6448 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6449 if (I->getOpcode() == Instruction::Shl) {
6450 // This is a value scaled by '1 << the shift amt'.
6451 Scale = 1U << RHS->getZExtValue();
6452 Offset = 0;
6453 return I->getOperand(0);
6454 } else if (I->getOpcode() == Instruction::Mul) {
6455 // This value is scaled by 'RHS'.
6456 Scale = RHS->getZExtValue();
6457 Offset = 0;
6458 return I->getOperand(0);
6459 } else if (I->getOpcode() == Instruction::Add) {
6460 // We have X+C. Check to see if we really have (X*C2)+C1,
6461 // where C1 is divisible by C2.
6462 unsigned SubScale;
6463 Value *SubVal =
6464 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6465 Offset += RHS->getZExtValue();
6466 Scale = SubScale;
6467 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006468 }
6469 }
6470 }
6471
6472 // Otherwise, we can't look past this.
6473 Scale = 1;
6474 Offset = 0;
6475 return Val;
6476}
6477
6478
Chris Lattnerb3f83972005-10-24 06:03:58 +00006479/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6480/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006481Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006482 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006483 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006484
Chris Lattnerb53c2382005-10-24 06:22:12 +00006485 // Remove any uses of AI that are dead.
6486 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006487
Chris Lattnerb53c2382005-10-24 06:22:12 +00006488 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6489 Instruction *User = cast<Instruction>(*UI++);
6490 if (isInstructionTriviallyDead(User)) {
6491 while (UI != E && *UI == User)
6492 ++UI; // If this instruction uses AI more than once, don't break UI.
6493
Chris Lattnerb53c2382005-10-24 06:22:12 +00006494 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006495 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006496 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006497 }
6498 }
6499
Chris Lattnerb3f83972005-10-24 06:03:58 +00006500 // Get the type really allocated and the type casted to.
6501 const Type *AllocElTy = AI.getAllocatedType();
6502 const Type *CastElTy = PTy->getElementType();
6503 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006504
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006505 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6506 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006507 if (CastElTyAlign < AllocElTyAlign) return 0;
6508
Chris Lattner39387a52005-10-24 06:35:18 +00006509 // If the allocation has multiple uses, only promote it if we are strictly
6510 // increasing the alignment of the resultant allocation. If we keep it the
6511 // same, we open the door to infinite loops of various kinds.
6512 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6513
Duncan Sands514ab342007-11-01 20:53:16 +00006514 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6515 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006516 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006517
Chris Lattner455fcc82005-10-29 03:19:53 +00006518 // See if we can satisfy the modulus by pulling a scale out of the array
6519 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006520 unsigned ArraySizeScale;
6521 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006522 Value *NumElements = // See if the array size is a decomposable linear expr.
6523 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6524
Chris Lattner455fcc82005-10-29 03:19:53 +00006525 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6526 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006527 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6528 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006529
Chris Lattner455fcc82005-10-29 03:19:53 +00006530 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6531 Value *Amt = 0;
6532 if (Scale == 1) {
6533 Amt = NumElements;
6534 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006535 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006536 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6537 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006538 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006539 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006540 else if (Scale != 1) {
6541 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6542 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006543 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006544 }
6545
Jeff Cohen86796be2007-04-04 16:58:57 +00006546 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6547 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006548 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6549 Amt = InsertNewInstBefore(Tmp, AI);
6550 }
6551
Chris Lattnerb3f83972005-10-24 06:03:58 +00006552 AllocationInst *New;
6553 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006554 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006555 else
Chris Lattner6934a042007-02-11 01:23:03 +00006556 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006557 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006558 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006559
6560 // If the allocation has multiple uses, insert a cast and change all things
6561 // that used it to use the new cast. This will also hack on CI, but it will
6562 // die soon.
6563 if (!AI.hasOneUse()) {
6564 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006565 // New is the allocation instruction, pointer typed. AI is the original
6566 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6567 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006568 InsertNewInstBefore(NewCast, AI);
6569 AI.replaceAllUsesWith(NewCast);
6570 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006571 return ReplaceInstUsesWith(CI, New);
6572}
6573
Chris Lattner70074e02006-05-13 02:06:03 +00006574/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006575/// and return it as type Ty without inserting any new casts and without
6576/// changing the computed value. This is used by code that tries to decide
6577/// whether promoting or shrinking integer operations to wider or smaller types
6578/// will allow us to eliminate a truncate or extend.
6579///
6580/// This is a truncation operation if Ty is smaller than V->getType(), or an
6581/// extension operation if Ty is larger.
6582static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006583 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006584 // We can always evaluate constants in another type.
6585 if (isa<ConstantInt>(V))
6586 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006587
6588 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006589 if (!I) return false;
6590
6591 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006592
Chris Lattner951626b2007-08-02 06:11:14 +00006593 // If this is an extension or truncate, we can often eliminate it.
6594 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6595 // If this is a cast from the destination type, we can trivially eliminate
6596 // it, and this will remove a cast overall.
6597 if (I->getOperand(0)->getType() == Ty) {
6598 // If the first operand is itself a cast, and is eliminable, do not count
6599 // this as an eliminable cast. We would prefer to eliminate those two
6600 // casts first.
6601 if (!isa<CastInst>(I->getOperand(0)))
6602 ++NumCastsRemoved;
6603 return true;
6604 }
6605 }
6606
6607 // We can't extend or shrink something that has multiple uses: doing so would
6608 // require duplicating the instruction in general, which isn't profitable.
6609 if (!I->hasOneUse()) return false;
6610
Chris Lattner70074e02006-05-13 02:06:03 +00006611 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006612 case Instruction::Add:
6613 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006614 case Instruction::And:
6615 case Instruction::Or:
6616 case Instruction::Xor:
6617 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006618 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6619 NumCastsRemoved) &&
6620 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6621 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006622
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006623 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006624 // A multiply can be truncated by truncating its operands.
6625 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6626 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6627 NumCastsRemoved) &&
6628 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6629 NumCastsRemoved);
6630
Chris Lattner46b96052006-11-29 07:18:39 +00006631 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006632 // If we are truncating the result of this SHL, and if it's a shift of a
6633 // constant amount, we can always perform a SHL in a smaller type.
6634 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006635 uint32_t BitWidth = Ty->getBitWidth();
6636 if (BitWidth < OrigTy->getBitWidth() &&
6637 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006638 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6639 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006640 }
6641 break;
6642 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006643 // If this is a truncate of a logical shr, we can truncate it to a smaller
6644 // lshr iff we know that the bits we would otherwise be shifting in are
6645 // already zeros.
6646 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006647 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6648 uint32_t BitWidth = Ty->getBitWidth();
6649 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006650 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006651 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6652 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006653 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6654 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006655 }
6656 }
Chris Lattner46b96052006-11-29 07:18:39 +00006657 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006658 case Instruction::ZExt:
6659 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006660 case Instruction::Trunc:
6661 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006662 // can safely replace it. Note that replacing it does not reduce the number
6663 // of casts in the input.
6664 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006665 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006666
Reid Spencer3da59db2006-11-27 01:05:10 +00006667 break;
6668 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006669 // TODO: Can handle more cases here.
6670 break;
6671 }
6672
6673 return false;
6674}
6675
6676/// EvaluateInDifferentType - Given an expression that
6677/// CanEvaluateInDifferentType returns true for, actually insert the code to
6678/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006679Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006680 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006681 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006682 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006683
6684 // Otherwise, it must be an instruction.
6685 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006686 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006687 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006688 case Instruction::Add:
6689 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006690 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006691 case Instruction::And:
6692 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006693 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006694 case Instruction::AShr:
6695 case Instruction::LShr:
6696 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006697 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006698 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6699 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6700 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006701 break;
6702 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006703 case Instruction::Trunc:
6704 case Instruction::ZExt:
6705 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006706 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006707 // just return the source. There's no need to insert it because it is not
6708 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006709 if (I->getOperand(0)->getType() == Ty)
6710 return I->getOperand(0);
6711
Chris Lattner951626b2007-08-02 06:11:14 +00006712 // Otherwise, must be the same type of case, so just reinsert a new one.
6713 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6714 Ty, I->getName());
6715 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006716 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006717 // TODO: Can handle more cases here.
6718 assert(0 && "Unreachable!");
6719 break;
6720 }
6721
6722 return InsertNewInstBefore(Res, *I);
6723}
6724
Reid Spencer3da59db2006-11-27 01:05:10 +00006725/// @brief Implement the transforms common to all CastInst visitors.
6726Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006727 Value *Src = CI.getOperand(0);
6728
Dan Gohman23d9d272007-05-11 21:10:54 +00006729 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006730 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006731 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006732 if (Instruction::CastOps opc =
6733 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6734 // The first cast (CSrc) is eliminable so we need to fix up or replace
6735 // the second cast (CI). CSrc will then have a good chance of being dead.
6736 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006737 }
6738 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006739
Reid Spencer3da59db2006-11-27 01:05:10 +00006740 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006741 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6742 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6743 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006744
6745 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006746 if (isa<PHINode>(Src))
6747 if (Instruction *NV = FoldOpIntoPhi(CI))
6748 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006749
Reid Spencer3da59db2006-11-27 01:05:10 +00006750 return 0;
6751}
6752
Chris Lattnerd3e28342007-04-27 17:44:50 +00006753/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6754Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6755 Value *Src = CI.getOperand(0);
6756
Chris Lattnerd3e28342007-04-27 17:44:50 +00006757 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006758 // If casting the result of a getelementptr instruction with no offset, turn
6759 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006760 if (GEP->hasAllZeroIndices()) {
6761 // Changing the cast operand is usually not a good idea but it is safe
6762 // here because the pointer operand is being replaced with another
6763 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006764 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006765 CI.setOperand(0, GEP->getOperand(0));
6766 return &CI;
6767 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006768
6769 // If the GEP has a single use, and the base pointer is a bitcast, and the
6770 // GEP computes a constant offset, see if we can convert these three
6771 // instructions into fewer. This typically happens with unions and other
6772 // non-type-safe code.
6773 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6774 if (GEP->hasAllConstantIndices()) {
6775 // We are guaranteed to get a constant from EmitGEPOffset.
6776 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6777 int64_t Offset = OffsetV->getSExtValue();
6778
6779 // Get the base pointer input of the bitcast, and the type it points to.
6780 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6781 const Type *GEPIdxTy =
6782 cast<PointerType>(OrigBase->getType())->getElementType();
6783 if (GEPIdxTy->isSized()) {
6784 SmallVector<Value*, 8> NewIndices;
6785
Chris Lattnerc42e2262007-05-05 01:59:31 +00006786 // Start with the index over the outer type. Note that the type size
6787 // might be zero (even if the offset isn't zero) if the indexed type
6788 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006789 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006790 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006791 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006792 FirstIdx = Offset/TySize;
6793 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006794
Chris Lattnerc42e2262007-05-05 01:59:31 +00006795 // Handle silly modulus not returning values values [0..TySize).
6796 if (Offset < 0) {
6797 --FirstIdx;
6798 Offset += TySize;
6799 assert(Offset >= 0);
6800 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006801 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006802 }
6803
6804 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006805
6806 // Index into the types. If we fail, set OrigBase to null.
6807 while (Offset) {
6808 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6809 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006810 if (Offset < (int64_t)SL->getSizeInBytes()) {
6811 unsigned Elt = SL->getElementContainingOffset(Offset);
6812 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006813
Chris Lattner6b6aef82007-05-15 00:16:00 +00006814 Offset -= SL->getElementOffset(Elt);
6815 GEPIdxTy = STy->getElementType(Elt);
6816 } else {
6817 // Otherwise, we can't index into this, bail out.
6818 Offset = 0;
6819 OrigBase = 0;
6820 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006821 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6822 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006823 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006824 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6825 Offset %= EltSize;
6826 } else {
6827 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6828 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006829 GEPIdxTy = STy->getElementType();
6830 } else {
6831 // Otherwise, we can't index into this, bail out.
6832 Offset = 0;
6833 OrigBase = 0;
6834 }
6835 }
6836 if (OrigBase) {
6837 // If we were able to index down into an element, create the GEP
6838 // and bitcast the result. This eliminates one bitcast, potentially
6839 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006840 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6841 NewIndices.begin(),
6842 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006843 InsertNewInstBefore(NGEP, CI);
6844 NGEP->takeName(GEP);
6845
Chris Lattner9bc14642007-04-28 00:57:34 +00006846 if (isa<BitCastInst>(CI))
6847 return new BitCastInst(NGEP, CI.getType());
6848 assert(isa<PtrToIntInst>(CI));
6849 return new PtrToIntInst(NGEP, CI.getType());
6850 }
6851 }
6852 }
6853 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006854 }
6855
6856 return commonCastTransforms(CI);
6857}
6858
6859
6860
Chris Lattnerc739cd62007-03-03 05:27:34 +00006861/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6862/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006863/// cases.
6864/// @brief Implement the transforms common to CastInst with integer operands
6865Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6866 if (Instruction *Result = commonCastTransforms(CI))
6867 return Result;
6868
6869 Value *Src = CI.getOperand(0);
6870 const Type *SrcTy = Src->getType();
6871 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006872 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6873 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006874
Reid Spencer3da59db2006-11-27 01:05:10 +00006875 // See if we can simplify any instructions used by the LHS whose sole
6876 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006877 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6878 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006879 KnownZero, KnownOne))
6880 return &CI;
6881
6882 // If the source isn't an instruction or has more than one use then we
6883 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006884 Instruction *SrcI = dyn_cast<Instruction>(Src);
6885 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006886 return 0;
6887
Chris Lattnerc739cd62007-03-03 05:27:34 +00006888 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006889 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006890 if (!isa<BitCastInst>(CI) &&
6891 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006892 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006893 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006894 // eliminates the cast, so it is always a win. If this is a zero-extension,
6895 // we need to do an AND to maintain the clear top-part of the computation,
6896 // so we require that the input have eliminated at least one cast. If this
6897 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006898 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006899 bool DoXForm;
6900 switch (CI.getOpcode()) {
6901 default:
6902 // All the others use floating point so we shouldn't actually
6903 // get here because of the check above.
6904 assert(0 && "Unknown cast type");
6905 case Instruction::Trunc:
6906 DoXForm = true;
6907 break;
6908 case Instruction::ZExt:
6909 DoXForm = NumCastsRemoved >= 1;
6910 break;
6911 case Instruction::SExt:
6912 DoXForm = NumCastsRemoved >= 2;
6913 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006914 }
6915
6916 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006917 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6918 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006919 assert(Res->getType() == DestTy);
6920 switch (CI.getOpcode()) {
6921 default: assert(0 && "Unknown cast type!");
6922 case Instruction::Trunc:
6923 case Instruction::BitCast:
6924 // Just replace this cast with the result.
6925 return ReplaceInstUsesWith(CI, Res);
6926 case Instruction::ZExt: {
6927 // We need to emit an AND to clear the high bits.
6928 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006929 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6930 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006931 return BinaryOperator::createAnd(Res, C);
6932 }
6933 case Instruction::SExt:
6934 // We need to emit a cast to truncate, then a cast to sext.
6935 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006936 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6937 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006938 }
6939 }
6940 }
6941
6942 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6943 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6944
6945 switch (SrcI->getOpcode()) {
6946 case Instruction::Add:
6947 case Instruction::Mul:
6948 case Instruction::And:
6949 case Instruction::Or:
6950 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006951 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006952 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6953 // Don't insert two casts if they cannot be eliminated. We allow
6954 // two casts to be inserted if the sizes are the same. This could
6955 // only be converting signedness, which is a noop.
6956 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006957 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6958 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006959 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006960 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6961 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6962 return BinaryOperator::create(
6963 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006964 }
6965 }
6966
6967 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6968 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6969 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006970 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006971 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006972 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006973 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6974 }
6975 break;
6976 case Instruction::SDiv:
6977 case Instruction::UDiv:
6978 case Instruction::SRem:
6979 case Instruction::URem:
6980 // If we are just changing the sign, rewrite.
6981 if (DestBitSize == SrcBitSize) {
6982 // Don't insert two casts if they cannot be eliminated. We allow
6983 // two casts to be inserted if the sizes are the same. This could
6984 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006985 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6986 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006987 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6988 Op0, DestTy, SrcI);
6989 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6990 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006991 return BinaryOperator::create(
6992 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6993 }
6994 }
6995 break;
6996
6997 case Instruction::Shl:
6998 // Allow changing the sign of the source operand. Do not allow
6999 // changing the size of the shift, UNLESS the shift amount is a
7000 // constant. We must not change variable sized shifts to a smaller
7001 // size, because it is undefined to shift more bits out than exist
7002 // in the value.
7003 if (DestBitSize == SrcBitSize ||
7004 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007005 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7006 Instruction::BitCast : Instruction::Trunc);
7007 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007008 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007009 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007010 }
7011 break;
7012 case Instruction::AShr:
7013 // If this is a signed shr, and if all bits shifted in are about to be
7014 // truncated off, turn it into an unsigned shr to allow greater
7015 // simplifications.
7016 if (DestBitSize < SrcBitSize &&
7017 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007018 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007019 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7020 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007021 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007022 }
7023 }
7024 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007025 }
7026 return 0;
7027}
7028
Chris Lattner8a9f5712007-04-11 06:57:46 +00007029Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007030 if (Instruction *Result = commonIntCastTransforms(CI))
7031 return Result;
7032
7033 Value *Src = CI.getOperand(0);
7034 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007035 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7036 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007037
7038 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7039 switch (SrcI->getOpcode()) {
7040 default: break;
7041 case Instruction::LShr:
7042 // We can shrink lshr to something smaller if we know the bits shifted in
7043 // are already zeros.
7044 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007045 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007046
7047 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007048 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007049 Value* SrcIOp0 = SrcI->getOperand(0);
7050 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007051 if (ShAmt >= DestBitWidth) // All zeros.
7052 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7053
7054 // Okay, we can shrink this. Truncate the input, then return a new
7055 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007056 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7057 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7058 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007059 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007060 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007061 } else { // This is a variable shr.
7062
7063 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7064 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7065 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007066 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007067 Value *One = ConstantInt::get(SrcI->getType(), 1);
7068
Reid Spencer832254e2007-02-02 02:16:23 +00007069 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007070 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007071 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007072 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7073 SrcI->getOperand(0),
7074 "tmp"), CI);
7075 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007076 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007077 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007078 }
7079 break;
7080 }
7081 }
7082
7083 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007084}
7085
Chris Lattner8a9f5712007-04-11 06:57:46 +00007086Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007087 // If one of the common conversion will work ..
7088 if (Instruction *Result = commonIntCastTransforms(CI))
7089 return Result;
7090
7091 Value *Src = CI.getOperand(0);
7092
7093 // If this is a cast of a cast
7094 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007095 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7096 // types and if the sizes are just right we can convert this into a logical
7097 // 'and' which will be much cheaper than the pair of casts.
7098 if (isa<TruncInst>(CSrc)) {
7099 // Get the sizes of the types involved
7100 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007101 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7102 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7103 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007104 // If we're actually extending zero bits and the trunc is a no-op
7105 if (MidSize < DstSize && SrcSize == DstSize) {
7106 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007107 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007108 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007109 Instruction *And =
7110 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7111 // Unfortunately, if the type changed, we need to cast it back.
7112 if (And->getType() != CI.getType()) {
7113 And->setName(CSrc->getName()+".mask");
7114 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007115 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007116 }
7117 return And;
7118 }
7119 }
7120 }
7121
Chris Lattner66bc3252007-04-11 05:45:39 +00007122 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7123 // If we are just checking for a icmp eq of a single bit and zext'ing it
7124 // to an integer, then shift the bit to the appropriate place and then
7125 // cast to integer to avoid the comparison.
7126 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007127 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007128
7129 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7130 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7131 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7132 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7133 Value *In = ICI->getOperand(0);
7134 Value *Sh = ConstantInt::get(In->getType(),
7135 In->getType()->getPrimitiveSizeInBits()-1);
7136 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007137 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007138 CI);
7139 if (In->getType() != CI.getType())
7140 In = CastInst::createIntegerCast(In, CI.getType(),
7141 false/*ZExt*/, "tmp", &CI);
7142
7143 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7144 Constant *One = ConstantInt::get(In->getType(), 1);
7145 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007146 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007147 CI);
7148 }
7149
7150 return ReplaceInstUsesWith(CI, In);
7151 }
7152
7153
7154
Chris Lattnerba417832007-04-11 06:12:58 +00007155 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7156 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7157 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7158 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7159 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7160 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7161 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7162 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007163 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7164 // This only works for EQ and NE
7165 ICI->isEquality()) {
7166 // If Op1C some other power of two, convert:
7167 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7168 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7169 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7170 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7171
7172 APInt KnownZeroMask(~KnownZero);
7173 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7174 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7175 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7176 // (X&4) == 2 --> false
7177 // (X&4) != 2 --> true
7178 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7179 Res = ConstantExpr::getZExt(Res, CI.getType());
7180 return ReplaceInstUsesWith(CI, Res);
7181 }
7182
7183 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7184 Value *In = ICI->getOperand(0);
7185 if (ShiftAmt) {
7186 // Perform a logical shr by shiftamt.
7187 // Insert the shift to put the result in the low bit.
7188 In = InsertNewInstBefore(
7189 BinaryOperator::createLShr(In,
7190 ConstantInt::get(In->getType(), ShiftAmt),
7191 In->getName()+".lobit"), CI);
7192 }
7193
7194 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7195 Constant *One = ConstantInt::get(In->getType(), 1);
7196 In = BinaryOperator::createXor(In, One, "tmp");
7197 InsertNewInstBefore(cast<Instruction>(In), CI);
7198 }
7199
7200 if (CI.getType() == In->getType())
7201 return ReplaceInstUsesWith(CI, In);
7202 else
7203 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7204 }
7205 }
7206 }
7207 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007208 return 0;
7209}
7210
Chris Lattner8a9f5712007-04-11 06:57:46 +00007211Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007212 if (Instruction *I = commonIntCastTransforms(CI))
7213 return I;
7214
Chris Lattner8a9f5712007-04-11 06:57:46 +00007215 Value *Src = CI.getOperand(0);
7216
7217 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7218 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7219 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7220 // If we are just checking for a icmp eq of a single bit and zext'ing it
7221 // to an integer, then shift the bit to the appropriate place and then
7222 // cast to integer to avoid the comparison.
7223 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7224 const APInt &Op1CV = Op1C->getValue();
7225
7226 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7227 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7228 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7229 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7230 Value *In = ICI->getOperand(0);
7231 Value *Sh = ConstantInt::get(In->getType(),
7232 In->getType()->getPrimitiveSizeInBits()-1);
7233 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007234 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007235 CI);
7236 if (In->getType() != CI.getType())
7237 In = CastInst::createIntegerCast(In, CI.getType(),
7238 true/*SExt*/, "tmp", &CI);
7239
7240 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7241 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7242 In->getName()+".not"), CI);
7243
7244 return ReplaceInstUsesWith(CI, In);
7245 }
7246 }
7247 }
7248
Chris Lattnerba417832007-04-11 06:12:58 +00007249 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007250}
7251
Chris Lattnerb7530652008-01-27 05:29:54 +00007252/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7253/// in the specified FP type without changing its value.
7254static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7255 const fltSemantics &Sem) {
7256 APFloat F = CFP->getValueAPF();
7257 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7258 return ConstantFP::get(FPTy, F);
7259 return 0;
7260}
7261
7262/// LookThroughFPExtensions - If this is an fp extension instruction, look
7263/// through it until we get the source value.
7264static Value *LookThroughFPExtensions(Value *V) {
7265 if (Instruction *I = dyn_cast<Instruction>(V))
7266 if (I->getOpcode() == Instruction::FPExt)
7267 return LookThroughFPExtensions(I->getOperand(0));
7268
7269 // If this value is a constant, return the constant in the smallest FP type
7270 // that can accurately represent it. This allows us to turn
7271 // (float)((double)X+2.0) into x+2.0f.
7272 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7273 if (CFP->getType() == Type::PPC_FP128Ty)
7274 return V; // No constant folding of this.
7275 // See if the value can be truncated to float and then reextended.
7276 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7277 return V;
7278 if (CFP->getType() == Type::DoubleTy)
7279 return V; // Won't shrink.
7280 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7281 return V;
7282 // Don't try to shrink to various long double types.
7283 }
7284
7285 return V;
7286}
7287
7288Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7289 if (Instruction *I = commonCastTransforms(CI))
7290 return I;
7291
7292 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7293 // smaller than the destination type, we can eliminate the truncate by doing
7294 // the add as the smaller type. This applies to add/sub/mul/div as well as
7295 // many builtins (sqrt, etc).
7296 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7297 if (OpI && OpI->hasOneUse()) {
7298 switch (OpI->getOpcode()) {
7299 default: break;
7300 case Instruction::Add:
7301 case Instruction::Sub:
7302 case Instruction::Mul:
7303 case Instruction::FDiv:
7304 case Instruction::FRem:
7305 const Type *SrcTy = OpI->getType();
7306 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7307 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7308 if (LHSTrunc->getType() != SrcTy &&
7309 RHSTrunc->getType() != SrcTy) {
7310 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7311 // If the source types were both smaller than the destination type of
7312 // the cast, do this xform.
7313 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7314 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7315 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7316 CI.getType(), CI);
7317 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7318 CI.getType(), CI);
7319 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7320 }
7321 }
7322 break;
7323 }
7324 }
7325 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007326}
7327
7328Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7329 return commonCastTransforms(CI);
7330}
7331
7332Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007333 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007334}
7335
7336Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007337 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007338}
7339
7340Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7341 return commonCastTransforms(CI);
7342}
7343
7344Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7345 return commonCastTransforms(CI);
7346}
7347
7348Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007349 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007350}
7351
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007352Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7353 if (Instruction *I = commonCastTransforms(CI))
7354 return I;
7355
7356 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7357 if (!DestPointee->isSized()) return 0;
7358
7359 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7360 ConstantInt *Cst;
7361 Value *X;
7362 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7363 m_ConstantInt(Cst)))) {
7364 // If the source and destination operands have the same type, see if this
7365 // is a single-index GEP.
7366 if (X->getType() == CI.getType()) {
7367 // Get the size of the pointee type.
7368 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7369
7370 // Convert the constant to intptr type.
7371 APInt Offset = Cst->getValue();
7372 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7373
7374 // If Offset is evenly divisible by Size, we can do this xform.
7375 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7376 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7377 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7378 }
7379 }
7380 // TODO: Could handle other cases, e.g. where add is indexing into field of
7381 // struct etc.
7382 } else if (CI.getOperand(0)->hasOneUse() &&
7383 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7384 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7385 // "inttoptr+GEP" instead of "add+intptr".
7386
7387 // Get the size of the pointee type.
7388 uint64_t Size = TD->getABITypeSize(DestPointee);
7389
7390 // Convert the constant to intptr type.
7391 APInt Offset = Cst->getValue();
7392 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7393
7394 // If Offset is evenly divisible by Size, we can do this xform.
7395 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7396 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7397
7398 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7399 "tmp"), CI);
7400 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7401 }
7402 }
7403 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007404}
7405
Chris Lattnerd3e28342007-04-27 17:44:50 +00007406Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007407 // If the operands are integer typed then apply the integer transforms,
7408 // otherwise just apply the common ones.
7409 Value *Src = CI.getOperand(0);
7410 const Type *SrcTy = Src->getType();
7411 const Type *DestTy = CI.getType();
7412
Chris Lattner42a75512007-01-15 02:27:26 +00007413 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007414 if (Instruction *Result = commonIntCastTransforms(CI))
7415 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007416 } else if (isa<PointerType>(SrcTy)) {
7417 if (Instruction *I = commonPointerCastTransforms(CI))
7418 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007419 } else {
7420 if (Instruction *Result = commonCastTransforms(CI))
7421 return Result;
7422 }
7423
7424
7425 // Get rid of casts from one type to the same type. These are useless and can
7426 // be replaced by the operand.
7427 if (DestTy == Src->getType())
7428 return ReplaceInstUsesWith(CI, Src);
7429
Reid Spencer3da59db2006-11-27 01:05:10 +00007430 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007431 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7432 const Type *DstElTy = DstPTy->getElementType();
7433 const Type *SrcElTy = SrcPTy->getElementType();
7434
7435 // If we are casting a malloc or alloca to a pointer to a type of the same
7436 // size, rewrite the allocation instruction to allocate the "right" type.
7437 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7438 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7439 return V;
7440
Chris Lattnerd717c182007-05-05 22:32:24 +00007441 // If the source and destination are pointers, and this cast is equivalent
7442 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007443 // This can enhance SROA and other transforms that want type-safe pointers.
7444 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7445 unsigned NumZeros = 0;
7446 while (SrcElTy != DstElTy &&
7447 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7448 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7449 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7450 ++NumZeros;
7451 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007452
Chris Lattnerd3e28342007-04-27 17:44:50 +00007453 // If we found a path from the src to dest, create the getelementptr now.
7454 if (SrcElTy == DstElTy) {
7455 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007456 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7457 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007458 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007459 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007460
Reid Spencer3da59db2006-11-27 01:05:10 +00007461 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7462 if (SVI->hasOneUse()) {
7463 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7464 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007465 if (isa<VectorType>(DestTy) &&
7466 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007467 SVI->getType()->getNumElements()) {
7468 CastInst *Tmp;
7469 // If either of the operands is a cast from CI.getType(), then
7470 // evaluating the shuffle in the casted destination's type will allow
7471 // us to eliminate at least one cast.
7472 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7473 Tmp->getOperand(0)->getType() == DestTy) ||
7474 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7475 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007476 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7477 SVI->getOperand(0), DestTy, &CI);
7478 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7479 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007480 // Return a new shuffle vector. Use the same element ID's, as we
7481 // know the vector types match #elts.
7482 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007483 }
7484 }
7485 }
7486 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007487 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007488}
7489
Chris Lattnere576b912004-04-09 23:46:01 +00007490/// GetSelectFoldableOperands - We want to turn code that looks like this:
7491/// %C = or %A, %B
7492/// %D = select %cond, %C, %A
7493/// into:
7494/// %C = select %cond, %B, 0
7495/// %D = or %A, %C
7496///
7497/// Assuming that the specified instruction is an operand to the select, return
7498/// a bitmask indicating which operands of this instruction are foldable if they
7499/// equal the other incoming value of the select.
7500///
7501static unsigned GetSelectFoldableOperands(Instruction *I) {
7502 switch (I->getOpcode()) {
7503 case Instruction::Add:
7504 case Instruction::Mul:
7505 case Instruction::And:
7506 case Instruction::Or:
7507 case Instruction::Xor:
7508 return 3; // Can fold through either operand.
7509 case Instruction::Sub: // Can only fold on the amount subtracted.
7510 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007511 case Instruction::LShr:
7512 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007513 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007514 default:
7515 return 0; // Cannot fold
7516 }
7517}
7518
7519/// GetSelectFoldableConstant - For the same transformation as the previous
7520/// function, return the identity constant that goes into the select.
7521static Constant *GetSelectFoldableConstant(Instruction *I) {
7522 switch (I->getOpcode()) {
7523 default: assert(0 && "This cannot happen!"); abort();
7524 case Instruction::Add:
7525 case Instruction::Sub:
7526 case Instruction::Or:
7527 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007528 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007529 case Instruction::LShr:
7530 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007531 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007532 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007533 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007534 case Instruction::Mul:
7535 return ConstantInt::get(I->getType(), 1);
7536 }
7537}
7538
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007539/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7540/// have the same opcode and only one use each. Try to simplify this.
7541Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7542 Instruction *FI) {
7543 if (TI->getNumOperands() == 1) {
7544 // If this is a non-volatile load or a cast from the same type,
7545 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007546 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007547 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7548 return 0;
7549 } else {
7550 return 0; // unknown unary op.
7551 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007552
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007553 // Fold this by inserting a select from the input values.
7554 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7555 FI->getOperand(0), SI.getName()+".v");
7556 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007557 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7558 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007559 }
7560
Reid Spencer832254e2007-02-02 02:16:23 +00007561 // Only handle binary operators here.
7562 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007563 return 0;
7564
7565 // Figure out if the operations have any operands in common.
7566 Value *MatchOp, *OtherOpT, *OtherOpF;
7567 bool MatchIsOpZero;
7568 if (TI->getOperand(0) == FI->getOperand(0)) {
7569 MatchOp = TI->getOperand(0);
7570 OtherOpT = TI->getOperand(1);
7571 OtherOpF = FI->getOperand(1);
7572 MatchIsOpZero = true;
7573 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7574 MatchOp = TI->getOperand(1);
7575 OtherOpT = TI->getOperand(0);
7576 OtherOpF = FI->getOperand(0);
7577 MatchIsOpZero = false;
7578 } else if (!TI->isCommutative()) {
7579 return 0;
7580 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7581 MatchOp = TI->getOperand(0);
7582 OtherOpT = TI->getOperand(1);
7583 OtherOpF = FI->getOperand(0);
7584 MatchIsOpZero = true;
7585 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7586 MatchOp = TI->getOperand(1);
7587 OtherOpT = TI->getOperand(0);
7588 OtherOpF = FI->getOperand(1);
7589 MatchIsOpZero = true;
7590 } else {
7591 return 0;
7592 }
7593
7594 // If we reach here, they do have operations in common.
7595 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7596 OtherOpF, SI.getName()+".v");
7597 InsertNewInstBefore(NewSI, SI);
7598
7599 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7600 if (MatchIsOpZero)
7601 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7602 else
7603 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007604 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007605 assert(0 && "Shouldn't get here");
7606 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007607}
7608
Chris Lattner3d69f462004-03-12 05:52:32 +00007609Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007610 Value *CondVal = SI.getCondition();
7611 Value *TrueVal = SI.getTrueValue();
7612 Value *FalseVal = SI.getFalseValue();
7613
7614 // select true, X, Y -> X
7615 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007616 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007617 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007618
7619 // select C, X, X -> X
7620 if (TrueVal == FalseVal)
7621 return ReplaceInstUsesWith(SI, TrueVal);
7622
Chris Lattnere87597f2004-10-16 18:11:37 +00007623 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7624 return ReplaceInstUsesWith(SI, FalseVal);
7625 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7626 return ReplaceInstUsesWith(SI, TrueVal);
7627 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7628 if (isa<Constant>(TrueVal))
7629 return ReplaceInstUsesWith(SI, TrueVal);
7630 else
7631 return ReplaceInstUsesWith(SI, FalseVal);
7632 }
7633
Reid Spencer4fe16d62007-01-11 18:21:29 +00007634 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007635 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007636 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007637 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007638 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007639 } else {
7640 // Change: A = select B, false, C --> A = and !B, C
7641 Value *NotCond =
7642 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7643 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007644 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007645 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007646 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007647 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007648 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007649 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007650 } else {
7651 // Change: A = select B, C, true --> A = or !B, C
7652 Value *NotCond =
7653 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7654 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007655 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007656 }
7657 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007658
7659 // select a, b, a -> a&b
7660 // select a, a, b -> a|b
7661 if (CondVal == TrueVal)
7662 return BinaryOperator::createOr(CondVal, FalseVal);
7663 else if (CondVal == FalseVal)
7664 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007665 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007666
Chris Lattner2eefe512004-04-09 19:05:30 +00007667 // Selecting between two integer constants?
7668 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7669 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007670 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007671 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007672 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007673 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007674 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007675 Value *NotCond =
7676 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007677 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007678 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007679 }
Chris Lattnerba417832007-04-11 06:12:58 +00007680
7681 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007682
Reid Spencere4d87aa2006-12-23 06:05:41 +00007683 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007684
Reid Spencere4d87aa2006-12-23 06:05:41 +00007685 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007686 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007687 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007688 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007689 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007690 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007691 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007692 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007693 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7694 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7695 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007696 InsertNewInstBefore(SRA, SI);
7697
Reid Spencer3da59db2006-11-27 01:05:10 +00007698 // Finally, convert to the type of the select RHS. We figure out
7699 // if this requires a SExt, Trunc or BitCast based on the sizes.
7700 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007701 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7702 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007703 if (SRASize < SISize)
7704 opc = Instruction::SExt;
7705 else if (SRASize > SISize)
7706 opc = Instruction::Trunc;
7707 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007708 }
7709 }
7710
7711
7712 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007713 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007714 // non-constant value, eliminate this whole mess. This corresponds to
7715 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007716 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007717 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007718 cast<Constant>(IC->getOperand(1))->isNullValue())
7719 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7720 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007721 isa<ConstantInt>(ICA->getOperand(1)) &&
7722 (ICA->getOperand(1) == TrueValC ||
7723 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007724 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7725 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007726 // know whether we have a icmp_ne or icmp_eq and whether the
7727 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007728 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007729 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007730 Value *V = ICA;
7731 if (ShouldNotVal)
7732 V = InsertNewInstBefore(BinaryOperator::create(
7733 Instruction::Xor, V, ICA->getOperand(1)), SI);
7734 return ReplaceInstUsesWith(SI, V);
7735 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007736 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007737 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007738
7739 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007740 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7741 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007742 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007743 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7744 // This is not safe in general for floating point:
7745 // consider X== -0, Y== +0.
7746 // It becomes safe if either operand is a nonzero constant.
7747 ConstantFP *CFPt, *CFPf;
7748 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7749 !CFPt->getValueAPF().isZero()) ||
7750 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7751 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007752 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007753 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007754 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007755 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007756 return ReplaceInstUsesWith(SI, TrueVal);
7757 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7758
Reid Spencere4d87aa2006-12-23 06:05:41 +00007759 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007760 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007761 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7762 // This is not safe in general for floating point:
7763 // consider X== -0, Y== +0.
7764 // It becomes safe if either operand is a nonzero constant.
7765 ConstantFP *CFPt, *CFPf;
7766 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7767 !CFPt->getValueAPF().isZero()) ||
7768 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7769 !CFPf->getValueAPF().isZero()))
7770 return ReplaceInstUsesWith(SI, FalseVal);
7771 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007772 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007773 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7774 return ReplaceInstUsesWith(SI, TrueVal);
7775 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7776 }
7777 }
7778
7779 // See if we are selecting two values based on a comparison of the two values.
7780 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7781 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7782 // Transform (X == Y) ? X : Y -> Y
7783 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7784 return ReplaceInstUsesWith(SI, FalseVal);
7785 // Transform (X != Y) ? X : Y -> X
7786 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7787 return ReplaceInstUsesWith(SI, TrueVal);
7788 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7789
7790 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7791 // Transform (X == Y) ? Y : X -> X
7792 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7793 return ReplaceInstUsesWith(SI, FalseVal);
7794 // Transform (X != Y) ? Y : X -> Y
7795 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007796 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007797 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7798 }
7799 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007800
Chris Lattner87875da2005-01-13 22:52:24 +00007801 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7802 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7803 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007804 Instruction *AddOp = 0, *SubOp = 0;
7805
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007806 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7807 if (TI->getOpcode() == FI->getOpcode())
7808 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7809 return IV;
7810
7811 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7812 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007813 if (TI->getOpcode() == Instruction::Sub &&
7814 FI->getOpcode() == Instruction::Add) {
7815 AddOp = FI; SubOp = TI;
7816 } else if (FI->getOpcode() == Instruction::Sub &&
7817 TI->getOpcode() == Instruction::Add) {
7818 AddOp = TI; SubOp = FI;
7819 }
7820
7821 if (AddOp) {
7822 Value *OtherAddOp = 0;
7823 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7824 OtherAddOp = AddOp->getOperand(1);
7825 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7826 OtherAddOp = AddOp->getOperand(0);
7827 }
7828
7829 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007830 // So at this point we know we have (Y -> OtherAddOp):
7831 // select C, (add X, Y), (sub X, Z)
7832 Value *NegVal; // Compute -Z
7833 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7834 NegVal = ConstantExpr::getNeg(C);
7835 } else {
7836 NegVal = InsertNewInstBefore(
7837 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007838 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007839
7840 Value *NewTrueOp = OtherAddOp;
7841 Value *NewFalseOp = NegVal;
7842 if (AddOp != TI)
7843 std::swap(NewTrueOp, NewFalseOp);
7844 Instruction *NewSel =
7845 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7846
7847 NewSel = InsertNewInstBefore(NewSel, SI);
7848 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007849 }
7850 }
7851 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007852
Chris Lattnere576b912004-04-09 23:46:01 +00007853 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007854 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007855 // See the comment above GetSelectFoldableOperands for a description of the
7856 // transformation we are doing here.
7857 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7858 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7859 !isa<Constant>(FalseVal))
7860 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7861 unsigned OpToFold = 0;
7862 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7863 OpToFold = 1;
7864 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7865 OpToFold = 2;
7866 }
7867
7868 if (OpToFold) {
7869 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007870 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007871 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007872 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007873 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007874 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7875 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007876 else {
7877 assert(0 && "Unknown instruction!!");
7878 }
7879 }
7880 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007881
Chris Lattnere576b912004-04-09 23:46:01 +00007882 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7883 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7884 !isa<Constant>(TrueVal))
7885 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7886 unsigned OpToFold = 0;
7887 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7888 OpToFold = 1;
7889 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7890 OpToFold = 2;
7891 }
7892
7893 if (OpToFold) {
7894 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007895 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007896 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007897 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007898 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007899 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7900 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007901 else
Chris Lattnere576b912004-04-09 23:46:01 +00007902 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007903 }
7904 }
7905 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007906
7907 if (BinaryOperator::isNot(CondVal)) {
7908 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7909 SI.setOperand(1, FalseVal);
7910 SI.setOperand(2, TrueVal);
7911 return &SI;
7912 }
7913
Chris Lattner3d69f462004-03-12 05:52:32 +00007914 return 0;
7915}
7916
Chris Lattnerf2369f22007-08-09 19:05:49 +00007917/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7918/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7919/// and it is more than the alignment of the ultimate object, see if we can
7920/// increase the alignment of the ultimate object, making this check succeed.
7921static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7922 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007923 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7924 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007925 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007926 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007927
7928 // If there is a large requested alignment and we can, bump up the alignment
7929 // of the global.
7930 if (PrefAlign > Align && GV->hasInitializer()) {
7931 GV->setAlignment(PrefAlign);
7932 Align = PrefAlign;
7933 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007934 return Align;
7935 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7936 unsigned Align = AI->getAlignment();
7937 if (Align == 0 && TD) {
7938 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007939 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007940 else if (isa<MallocInst>(AI)) {
7941 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007942 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007943 Align =
7944 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007945 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007946 Align =
7947 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007948 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007949 }
7950 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007951
7952 // If there is a requested alignment and if this is an alloca, round up. We
7953 // don't do this for malloc, because some systems can't respect the request.
7954 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7955 AI->setAlignment(PrefAlign);
7956 Align = PrefAlign;
7957 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007958 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007959 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007960 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007961 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007962 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7963 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00007964 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007965 // If all indexes are zero, it is just the alignment of the base pointer.
7966 bool AllZeroOperands = true;
7967 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7968 if (!isa<Constant>(GEPI->getOperand(i)) ||
7969 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7970 AllZeroOperands = false;
7971 break;
7972 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007973
7974 if (AllZeroOperands) {
7975 // Treat this like a bitcast.
7976 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7977 }
7978
7979 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7980 if (BaseAlignment == 0) return 0;
7981
Chris Lattner95a959d2006-03-06 20:18:44 +00007982 // Otherwise, if the base alignment is >= the alignment we expect for the
7983 // base pointer type, then we know that the resultant pointer is aligned at
7984 // least as much as its type requires.
7985 if (!TD) return 0;
7986
7987 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007988 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007989 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7990 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007991 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007992 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007993 Align = std::min(Align, (unsigned)
7994 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7995 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00007996 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007997 return 0;
7998 }
7999 return 0;
8000}
8001
Chris Lattnerf497b022008-01-13 23:50:23 +00008002Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8003 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8004 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8005 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8006 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8007
8008 if (CopyAlign < MinAlign) {
8009 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8010 return MI;
8011 }
8012
8013 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8014 // load/store.
8015 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8016 if (MemOpLength == 0) return 0;
8017
Chris Lattner37ac6082008-01-14 00:28:35 +00008018 // Source and destination pointer types are always "i8*" for intrinsic. See
8019 // if the size is something we can handle with a single primitive load/store.
8020 // A single load+store correctly handles overlapping memory in the memmove
8021 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008022 unsigned Size = MemOpLength->getZExtValue();
8023 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008024 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008025
Chris Lattner37ac6082008-01-14 00:28:35 +00008026 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008027 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008028
8029 // Memcpy forces the use of i8* for the source and destination. That means
8030 // that if you're using memcpy to move one double around, you'll get a cast
8031 // from double* to i8*. We'd much rather use a double load+store rather than
8032 // an i64 load+store, here because this improves the odds that the source or
8033 // dest address will be promotable. See if we can find a better type than the
8034 // integer datatype.
8035 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8036 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8037 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8038 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8039 // down through these levels if so.
8040 while (!SrcETy->isFirstClassType()) {
8041 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8042 if (STy->getNumElements() == 1)
8043 SrcETy = STy->getElementType(0);
8044 else
8045 break;
8046 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8047 if (ATy->getNumElements() == 1)
8048 SrcETy = ATy->getElementType();
8049 else
8050 break;
8051 } else
8052 break;
8053 }
8054
8055 if (SrcETy->isFirstClassType())
8056 NewPtrTy = PointerType::getUnqual(SrcETy);
8057 }
8058 }
8059
8060
Chris Lattnerf497b022008-01-13 23:50:23 +00008061 // If the memcpy/memmove provides better alignment info than we can
8062 // infer, use it.
8063 SrcAlign = std::max(SrcAlign, CopyAlign);
8064 DstAlign = std::max(DstAlign, CopyAlign);
8065
8066 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8067 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008068 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8069 InsertNewInstBefore(L, *MI);
8070 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8071
8072 // Set the size of the copy to 0, it will be deleted on the next iteration.
8073 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8074 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008075}
Chris Lattner3d69f462004-03-12 05:52:32 +00008076
Chris Lattner8b0ea312006-01-13 20:11:04 +00008077/// visitCallInst - CallInst simplification. This mostly only handles folding
8078/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8079/// the heavy lifting.
8080///
Chris Lattner9fe38862003-06-19 17:00:31 +00008081Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008082 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8083 if (!II) return visitCallSite(&CI);
8084
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008085 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8086 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008087 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008088 bool Changed = false;
8089
8090 // memmove/cpy/set of zero bytes is a noop.
8091 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8092 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8093
Chris Lattner35b9e482004-10-12 04:52:52 +00008094 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008095 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008096 // Replace the instruction with just byte operations. We would
8097 // transform other cases to loads/stores, but we don't know if
8098 // alignment is sufficient.
8099 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008100 }
8101
Chris Lattner35b9e482004-10-12 04:52:52 +00008102 // If we have a memmove and the source operation is a constant global,
8103 // then the source and dest pointers can't alias, so we can change this
8104 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008105 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008106 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8107 if (GVSrc->isConstant()) {
8108 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008109 Intrinsic::ID MemCpyID;
8110 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8111 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008112 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008113 MemCpyID = Intrinsic::memcpy_i64;
8114 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008115 Changed = true;
8116 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008117 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008118
Chris Lattner95a959d2006-03-06 20:18:44 +00008119 // If we can determine a pointer alignment that is bigger than currently
8120 // set, update the alignment.
8121 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008122 if (Instruction *I = SimplifyMemTransfer(MI))
8123 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008124 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008125 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008126 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008127 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008128 Changed = true;
8129 }
8130 }
8131
Chris Lattner8b0ea312006-01-13 20:11:04 +00008132 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008133 } else {
8134 switch (II->getIntrinsicID()) {
8135 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008136 case Intrinsic::ppc_altivec_lvx:
8137 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008138 case Intrinsic::x86_sse_loadu_ps:
8139 case Intrinsic::x86_sse2_loadu_pd:
8140 case Intrinsic::x86_sse2_loadu_dq:
8141 // Turn PPC lvx -> load if the pointer is known aligned.
8142 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008143 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008144 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8145 PointerType::getUnqual(II->getType()),
8146 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008147 return new LoadInst(Ptr);
8148 }
8149 break;
8150 case Intrinsic::ppc_altivec_stvx:
8151 case Intrinsic::ppc_altivec_stvxl:
8152 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008153 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008154 const Type *OpPtrTy =
8155 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008156 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008157 return new StoreInst(II->getOperand(1), Ptr);
8158 }
8159 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008160 case Intrinsic::x86_sse_storeu_ps:
8161 case Intrinsic::x86_sse2_storeu_pd:
8162 case Intrinsic::x86_sse2_storeu_dq:
8163 case Intrinsic::x86_sse2_storel_dq:
8164 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008165 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008166 const Type *OpPtrTy =
8167 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008168 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008169 return new StoreInst(II->getOperand(2), Ptr);
8170 }
8171 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008172
8173 case Intrinsic::x86_sse_cvttss2si: {
8174 // These intrinsics only demands the 0th element of its input vector. If
8175 // we can simplify the input based on that, do so now.
8176 uint64_t UndefElts;
8177 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8178 UndefElts)) {
8179 II->setOperand(1, V);
8180 return II;
8181 }
8182 break;
8183 }
8184
Chris Lattnere2ed0572006-04-06 19:19:17 +00008185 case Intrinsic::ppc_altivec_vperm:
8186 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008187 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008188 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8189
8190 // Check that all of the elements are integer constants or undefs.
8191 bool AllEltsOk = true;
8192 for (unsigned i = 0; i != 16; ++i) {
8193 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8194 !isa<UndefValue>(Mask->getOperand(i))) {
8195 AllEltsOk = false;
8196 break;
8197 }
8198 }
8199
8200 if (AllEltsOk) {
8201 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008202 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8203 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008204 Value *Result = UndefValue::get(Op0->getType());
8205
8206 // Only extract each element once.
8207 Value *ExtractedElts[32];
8208 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8209
8210 for (unsigned i = 0; i != 16; ++i) {
8211 if (isa<UndefValue>(Mask->getOperand(i)))
8212 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008213 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008214 Idx &= 31; // Match the hardware behavior.
8215
8216 if (ExtractedElts[Idx] == 0) {
8217 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008218 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008219 InsertNewInstBefore(Elt, CI);
8220 ExtractedElts[Idx] = Elt;
8221 }
8222
8223 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008224 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008225 InsertNewInstBefore(cast<Instruction>(Result), CI);
8226 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008227 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008228 }
8229 }
8230 break;
8231
Chris Lattnera728ddc2006-01-13 21:28:09 +00008232 case Intrinsic::stackrestore: {
8233 // If the save is right next to the restore, remove the restore. This can
8234 // happen when variable allocas are DCE'd.
8235 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8236 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8237 BasicBlock::iterator BI = SS;
8238 if (&*++BI == II)
8239 return EraseInstFromFunction(CI);
8240 }
8241 }
8242
8243 // If the stack restore is in a return/unwind block and if there are no
8244 // allocas or calls between the restore and the return, nuke the restore.
8245 TerminatorInst *TI = II->getParent()->getTerminator();
8246 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8247 BasicBlock::iterator BI = II;
8248 bool CannotRemove = false;
8249 for (++BI; &*BI != TI; ++BI) {
8250 if (isa<AllocaInst>(BI) ||
8251 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8252 CannotRemove = true;
8253 break;
8254 }
8255 }
8256 if (!CannotRemove)
8257 return EraseInstFromFunction(CI);
8258 }
8259 break;
8260 }
8261 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008262 }
8263
Chris Lattner8b0ea312006-01-13 20:11:04 +00008264 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008265}
8266
8267// InvokeInst simplification
8268//
8269Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008270 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008271}
8272
Chris Lattnera44d8a22003-10-07 22:32:43 +00008273// visitCallSite - Improvements for call and invoke instructions.
8274//
8275Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008276 bool Changed = false;
8277
8278 // If the callee is a constexpr cast of a function, attempt to move the cast
8279 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008280 if (transformConstExprCastCall(CS)) return 0;
8281
Chris Lattner6c266db2003-10-07 22:54:13 +00008282 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008283
Chris Lattner08b22ec2005-05-13 07:09:09 +00008284 if (Function *CalleeF = dyn_cast<Function>(Callee))
8285 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8286 Instruction *OldCall = CS.getInstruction();
8287 // If the call and callee calling conventions don't match, this call must
8288 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008289 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008290 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8291 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008292 if (!OldCall->use_empty())
8293 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8294 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8295 return EraseInstFromFunction(*OldCall);
8296 return 0;
8297 }
8298
Chris Lattner17be6352004-10-18 02:59:09 +00008299 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8300 // This instruction is not reachable, just remove it. We insert a store to
8301 // undef so that we know that this code is not reachable, despite the fact
8302 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008303 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008304 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008305 CS.getInstruction());
8306
8307 if (!CS.getInstruction()->use_empty())
8308 CS.getInstruction()->
8309 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8310
8311 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8312 // Don't break the CFG, insert a dummy cond branch.
8313 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008314 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008315 }
Chris Lattner17be6352004-10-18 02:59:09 +00008316 return EraseInstFromFunction(*CS.getInstruction());
8317 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008318
Duncan Sandscdb6d922007-09-17 10:26:40 +00008319 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8320 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8321 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8322 return transformCallThroughTrampoline(CS);
8323
Chris Lattner6c266db2003-10-07 22:54:13 +00008324 const PointerType *PTy = cast<PointerType>(Callee->getType());
8325 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8326 if (FTy->isVarArg()) {
8327 // See if we can optimize any arguments passed through the varargs area of
8328 // the call.
8329 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8330 E = CS.arg_end(); I != E; ++I)
8331 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8332 // If this cast does not effect the value passed through the varargs
8333 // area, we can eliminate the use of the cast.
8334 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008335 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008336 *I = Op;
8337 Changed = true;
8338 }
8339 }
8340 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008341
Duncan Sandsf0c33542007-12-19 21:13:37 +00008342 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008343 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008344 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008345 Changed = true;
8346 }
8347
Chris Lattner6c266db2003-10-07 22:54:13 +00008348 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008349}
8350
Chris Lattner9fe38862003-06-19 17:00:31 +00008351// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8352// attempt to move the cast to the arguments of the call/invoke.
8353//
8354bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8355 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8356 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008357 if (CE->getOpcode() != Instruction::BitCast ||
8358 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008359 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008360 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008361 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008362 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008363
8364 // Okay, this is a cast from a function to a different type. Unless doing so
8365 // would cause a type conversion of one of our arguments, change this call to
8366 // be a direct call with arguments casted to the appropriate types.
8367 //
8368 const FunctionType *FT = Callee->getFunctionType();
8369 const Type *OldRetTy = Caller->getType();
8370
Chris Lattnerf78616b2004-01-14 06:06:08 +00008371 // Check to see if we are changing the return type...
8372 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008373 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008374 // Conversion is ok if changing from pointer to int of same size.
8375 !(isa<PointerType>(FT->getReturnType()) &&
8376 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008377 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008378
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008379 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008380 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008381 FT->getReturnType() != Type::VoidTy &&
8382 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008383 return false; // Cannot transform this return value.
8384
Duncan Sands6c3470e2008-01-07 17:16:06 +00008385 if (CallerPAL && !Caller->use_empty()) {
8386 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8387 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8388 return false; // Attribute not compatible with transformed value.
8389 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008390
Chris Lattnerf78616b2004-01-14 06:06:08 +00008391 // If the callsite is an invoke instruction, and the return value is used by
8392 // a PHI node in a successor, we cannot change the return type of the call
8393 // because there is no place to put the cast instruction (without breaking
8394 // the critical edge). Bail out in this case.
8395 if (!Caller->use_empty())
8396 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8397 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8398 UI != E; ++UI)
8399 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8400 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008401 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008402 return false;
8403 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008404
8405 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8406 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008407
Chris Lattner9fe38862003-06-19 17:00:31 +00008408 CallSite::arg_iterator AI = CS.arg_begin();
8409 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8410 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008411 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008412
8413 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008414 return false; // Cannot transform this parameter value.
8415
Duncan Sands6c3470e2008-01-07 17:16:06 +00008416 if (CallerPAL) {
8417 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8418 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8419 return false; // Attribute not compatible with transformed value.
8420 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008421
Reid Spencer3da59db2006-11-27 01:05:10 +00008422 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008423 // Some conversions are safe even if we do not have a body.
8424 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008425 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008426 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008427 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008428 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8429 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008430 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008431 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008432 }
8433
8434 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008435 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008436 return false; // Do not delete arguments unless we have a function body...
8437
Duncan Sandse1e520f2008-01-13 08:02:44 +00008438 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008439 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008440 // won't be dropping them. Check that these extra arguments have attributes
8441 // that are compatible with being a vararg call argument.
8442 for (unsigned i = CallerPAL->size(); i; --i) {
8443 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8444 break;
8445 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8446 if (PAttrs & ParamAttr::VarArgsIncompatible)
8447 return false;
8448 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008449
Chris Lattner9fe38862003-06-19 17:00:31 +00008450 // Okay, we decided that this is a safe thing to do: go ahead and start
8451 // inserting cast instructions as necessary...
8452 std::vector<Value*> Args;
8453 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008454 ParamAttrsVector attrVec;
8455 attrVec.reserve(NumCommonArgs);
8456
8457 // Get any return attributes.
8458 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8459
8460 // If the return value is not being used, the type may not be compatible
8461 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008462 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008463
8464 // Add the new return attributes.
8465 if (RAttrs)
8466 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008467
8468 AI = CS.arg_begin();
8469 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8470 const Type *ParamTy = FT->getParamType(i);
8471 if ((*AI)->getType() == ParamTy) {
8472 Args.push_back(*AI);
8473 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008474 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008475 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008476 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008477 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008478 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008479
8480 // Add any parameter attributes.
8481 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8482 if (PAttrs)
8483 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008484 }
8485
8486 // If the function takes more arguments than the call was taking, add them
8487 // now...
8488 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8489 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8490
8491 // If we are removing arguments to the function, emit an obnoxious warning...
8492 if (FT->getNumParams() < NumActualArgs)
8493 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008494 cerr << "WARNING: While resolving call to function '"
8495 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008496 } else {
8497 // Add all of the arguments in their promoted form to the arg list...
8498 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8499 const Type *PTy = getPromotedType((*AI)->getType());
8500 if (PTy != (*AI)->getType()) {
8501 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008502 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8503 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008504 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008505 InsertNewInstBefore(Cast, *Caller);
8506 Args.push_back(Cast);
8507 } else {
8508 Args.push_back(*AI);
8509 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008510
Duncan Sandse1e520f2008-01-13 08:02:44 +00008511 // Add any parameter attributes.
8512 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8513 if (PAttrs)
8514 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8515 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008516 }
8517
8518 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008519 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008520
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008521 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8522
Chris Lattner9fe38862003-06-19 17:00:31 +00008523 Instruction *NC;
8524 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008525 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008526 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008527 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008528 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008529 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008530 NC = new CallInst(Callee, Args.begin(), Args.end(),
8531 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008532 CallInst *CI = cast<CallInst>(Caller);
8533 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008534 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008535 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008536 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008537 }
8538
Chris Lattner6934a042007-02-11 01:23:03 +00008539 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008540 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008541 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008542 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008543 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008544 OldRetTy, false);
8545 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008546
8547 // If this is an invoke instruction, we should insert it after the first
8548 // non-phi, instruction in the normal successor block.
8549 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8550 BasicBlock::iterator I = II->getNormalDest()->begin();
8551 while (isa<PHINode>(I)) ++I;
8552 InsertNewInstBefore(NC, *I);
8553 } else {
8554 // Otherwise, it's a call, just insert cast right after the call instr
8555 InsertNewInstBefore(NC, *Caller);
8556 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008557 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008558 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008559 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008560 }
8561 }
8562
8563 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8564 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008565 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008566 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008567 return true;
8568}
8569
Duncan Sandscdb6d922007-09-17 10:26:40 +00008570// transformCallThroughTrampoline - Turn a call to a function created by the
8571// init_trampoline intrinsic into a direct call to the underlying function.
8572//
8573Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8574 Value *Callee = CS.getCalledValue();
8575 const PointerType *PTy = cast<PointerType>(Callee->getType());
8576 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008577 const ParamAttrsList *Attrs = CS.getParamAttrs();
8578
8579 // If the call already has the 'nest' attribute somewhere then give up -
8580 // otherwise 'nest' would occur twice after splicing in the chain.
8581 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8582 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008583
8584 IntrinsicInst *Tramp =
8585 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8586
8587 Function *NestF =
8588 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8589 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8590 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8591
Duncan Sandsdc024672007-11-27 13:23:08 +00008592 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008593 unsigned NestIdx = 1;
8594 const Type *NestTy = 0;
8595 uint16_t NestAttr = 0;
8596
8597 // Look for a parameter marked with the 'nest' attribute.
8598 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8599 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8600 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8601 // Record the parameter type and any other attributes.
8602 NestTy = *I;
8603 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8604 break;
8605 }
8606
8607 if (NestTy) {
8608 Instruction *Caller = CS.getInstruction();
8609 std::vector<Value*> NewArgs;
8610 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8611
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008612 ParamAttrsVector NewAttrs;
8613 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8614
Duncan Sandscdb6d922007-09-17 10:26:40 +00008615 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008616 // mean appending it. Likewise for attributes.
8617
8618 // Add any function result attributes.
8619 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8620 if (Attr)
8621 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8622
Duncan Sandscdb6d922007-09-17 10:26:40 +00008623 {
8624 unsigned Idx = 1;
8625 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8626 do {
8627 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008628 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008629 Value *NestVal = Tramp->getOperand(3);
8630 if (NestVal->getType() != NestTy)
8631 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8632 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008633 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008634 }
8635
8636 if (I == E)
8637 break;
8638
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008639 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008640 NewArgs.push_back(*I);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008641 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8642 if (Attr)
8643 NewAttrs.push_back
8644 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008645
8646 ++Idx, ++I;
8647 } while (1);
8648 }
8649
8650 // The trampoline may have been bitcast to a bogus type (FTy).
8651 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008652 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008653
Duncan Sandscdb6d922007-09-17 10:26:40 +00008654 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008655 NewTypes.reserve(FTy->getNumParams()+1);
8656
Duncan Sandscdb6d922007-09-17 10:26:40 +00008657 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008658 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008659 {
8660 unsigned Idx = 1;
8661 FunctionType::param_iterator I = FTy->param_begin(),
8662 E = FTy->param_end();
8663
8664 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008665 if (Idx == NestIdx)
8666 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008667 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008668
8669 if (I == E)
8670 break;
8671
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008672 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008673 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008674
8675 ++Idx, ++I;
8676 } while (1);
8677 }
8678
8679 // Replace the trampoline call with a direct call. Let the generic
8680 // code sort out any function type mismatches.
8681 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008682 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008683 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8684 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008685 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008686
8687 Instruction *NewCaller;
8688 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8689 NewCaller = new InvokeInst(NewCallee,
8690 II->getNormalDest(), II->getUnwindDest(),
8691 NewArgs.begin(), NewArgs.end(),
8692 Caller->getName(), Caller);
8693 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008694 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008695 } else {
8696 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8697 Caller->getName(), Caller);
8698 if (cast<CallInst>(Caller)->isTailCall())
8699 cast<CallInst>(NewCaller)->setTailCall();
8700 cast<CallInst>(NewCaller)->
8701 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008702 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008703 }
8704 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8705 Caller->replaceAllUsesWith(NewCaller);
8706 Caller->eraseFromParent();
8707 RemoveFromWorkList(Caller);
8708 return 0;
8709 }
8710 }
8711
8712 // Replace the trampoline call with a direct call. Since there is no 'nest'
8713 // parameter, there is no need to adjust the argument list. Let the generic
8714 // code sort out any function type mismatches.
8715 Constant *NewCallee =
8716 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8717 CS.setCalledFunction(NewCallee);
8718 return CS.getInstruction();
8719}
8720
Chris Lattner7da52b22006-11-01 04:51:18 +00008721/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8722/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8723/// and a single binop.
8724Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8725 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008726 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8727 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008728 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008729 Value *LHSVal = FirstInst->getOperand(0);
8730 Value *RHSVal = FirstInst->getOperand(1);
8731
8732 const Type *LHSType = LHSVal->getType();
8733 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008734
8735 // Scan to see if all operands are the same opcode, all have one use, and all
8736 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008737 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008738 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008739 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008740 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008741 // types or GEP's with different index types.
8742 I->getOperand(0)->getType() != LHSType ||
8743 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008744 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008745
8746 // If they are CmpInst instructions, check their predicates
8747 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8748 if (cast<CmpInst>(I)->getPredicate() !=
8749 cast<CmpInst>(FirstInst)->getPredicate())
8750 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008751
8752 // Keep track of which operand needs a phi node.
8753 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8754 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008755 }
8756
Chris Lattner53738a42006-11-08 19:42:28 +00008757 // Otherwise, this is safe to transform, determine if it is profitable.
8758
8759 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8760 // Indexes are often folded into load/store instructions, so we don't want to
8761 // hide them behind a phi.
8762 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8763 return 0;
8764
Chris Lattner7da52b22006-11-01 04:51:18 +00008765 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008766 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008767 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008768 if (LHSVal == 0) {
8769 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8770 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8771 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008772 InsertNewInstBefore(NewLHS, PN);
8773 LHSVal = NewLHS;
8774 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008775
8776 if (RHSVal == 0) {
8777 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8778 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8779 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008780 InsertNewInstBefore(NewRHS, PN);
8781 RHSVal = NewRHS;
8782 }
8783
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008784 // Add all operands to the new PHIs.
8785 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8786 if (NewLHS) {
8787 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8788 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8789 }
8790 if (NewRHS) {
8791 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8792 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8793 }
8794 }
8795
Chris Lattner7da52b22006-11-01 04:51:18 +00008796 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008797 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008798 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8799 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8800 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008801 else {
8802 assert(isa<GetElementPtrInst>(FirstInst));
8803 return new GetElementPtrInst(LHSVal, RHSVal);
8804 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008805}
8806
Chris Lattner76c73142006-11-01 07:13:54 +00008807/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8808/// of the block that defines it. This means that it must be obvious the value
8809/// of the load is not changed from the point of the load to the end of the
8810/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008811///
8812/// Finally, it is safe, but not profitable, to sink a load targetting a
8813/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8814/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008815static bool isSafeToSinkLoad(LoadInst *L) {
8816 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8817
8818 for (++BBI; BBI != E; ++BBI)
8819 if (BBI->mayWriteToMemory())
8820 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008821
8822 // Check for non-address taken alloca. If not address-taken already, it isn't
8823 // profitable to do this xform.
8824 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8825 bool isAddressTaken = false;
8826 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8827 UI != E; ++UI) {
8828 if (isa<LoadInst>(UI)) continue;
8829 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8830 // If storing TO the alloca, then the address isn't taken.
8831 if (SI->getOperand(1) == AI) continue;
8832 }
8833 isAddressTaken = true;
8834 break;
8835 }
8836
8837 if (!isAddressTaken)
8838 return false;
8839 }
8840
Chris Lattner76c73142006-11-01 07:13:54 +00008841 return true;
8842}
8843
Chris Lattner9fe38862003-06-19 17:00:31 +00008844
Chris Lattnerbac32862004-11-14 19:13:23 +00008845// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8846// operator and they all are only used by the PHI, PHI together their
8847// inputs, and do the operation once, to the result of the PHI.
8848Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8849 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8850
8851 // Scan the instruction, looking for input operations that can be folded away.
8852 // If all input operands to the phi are the same instruction (e.g. a cast from
8853 // the same type or "+42") we can pull the operation through the PHI, reducing
8854 // code size and simplifying code.
8855 Constant *ConstantOp = 0;
8856 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008857 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008858 if (isa<CastInst>(FirstInst)) {
8859 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008860 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008861 // Can fold binop, compare or shift here if the RHS is a constant,
8862 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008863 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008864 if (ConstantOp == 0)
8865 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008866 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8867 isVolatile = LI->isVolatile();
8868 // We can't sink the load if the loaded value could be modified between the
8869 // load and the PHI.
8870 if (LI->getParent() != PN.getIncomingBlock(0) ||
8871 !isSafeToSinkLoad(LI))
8872 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008873 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008874 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008875 return FoldPHIArgBinOpIntoPHI(PN);
8876 // Can't handle general GEPs yet.
8877 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008878 } else {
8879 return 0; // Cannot fold this operation.
8880 }
8881
8882 // Check to see if all arguments are the same operation.
8883 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8884 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8885 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008886 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008887 return 0;
8888 if (CastSrcTy) {
8889 if (I->getOperand(0)->getType() != CastSrcTy)
8890 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008891 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008892 // We can't sink the load if the loaded value could be modified between
8893 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008894 if (LI->isVolatile() != isVolatile ||
8895 LI->getParent() != PN.getIncomingBlock(i) ||
8896 !isSafeToSinkLoad(LI))
8897 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008898 } else if (I->getOperand(1) != ConstantOp) {
8899 return 0;
8900 }
8901 }
8902
8903 // Okay, they are all the same operation. Create a new PHI node of the
8904 // correct type, and PHI together all of the LHS's of the instructions.
8905 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8906 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008907 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008908
8909 Value *InVal = FirstInst->getOperand(0);
8910 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008911
8912 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008913 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8914 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8915 if (NewInVal != InVal)
8916 InVal = 0;
8917 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8918 }
8919
8920 Value *PhiVal;
8921 if (InVal) {
8922 // The new PHI unions all of the same values together. This is really
8923 // common, so we handle it intelligently here for compile-time speed.
8924 PhiVal = InVal;
8925 delete NewPN;
8926 } else {
8927 InsertNewInstBefore(NewPN, PN);
8928 PhiVal = NewPN;
8929 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008930
Chris Lattnerbac32862004-11-14 19:13:23 +00008931 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008932 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8933 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008934 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008935 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008936 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008937 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008938 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8939 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8940 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008941 else
Reid Spencer832254e2007-02-02 02:16:23 +00008942 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008943 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008944}
Chris Lattnera1be5662002-05-02 17:06:02 +00008945
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008946/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8947/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008948static bool DeadPHICycle(PHINode *PN,
8949 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008950 if (PN->use_empty()) return true;
8951 if (!PN->hasOneUse()) return false;
8952
8953 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008954 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008955 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00008956
8957 // Don't scan crazily complex things.
8958 if (PotentiallyDeadPHIs.size() == 16)
8959 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008960
8961 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8962 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008963
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008964 return false;
8965}
8966
Chris Lattnercf5008a2007-11-06 21:52:06 +00008967/// PHIsEqualValue - Return true if this phi node is always equal to
8968/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8969/// z = some value; x = phi (y, z); y = phi (x, z)
8970static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8971 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8972 // See if we already saw this PHI node.
8973 if (!ValueEqualPHIs.insert(PN))
8974 return true;
8975
8976 // Don't scan crazily complex things.
8977 if (ValueEqualPHIs.size() == 16)
8978 return false;
8979
8980 // Scan the operands to see if they are either phi nodes or are equal to
8981 // the value.
8982 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8983 Value *Op = PN->getIncomingValue(i);
8984 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8985 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8986 return false;
8987 } else if (Op != NonPhiInVal)
8988 return false;
8989 }
8990
8991 return true;
8992}
8993
8994
Chris Lattner473945d2002-05-06 18:06:38 +00008995// PHINode simplification
8996//
Chris Lattner7e708292002-06-25 16:13:24 +00008997Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008998 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008999 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009000
Owen Anderson7e057142006-07-10 22:03:18 +00009001 if (Value *V = PN.hasConstantValue())
9002 return ReplaceInstUsesWith(PN, V);
9003
Owen Anderson7e057142006-07-10 22:03:18 +00009004 // If all PHI operands are the same operation, pull them through the PHI,
9005 // reducing code size.
9006 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9007 PN.getIncomingValue(0)->hasOneUse())
9008 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9009 return Result;
9010
9011 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9012 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9013 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009014 if (PN.hasOneUse()) {
9015 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9016 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009017 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009018 PotentiallyDeadPHIs.insert(&PN);
9019 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9020 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9021 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009022
9023 // If this phi has a single use, and if that use just computes a value for
9024 // the next iteration of a loop, delete the phi. This occurs with unused
9025 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9026 // common case here is good because the only other things that catch this
9027 // are induction variable analysis (sometimes) and ADCE, which is only run
9028 // late.
9029 if (PHIUser->hasOneUse() &&
9030 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9031 PHIUser->use_back() == &PN) {
9032 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9033 }
9034 }
Owen Anderson7e057142006-07-10 22:03:18 +00009035
Chris Lattnercf5008a2007-11-06 21:52:06 +00009036 // We sometimes end up with phi cycles that non-obviously end up being the
9037 // same value, for example:
9038 // z = some value; x = phi (y, z); y = phi (x, z)
9039 // where the phi nodes don't necessarily need to be in the same block. Do a
9040 // quick check to see if the PHI node only contains a single non-phi value, if
9041 // so, scan to see if the phi cycle is actually equal to that value.
9042 {
9043 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9044 // Scan for the first non-phi operand.
9045 while (InValNo != NumOperandVals &&
9046 isa<PHINode>(PN.getIncomingValue(InValNo)))
9047 ++InValNo;
9048
9049 if (InValNo != NumOperandVals) {
9050 Value *NonPhiInVal = PN.getOperand(InValNo);
9051
9052 // Scan the rest of the operands to see if there are any conflicts, if so
9053 // there is no need to recursively scan other phis.
9054 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9055 Value *OpVal = PN.getIncomingValue(InValNo);
9056 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9057 break;
9058 }
9059
9060 // If we scanned over all operands, then we have one unique value plus
9061 // phi values. Scan PHI nodes to see if they all merge in each other or
9062 // the value.
9063 if (InValNo == NumOperandVals) {
9064 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9065 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9066 return ReplaceInstUsesWith(PN, NonPhiInVal);
9067 }
9068 }
9069 }
Chris Lattner60921c92003-12-19 05:58:40 +00009070 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009071}
9072
Reid Spencer17212df2006-12-12 09:18:51 +00009073static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9074 Instruction *InsertPoint,
9075 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009076 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9077 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009078 // We must cast correctly to the pointer type. Ensure that we
9079 // sign extend the integer value if it is smaller as this is
9080 // used for address computation.
9081 Instruction::CastOps opcode =
9082 (VTySize < PtrSize ? Instruction::SExt :
9083 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9084 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009085}
9086
Chris Lattnera1be5662002-05-02 17:06:02 +00009087
Chris Lattner7e708292002-06-25 16:13:24 +00009088Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009089 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009090 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009091 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009092 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009093 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009094
Chris Lattnere87597f2004-10-16 18:11:37 +00009095 if (isa<UndefValue>(GEP.getOperand(0)))
9096 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9097
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009098 bool HasZeroPointerIndex = false;
9099 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9100 HasZeroPointerIndex = C->isNullValue();
9101
9102 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009103 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009104
Chris Lattner28977af2004-04-05 01:30:19 +00009105 // Eliminate unneeded casts for indices.
9106 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009107
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009108 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009109 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009110 if (isa<SequentialType>(*GTI)) {
9111 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009112 if (CI->getOpcode() == Instruction::ZExt ||
9113 CI->getOpcode() == Instruction::SExt) {
9114 const Type *SrcTy = CI->getOperand(0)->getType();
9115 // We can eliminate a cast from i32 to i64 iff the target
9116 // is a 32-bit pointer target.
9117 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9118 MadeChange = true;
9119 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009120 }
9121 }
9122 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009123 // If we are using a wider index than needed for this platform, shrink it
9124 // to what we need. If the incoming value needs a cast instruction,
9125 // insert it. This explicit cast can make subsequent optimizations more
9126 // obvious.
9127 Value *Op = GEP.getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00009128 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Chris Lattner4f1134e2004-04-17 18:16:10 +00009129 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009130 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009131 MadeChange = true;
9132 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009133 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9134 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009135 GEP.setOperand(i, Op);
9136 MadeChange = true;
9137 }
Chris Lattner28977af2004-04-05 01:30:19 +00009138 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009139 }
Chris Lattner28977af2004-04-05 01:30:19 +00009140 if (MadeChange) return &GEP;
9141
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009142 // If this GEP instruction doesn't move the pointer, and if the input operand
9143 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9144 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009145 if (GEP.hasAllZeroIndices()) {
9146 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9147 // If the bitcast is of an allocation, and the allocation will be
9148 // converted to match the type of the cast, don't touch this.
9149 if (isa<AllocationInst>(BCI->getOperand(0))) {
9150 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009151 if (Instruction *I = visitBitCast(*BCI)) {
9152 if (I != BCI) {
9153 I->takeName(BCI);
9154 BCI->getParent()->getInstList().insert(BCI, I);
9155 ReplaceInstUsesWith(*BCI, I);
9156 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009157 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009158 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009159 }
9160 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9161 }
9162 }
9163
Chris Lattner90ac28c2002-08-02 19:29:35 +00009164 // Combine Indices - If the source pointer to this getelementptr instruction
9165 // is a getelementptr instruction, combine the indices of the two
9166 // getelementptr instructions into a single instruction.
9167 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009168 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009169 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009170 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009171
9172 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009173 // Note that if our source is a gep chain itself that we wait for that
9174 // chain to be resolved before we perform this transformation. This
9175 // avoids us creating a TON of code in some cases.
9176 //
9177 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9178 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9179 return 0; // Wait until our source is folded to completion.
9180
Chris Lattner72588fc2007-02-15 22:48:32 +00009181 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009182
9183 // Find out whether the last index in the source GEP is a sequential idx.
9184 bool EndsWithSequential = false;
9185 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9186 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009187 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009188
Chris Lattner90ac28c2002-08-02 19:29:35 +00009189 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009190 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009191 // Replace: gep (gep %P, long B), long A, ...
9192 // With: T = long A+B; gep %P, T, ...
9193 //
Chris Lattner620ce142004-05-07 22:09:22 +00009194 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009195 if (SO1 == Constant::getNullValue(SO1->getType())) {
9196 Sum = GO1;
9197 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9198 Sum = SO1;
9199 } else {
9200 // If they aren't the same type, convert both to an integer of the
9201 // target's pointer size.
9202 if (SO1->getType() != GO1->getType()) {
9203 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009204 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009205 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009206 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009207 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009208 unsigned PS = TD->getPointerSizeInBits();
9209 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009210 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009211 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009212
Duncan Sands514ab342007-11-01 20:53:16 +00009213 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009214 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009215 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009216 } else {
9217 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009218 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9219 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009220 }
9221 }
9222 }
Chris Lattner620ce142004-05-07 22:09:22 +00009223 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9224 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9225 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009226 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9227 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009228 }
Chris Lattner28977af2004-04-05 01:30:19 +00009229 }
Chris Lattner620ce142004-05-07 22:09:22 +00009230
9231 // Recycle the GEP we already have if possible.
9232 if (SrcGEPOperands.size() == 2) {
9233 GEP.setOperand(0, SrcGEPOperands[0]);
9234 GEP.setOperand(1, Sum);
9235 return &GEP;
9236 } else {
9237 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9238 SrcGEPOperands.end()-1);
9239 Indices.push_back(Sum);
9240 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9241 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009242 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009243 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009244 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009245 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009246 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9247 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009248 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9249 }
9250
9251 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009252 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9253 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009254
Chris Lattner620ce142004-05-07 22:09:22 +00009255 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009256 // GEP of global variable. If all of the indices for this GEP are
9257 // constants, we can promote this to a constexpr instead of an instruction.
9258
9259 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009260 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009261 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9262 for (; I != E && isa<Constant>(*I); ++I)
9263 Indices.push_back(cast<Constant>(*I));
9264
9265 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009266 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9267 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009268
9269 // Replace all uses of the GEP with the new constexpr...
9270 return ReplaceInstUsesWith(GEP, CE);
9271 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009272 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009273 if (!isa<PointerType>(X->getType())) {
9274 // Not interesting. Source pointer must be a cast from pointer.
9275 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009276 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9277 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009278 //
9279 // This occurs when the program declares an array extern like "int X[];"
9280 //
9281 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9282 const PointerType *XTy = cast<PointerType>(X->getType());
9283 if (const ArrayType *XATy =
9284 dyn_cast<ArrayType>(XTy->getElementType()))
9285 if (const ArrayType *CATy =
9286 dyn_cast<ArrayType>(CPTy->getElementType()))
9287 if (CATy->getElementType() == XATy->getElementType()) {
9288 // At this point, we know that the cast source type is a pointer
9289 // to an array of the same type as the destination pointer
9290 // array. Because the array type is never stepped over (there
9291 // is a leading zero) we can fold the cast into this GEP.
9292 GEP.setOperand(0, X);
9293 return &GEP;
9294 }
9295 } else if (GEP.getNumOperands() == 2) {
9296 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009297 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9298 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009299 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9300 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9301 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009302 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9303 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009304 Value *Idx[2];
9305 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9306 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009307 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009308 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009309 // V and GEP are both pointer types --> BitCast
9310 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009311 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009312
9313 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009314 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009315 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009316 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009317
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009318 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009319 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009320 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009321
9322 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9323 // allow either a mul, shift, or constant here.
9324 Value *NewIdx = 0;
9325 ConstantInt *Scale = 0;
9326 if (ArrayEltSize == 1) {
9327 NewIdx = GEP.getOperand(1);
9328 Scale = ConstantInt::get(NewIdx->getType(), 1);
9329 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009330 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009331 Scale = CI;
9332 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9333 if (Inst->getOpcode() == Instruction::Shl &&
9334 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009335 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9336 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9337 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009338 NewIdx = Inst->getOperand(0);
9339 } else if (Inst->getOpcode() == Instruction::Mul &&
9340 isa<ConstantInt>(Inst->getOperand(1))) {
9341 Scale = cast<ConstantInt>(Inst->getOperand(1));
9342 NewIdx = Inst->getOperand(0);
9343 }
9344 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009345
Chris Lattner7835cdd2005-09-13 18:36:04 +00009346 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009347 // out, perform the transformation. Note, we don't know whether Scale is
9348 // signed or not. We'll use unsigned version of division/modulo
9349 // operation after making sure Scale doesn't have the sign bit set.
9350 if (Scale && Scale->getSExtValue() >= 0LL &&
9351 Scale->getZExtValue() % ArrayEltSize == 0) {
9352 Scale = ConstantInt::get(Scale->getType(),
9353 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009354 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009355 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009356 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009357 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9358 NewIdx = InsertNewInstBefore(Sc, GEP);
9359 }
9360
9361 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009362 Value *Idx[2];
9363 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9364 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009365 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009366 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009367 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9368 // The NewGEP must be pointer typed, so must the old one -> BitCast
9369 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009370 }
9371 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009372 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009373 }
9374
Chris Lattner8a2a3112001-12-14 16:52:21 +00009375 return 0;
9376}
9377
Chris Lattner0864acf2002-11-04 16:18:53 +00009378Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9379 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9380 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009381 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9382 const Type *NewTy =
9383 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009384 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009385
9386 // Create and insert the replacement instruction...
9387 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009388 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009389 else {
9390 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009391 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009392 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009393
9394 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009395
Chris Lattner0864acf2002-11-04 16:18:53 +00009396 // Scan to the end of the allocation instructions, to skip over a block of
9397 // allocas if possible...
9398 //
9399 BasicBlock::iterator It = New;
9400 while (isa<AllocationInst>(*It)) ++It;
9401
9402 // Now that I is pointing to the first non-allocation-inst in the block,
9403 // insert our getelementptr instruction...
9404 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009405 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009406 Value *Idx[2];
9407 Idx[0] = NullIdx;
9408 Idx[1] = NullIdx;
9409 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009410 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009411
9412 // Now make everything use the getelementptr instead of the original
9413 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009414 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009415 } else if (isa<UndefValue>(AI.getArraySize())) {
9416 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009417 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009418
9419 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9420 // Note that we only do this for alloca's, because malloc should allocate and
9421 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009422 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009423 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009424 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9425
Chris Lattner0864acf2002-11-04 16:18:53 +00009426 return 0;
9427}
9428
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009429Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9430 Value *Op = FI.getOperand(0);
9431
Chris Lattner17be6352004-10-18 02:59:09 +00009432 // free undef -> unreachable.
9433 if (isa<UndefValue>(Op)) {
9434 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009435 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009436 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009437 return EraseInstFromFunction(FI);
9438 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009439
Chris Lattner6160e852004-02-28 04:57:37 +00009440 // If we have 'free null' delete the instruction. This can happen in stl code
9441 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009442 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009443 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009444
9445 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9446 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9447 FI.setOperand(0, CI->getOperand(0));
9448 return &FI;
9449 }
9450
9451 // Change free (gep X, 0,0,0,0) into free(X)
9452 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9453 if (GEPI->hasAllZeroIndices()) {
9454 AddToWorkList(GEPI);
9455 FI.setOperand(0, GEPI->getOperand(0));
9456 return &FI;
9457 }
9458 }
9459
9460 // Change free(malloc) into nothing, if the malloc has a single use.
9461 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9462 if (MI->hasOneUse()) {
9463 EraseInstFromFunction(FI);
9464 return EraseInstFromFunction(*MI);
9465 }
Chris Lattner6160e852004-02-28 04:57:37 +00009466
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009467 return 0;
9468}
9469
9470
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009471/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009472static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9473 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009474 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009475 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009476
Devang Patel99db6ad2007-10-18 19:52:32 +00009477 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9478 // Instead of loading constant c string, use corresponding integer value
9479 // directly if string length is small enough.
9480 const std::string &Str = CE->getOperand(0)->getStringValue();
9481 if (!Str.empty()) {
9482 unsigned len = Str.length();
9483 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9484 unsigned numBits = Ty->getPrimitiveSizeInBits();
9485 // Replace LI with immediate integer store.
9486 if ((numBits >> 3) == len + 1) {
9487 APInt StrVal(numBits, 0);
9488 APInt SingleChar(numBits, 0);
9489 if (TD->isLittleEndian()) {
9490 for (signed i = len-1; i >= 0; i--) {
9491 SingleChar = (uint64_t) Str[i];
9492 StrVal = (StrVal << 8) | SingleChar;
9493 }
9494 } else {
9495 for (unsigned i = 0; i < len; i++) {
9496 SingleChar = (uint64_t) Str[i];
9497 StrVal = (StrVal << 8) | SingleChar;
9498 }
9499 // Append NULL at the end.
9500 SingleChar = 0;
9501 StrVal = (StrVal << 8) | SingleChar;
9502 }
9503 Value *NL = ConstantInt::get(StrVal);
9504 return IC.ReplaceInstUsesWith(LI, NL);
9505 }
9506 }
9507 }
9508
Chris Lattnerb89e0712004-07-13 01:49:43 +00009509 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009510 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009511 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009512
Reid Spencer42230162007-01-22 05:51:25 +00009513 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009514 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009515 // If the source is an array, the code below will not succeed. Check to
9516 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9517 // constants.
9518 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9519 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9520 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009521 Value *Idxs[2];
9522 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9523 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009524 SrcTy = cast<PointerType>(CastOp->getType());
9525 SrcPTy = SrcTy->getElementType();
9526 }
9527
Reid Spencer42230162007-01-22 05:51:25 +00009528 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009529 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009530 // Do not allow turning this into a load of an integer, which is then
9531 // casted to a pointer, this pessimizes pointer analysis a lot.
9532 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009533 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9534 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009535
Chris Lattnerf9527852005-01-31 04:50:46 +00009536 // Okay, we are casting from one integer or pointer type to another of
9537 // the same size. Instead of casting the pointer before the load, cast
9538 // the result of the loaded value.
9539 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9540 CI->getName(),
9541 LI.isVolatile()),LI);
9542 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009543 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009544 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009545 }
9546 }
9547 return 0;
9548}
9549
Chris Lattnerc10aced2004-09-19 18:43:46 +00009550/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009551/// from this value cannot trap. If it is not obviously safe to load from the
9552/// specified pointer, we do a quick local scan of the basic block containing
9553/// ScanFrom, to determine if the address is already accessed.
9554static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009555 // If it is an alloca it is always safe to load from.
9556 if (isa<AllocaInst>(V)) return true;
9557
Duncan Sands46318cd2007-09-19 10:25:38 +00009558 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009559 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009560 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009561 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009562
9563 // Otherwise, be a little bit agressive by scanning the local block where we
9564 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009565 // from/to. If so, the previous load or store would have already trapped,
9566 // so there is no harm doing an extra load (also, CSE will later eliminate
9567 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009568 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9569
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009570 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009571 --BBI;
9572
9573 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9574 if (LI->getOperand(0) == V) return true;
9575 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9576 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009577
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009578 }
Chris Lattner8a375202004-09-19 19:18:10 +00009579 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009580}
9581
Chris Lattner8d2e8882007-08-11 18:48:48 +00009582/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9583/// until we find the underlying object a pointer is referring to or something
9584/// we don't understand. Note that the returned pointer may be offset from the
9585/// input, because we ignore GEP indices.
9586static Value *GetUnderlyingObject(Value *Ptr) {
9587 while (1) {
9588 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9589 if (CE->getOpcode() == Instruction::BitCast ||
9590 CE->getOpcode() == Instruction::GetElementPtr)
9591 Ptr = CE->getOperand(0);
9592 else
9593 return Ptr;
9594 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9595 Ptr = BCI->getOperand(0);
9596 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9597 Ptr = GEP->getOperand(0);
9598 } else {
9599 return Ptr;
9600 }
9601 }
9602}
9603
Chris Lattner833b8a42003-06-26 05:06:25 +00009604Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9605 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009606
Dan Gohman9941f742007-07-20 16:34:21 +00009607 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009608 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009609 if (KnownAlign > LI.getAlignment())
9610 LI.setAlignment(KnownAlign);
9611
Chris Lattner37366c12005-05-01 04:24:53 +00009612 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009613 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009614 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009615 return Res;
9616
9617 // None of the following transforms are legal for volatile loads.
9618 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009619
Chris Lattner62f254d2005-09-12 22:00:15 +00009620 if (&LI.getParent()->front() != &LI) {
9621 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009622 // If the instruction immediately before this is a store to the same
9623 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009624 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9625 if (SI->getOperand(1) == LI.getOperand(0))
9626 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009627 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9628 if (LIB->getOperand(0) == LI.getOperand(0))
9629 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009630 }
Chris Lattner37366c12005-05-01 04:24:53 +00009631
Christopher Lambb15147e2007-12-29 07:56:53 +00009632 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9633 const Value *GEPI0 = GEPI->getOperand(0);
9634 // TODO: Consider a target hook for valid address spaces for this xform.
9635 if (isa<ConstantPointerNull>(GEPI0) &&
9636 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009637 // Insert a new store to null instruction before the load to indicate
9638 // that this code is not reachable. We do this instead of inserting
9639 // an unreachable instruction directly because we cannot modify the
9640 // CFG.
9641 new StoreInst(UndefValue::get(LI.getType()),
9642 Constant::getNullValue(Op->getType()), &LI);
9643 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9644 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009645 }
Chris Lattner37366c12005-05-01 04:24:53 +00009646
Chris Lattnere87597f2004-10-16 18:11:37 +00009647 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009648 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009649 // TODO: Consider a target hook for valid address spaces for this xform.
9650 if (isa<UndefValue>(C) || (C->isNullValue() &&
9651 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009652 // Insert a new store to null instruction before the load to indicate that
9653 // this code is not reachable. We do this instead of inserting an
9654 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009655 new StoreInst(UndefValue::get(LI.getType()),
9656 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009657 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009658 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009659
Chris Lattnere87597f2004-10-16 18:11:37 +00009660 // Instcombine load (constant global) into the value loaded.
9661 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009662 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009663 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009664
Chris Lattnere87597f2004-10-16 18:11:37 +00009665 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9666 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9667 if (CE->getOpcode() == Instruction::GetElementPtr) {
9668 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009669 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009670 if (Constant *V =
9671 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009672 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009673 if (CE->getOperand(0)->isNullValue()) {
9674 // Insert a new store to null instruction before the load to indicate
9675 // that this code is not reachable. We do this instead of inserting
9676 // an unreachable instruction directly because we cannot modify the
9677 // CFG.
9678 new StoreInst(UndefValue::get(LI.getType()),
9679 Constant::getNullValue(Op->getType()), &LI);
9680 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9681 }
9682
Reid Spencer3da59db2006-11-27 01:05:10 +00009683 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009684 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009685 return Res;
9686 }
9687 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009688
9689 // If this load comes from anywhere in a constant global, and if the global
9690 // is all undef or zero, we know what it loads.
9691 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9692 if (GV->isConstant() && GV->hasInitializer()) {
9693 if (GV->getInitializer()->isNullValue())
9694 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9695 else if (isa<UndefValue>(GV->getInitializer()))
9696 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9697 }
9698 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009699
Chris Lattner37366c12005-05-01 04:24:53 +00009700 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009701 // Change select and PHI nodes to select values instead of addresses: this
9702 // helps alias analysis out a lot, allows many others simplifications, and
9703 // exposes redundancy in the code.
9704 //
9705 // Note that we cannot do the transformation unless we know that the
9706 // introduced loads cannot trap! Something like this is valid as long as
9707 // the condition is always false: load (select bool %C, int* null, int* %G),
9708 // but it would not be valid if we transformed it to load from null
9709 // unconditionally.
9710 //
9711 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9712 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009713 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9714 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009715 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009716 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009717 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009718 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009719 return new SelectInst(SI->getCondition(), V1, V2);
9720 }
9721
Chris Lattner684fe212004-09-23 15:46:00 +00009722 // load (select (cond, null, P)) -> load P
9723 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9724 if (C->isNullValue()) {
9725 LI.setOperand(0, SI->getOperand(2));
9726 return &LI;
9727 }
9728
9729 // load (select (cond, P, null)) -> load P
9730 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9731 if (C->isNullValue()) {
9732 LI.setOperand(0, SI->getOperand(1));
9733 return &LI;
9734 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009735 }
9736 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009737 return 0;
9738}
9739
Reid Spencer55af2b52007-01-19 21:20:31 +00009740/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009741/// when possible.
9742static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9743 User *CI = cast<User>(SI.getOperand(1));
9744 Value *CastOp = CI->getOperand(0);
9745
9746 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9747 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9748 const Type *SrcPTy = SrcTy->getElementType();
9749
Reid Spencer42230162007-01-22 05:51:25 +00009750 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009751 // If the source is an array, the code below will not succeed. Check to
9752 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9753 // constants.
9754 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9755 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9756 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009757 Value* Idxs[2];
9758 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9759 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009760 SrcTy = cast<PointerType>(CastOp->getType());
9761 SrcPTy = SrcTy->getElementType();
9762 }
9763
Reid Spencer67f827c2007-01-20 23:35:48 +00009764 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9765 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9766 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009767
9768 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009769 // the same size. Instead of casting the pointer before
9770 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009771 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009772 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009773 Instruction::CastOps opcode = Instruction::BitCast;
9774 const Type* CastSrcTy = SIOp0->getType();
9775 const Type* CastDstTy = SrcPTy;
9776 if (isa<PointerType>(CastDstTy)) {
9777 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009778 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009779 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009780 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009781 opcode = Instruction::PtrToInt;
9782 }
9783 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009784 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009785 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009786 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009787 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9788 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009789 return new StoreInst(NewCast, CastOp);
9790 }
9791 }
9792 }
9793 return 0;
9794}
9795
Chris Lattner2f503e62005-01-31 05:36:43 +00009796Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9797 Value *Val = SI.getOperand(0);
9798 Value *Ptr = SI.getOperand(1);
9799
9800 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009801 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009802 ++NumCombined;
9803 return 0;
9804 }
Chris Lattner836692d2007-01-15 06:51:56 +00009805
9806 // If the RHS is an alloca with a single use, zapify the store, making the
9807 // alloca dead.
9808 if (Ptr->hasOneUse()) {
9809 if (isa<AllocaInst>(Ptr)) {
9810 EraseInstFromFunction(SI);
9811 ++NumCombined;
9812 return 0;
9813 }
9814
9815 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9816 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9817 GEP->getOperand(0)->hasOneUse()) {
9818 EraseInstFromFunction(SI);
9819 ++NumCombined;
9820 return 0;
9821 }
9822 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009823
Dan Gohman9941f742007-07-20 16:34:21 +00009824 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009825 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009826 if (KnownAlign > SI.getAlignment())
9827 SI.setAlignment(KnownAlign);
9828
Chris Lattner9ca96412006-02-08 03:25:32 +00009829 // Do really simple DSE, to catch cases where there are several consequtive
9830 // stores to the same location, separated by a few arithmetic operations. This
9831 // situation often occurs with bitfield accesses.
9832 BasicBlock::iterator BBI = &SI;
9833 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9834 --ScanInsts) {
9835 --BBI;
9836
9837 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9838 // Prev store isn't volatile, and stores to the same location?
9839 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9840 ++NumDeadStore;
9841 ++BBI;
9842 EraseInstFromFunction(*PrevSI);
9843 continue;
9844 }
9845 break;
9846 }
9847
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009848 // If this is a load, we have to stop. However, if the loaded value is from
9849 // the pointer we're loading and is producing the pointer we're storing,
9850 // then *this* store is dead (X = load P; store X -> P).
9851 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009852 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009853 EraseInstFromFunction(SI);
9854 ++NumCombined;
9855 return 0;
9856 }
9857 // Otherwise, this is a load from some other location. Stores before it
9858 // may not be dead.
9859 break;
9860 }
9861
Chris Lattner9ca96412006-02-08 03:25:32 +00009862 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009863 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009864 break;
9865 }
9866
9867
9868 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009869
9870 // store X, null -> turns into 'unreachable' in SimplifyCFG
9871 if (isa<ConstantPointerNull>(Ptr)) {
9872 if (!isa<UndefValue>(Val)) {
9873 SI.setOperand(0, UndefValue::get(Val->getType()));
9874 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009875 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009876 ++NumCombined;
9877 }
9878 return 0; // Do not modify these!
9879 }
9880
9881 // store undef, Ptr -> noop
9882 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009883 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009884 ++NumCombined;
9885 return 0;
9886 }
9887
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009888 // If the pointer destination is a cast, see if we can fold the cast into the
9889 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009890 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009891 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9892 return Res;
9893 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009894 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009895 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9896 return Res;
9897
Chris Lattner408902b2005-09-12 23:23:25 +00009898
9899 // If this store is the last instruction in the basic block, and if the block
9900 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009901 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009902 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009903 if (BI->isUnconditional())
9904 if (SimplifyStoreAtEndOfBlock(SI))
9905 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009906
Chris Lattner2f503e62005-01-31 05:36:43 +00009907 return 0;
9908}
9909
Chris Lattner3284d1f2007-04-15 00:07:55 +00009910/// SimplifyStoreAtEndOfBlock - Turn things like:
9911/// if () { *P = v1; } else { *P = v2 }
9912/// into a phi node with a store in the successor.
9913///
Chris Lattner31755a02007-04-15 01:02:18 +00009914/// Simplify things like:
9915/// *P = v1; if () { *P = v2; }
9916/// into a phi node with a store in the successor.
9917///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009918bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9919 BasicBlock *StoreBB = SI.getParent();
9920
9921 // Check to see if the successor block has exactly two incoming edges. If
9922 // so, see if the other predecessor contains a store to the same location.
9923 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009924 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009925
9926 // Determine whether Dest has exactly two predecessors and, if so, compute
9927 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009928 pred_iterator PI = pred_begin(DestBB);
9929 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009930 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009931 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009932 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009933 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009934 return false;
9935
9936 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009937 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009938 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009939 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009940 }
Chris Lattner31755a02007-04-15 01:02:18 +00009941 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009942 return false;
9943
9944
Chris Lattner31755a02007-04-15 01:02:18 +00009945 // Verify that the other block ends in a branch and is not otherwise empty.
9946 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009947 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009948 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009949 return false;
9950
Chris Lattner31755a02007-04-15 01:02:18 +00009951 // If the other block ends in an unconditional branch, check for the 'if then
9952 // else' case. there is an instruction before the branch.
9953 StoreInst *OtherStore = 0;
9954 if (OtherBr->isUnconditional()) {
9955 // If this isn't a store, or isn't a store to the same location, bail out.
9956 --BBI;
9957 OtherStore = dyn_cast<StoreInst>(BBI);
9958 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9959 return false;
9960 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009961 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009962 // destinations is StoreBB, then we have the if/then case.
9963 if (OtherBr->getSuccessor(0) != StoreBB &&
9964 OtherBr->getSuccessor(1) != StoreBB)
9965 return false;
9966
9967 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009968 // if/then triangle. See if there is a store to the same ptr as SI that
9969 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009970 for (;; --BBI) {
9971 // Check to see if we find the matching store.
9972 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9973 if (OtherStore->getOperand(1) != SI.getOperand(1))
9974 return false;
9975 break;
9976 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009977 // If we find something that may be using the stored value, or if we run
9978 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009979 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9980 BBI == OtherBB->begin())
9981 return false;
9982 }
9983
9984 // In order to eliminate the store in OtherBr, we have to
9985 // make sure nothing reads the stored value in StoreBB.
9986 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9987 // FIXME: This should really be AA driven.
9988 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9989 return false;
9990 }
9991 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009992
Chris Lattner31755a02007-04-15 01:02:18 +00009993 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009994 Value *MergedVal = OtherStore->getOperand(0);
9995 if (MergedVal != SI.getOperand(0)) {
9996 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9997 PN->reserveOperandSpace(2);
9998 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009999 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10000 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010001 }
10002
10003 // Advance to a place where it is safe to insert the new store and
10004 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010005 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010006 while (isa<PHINode>(BBI)) ++BBI;
10007 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10008 OtherStore->isVolatile()), *BBI);
10009
10010 // Nuke the old stores.
10011 EraseInstFromFunction(SI);
10012 EraseInstFromFunction(*OtherStore);
10013 ++NumCombined;
10014 return true;
10015}
10016
Chris Lattner2f503e62005-01-31 05:36:43 +000010017
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010018Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10019 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010020 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010021 BasicBlock *TrueDest;
10022 BasicBlock *FalseDest;
10023 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10024 !isa<Constant>(X)) {
10025 // Swap Destinations and condition...
10026 BI.setCondition(X);
10027 BI.setSuccessor(0, FalseDest);
10028 BI.setSuccessor(1, TrueDest);
10029 return &BI;
10030 }
10031
Reid Spencere4d87aa2006-12-23 06:05:41 +000010032 // Cannonicalize fcmp_one -> fcmp_oeq
10033 FCmpInst::Predicate FPred; Value *Y;
10034 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10035 TrueDest, FalseDest)))
10036 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10037 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10038 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010039 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010040 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10041 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010042 // Swap Destinations and condition...
10043 BI.setCondition(NewSCC);
10044 BI.setSuccessor(0, FalseDest);
10045 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010046 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010047 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010048 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010049 return &BI;
10050 }
10051
10052 // Cannonicalize icmp_ne -> icmp_eq
10053 ICmpInst::Predicate IPred;
10054 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10055 TrueDest, FalseDest)))
10056 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10057 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10058 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10059 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010060 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010061 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10062 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010063 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010064 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010065 BI.setSuccessor(0, FalseDest);
10066 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010067 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010068 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010069 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010070 return &BI;
10071 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010072
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010073 return 0;
10074}
Chris Lattner0864acf2002-11-04 16:18:53 +000010075
Chris Lattner46238a62004-07-03 00:26:11 +000010076Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10077 Value *Cond = SI.getCondition();
10078 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10079 if (I->getOpcode() == Instruction::Add)
10080 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10081 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10082 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010083 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010084 AddRHS));
10085 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010086 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010087 return &SI;
10088 }
10089 }
10090 return 0;
10091}
10092
Chris Lattner220b0cf2006-03-05 00:22:33 +000010093/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10094/// is to leave as a vector operation.
10095static bool CheapToScalarize(Value *V, bool isConstant) {
10096 if (isa<ConstantAggregateZero>(V))
10097 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010098 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010099 if (isConstant) return true;
10100 // If all elts are the same, we can extract.
10101 Constant *Op0 = C->getOperand(0);
10102 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10103 if (C->getOperand(i) != Op0)
10104 return false;
10105 return true;
10106 }
10107 Instruction *I = dyn_cast<Instruction>(V);
10108 if (!I) return false;
10109
10110 // Insert element gets simplified to the inserted element or is deleted if
10111 // this is constant idx extract element and its a constant idx insertelt.
10112 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10113 isa<ConstantInt>(I->getOperand(2)))
10114 return true;
10115 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10116 return true;
10117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10118 if (BO->hasOneUse() &&
10119 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10120 CheapToScalarize(BO->getOperand(1), isConstant)))
10121 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010122 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10123 if (CI->hasOneUse() &&
10124 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10125 CheapToScalarize(CI->getOperand(1), isConstant)))
10126 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010127
10128 return false;
10129}
10130
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010131/// Read and decode a shufflevector mask.
10132///
10133/// It turns undef elements into values that are larger than the number of
10134/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010135static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10136 unsigned NElts = SVI->getType()->getNumElements();
10137 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10138 return std::vector<unsigned>(NElts, 0);
10139 if (isa<UndefValue>(SVI->getOperand(2)))
10140 return std::vector<unsigned>(NElts, 2*NElts);
10141
10142 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010143 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010144 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10145 if (isa<UndefValue>(CP->getOperand(i)))
10146 Result.push_back(NElts*2); // undef -> 8
10147 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010148 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010149 return Result;
10150}
10151
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010152/// FindScalarElement - Given a vector and an element number, see if the scalar
10153/// value is already around as a register, for example if it were inserted then
10154/// extracted from the vector.
10155static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010156 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10157 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010158 unsigned Width = PTy->getNumElements();
10159 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010160 return UndefValue::get(PTy->getElementType());
10161
10162 if (isa<UndefValue>(V))
10163 return UndefValue::get(PTy->getElementType());
10164 else if (isa<ConstantAggregateZero>(V))
10165 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010166 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010167 return CP->getOperand(EltNo);
10168 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10169 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010170 if (!isa<ConstantInt>(III->getOperand(2)))
10171 return 0;
10172 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010173
10174 // If this is an insert to the element we are looking for, return the
10175 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010176 if (EltNo == IIElt)
10177 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010178
10179 // Otherwise, the insertelement doesn't modify the value, recurse on its
10180 // vector input.
10181 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010182 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010183 unsigned InEl = getShuffleMask(SVI)[EltNo];
10184 if (InEl < Width)
10185 return FindScalarElement(SVI->getOperand(0), InEl);
10186 else if (InEl < Width*2)
10187 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10188 else
10189 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010190 }
10191
10192 // Otherwise, we don't know.
10193 return 0;
10194}
10195
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010196Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010197
Dan Gohman07a96762007-07-16 14:29:03 +000010198 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010199 if (isa<UndefValue>(EI.getOperand(0)))
10200 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10201
Dan Gohman07a96762007-07-16 14:29:03 +000010202 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010203 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10204 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10205
Reid Spencer9d6565a2007-02-15 02:26:10 +000010206 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010207 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010208 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010209 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010210 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010211 if (C->getOperand(i) != op0) {
10212 op0 = 0;
10213 break;
10214 }
10215 if (op0)
10216 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010217 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010218
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010219 // If extracting a specified index from the vector, see if we can recursively
10220 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010221 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010222 unsigned IndexVal = IdxC->getZExtValue();
10223 unsigned VectorWidth =
10224 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10225
10226 // If this is extracting an invalid index, turn this into undef, to avoid
10227 // crashing the code below.
10228 if (IndexVal >= VectorWidth)
10229 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10230
Chris Lattner867b99f2006-10-05 06:55:50 +000010231 // This instruction only demands the single element from the input vector.
10232 // If the input vector has a single use, simplify it based on this use
10233 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010234 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010235 uint64_t UndefElts;
10236 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010237 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010238 UndefElts)) {
10239 EI.setOperand(0, V);
10240 return &EI;
10241 }
10242 }
10243
Reid Spencerb83eb642006-10-20 07:07:24 +000010244 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010245 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010246
10247 // If the this extractelement is directly using a bitcast from a vector of
10248 // the same number of elements, see if we can find the source element from
10249 // it. In this case, we will end up needing to bitcast the scalars.
10250 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10251 if (const VectorType *VT =
10252 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10253 if (VT->getNumElements() == VectorWidth)
10254 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10255 return new BitCastInst(Elt, EI.getType());
10256 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010257 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010258
Chris Lattner73fa49d2006-05-25 22:53:38 +000010259 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010260 if (I->hasOneUse()) {
10261 // Push extractelement into predecessor operation if legal and
10262 // profitable to do so
10263 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010264 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10265 if (CheapToScalarize(BO, isConstantElt)) {
10266 ExtractElementInst *newEI0 =
10267 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10268 EI.getName()+".lhs");
10269 ExtractElementInst *newEI1 =
10270 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10271 EI.getName()+".rhs");
10272 InsertNewInstBefore(newEI0, EI);
10273 InsertNewInstBefore(newEI1, EI);
10274 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10275 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010276 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010277 unsigned AS =
10278 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010279 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10280 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010281 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010282 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010283 InsertNewInstBefore(GEP, EI);
10284 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010285 }
10286 }
10287 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10288 // Extracting the inserted element?
10289 if (IE->getOperand(2) == EI.getOperand(1))
10290 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10291 // If the inserted and extracted elements are constants, they must not
10292 // be the same value, extract from the pre-inserted value instead.
10293 if (isa<Constant>(IE->getOperand(2)) &&
10294 isa<Constant>(EI.getOperand(1))) {
10295 AddUsesToWorkList(EI);
10296 EI.setOperand(0, IE->getOperand(0));
10297 return &EI;
10298 }
10299 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10300 // If this is extracting an element from a shufflevector, figure out where
10301 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010302 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10303 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010304 Value *Src;
10305 if (SrcIdx < SVI->getType()->getNumElements())
10306 Src = SVI->getOperand(0);
10307 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10308 SrcIdx -= SVI->getType()->getNumElements();
10309 Src = SVI->getOperand(1);
10310 } else {
10311 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010312 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010313 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010314 }
10315 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010316 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010317 return 0;
10318}
10319
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010320/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10321/// elements from either LHS or RHS, return the shuffle mask and true.
10322/// Otherwise, return false.
10323static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10324 std::vector<Constant*> &Mask) {
10325 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10326 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010327 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010328
10329 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010330 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010331 return true;
10332 } else if (V == LHS) {
10333 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010334 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010335 return true;
10336 } else if (V == RHS) {
10337 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010338 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010339 return true;
10340 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10341 // If this is an insert of an extract from some other vector, include it.
10342 Value *VecOp = IEI->getOperand(0);
10343 Value *ScalarOp = IEI->getOperand(1);
10344 Value *IdxOp = IEI->getOperand(2);
10345
Chris Lattnerd929f062006-04-27 21:14:21 +000010346 if (!isa<ConstantInt>(IdxOp))
10347 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010348 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010349
10350 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10351 // Okay, we can handle this if the vector we are insertinting into is
10352 // transitively ok.
10353 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10354 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010355 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010356 return true;
10357 }
10358 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10359 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010360 EI->getOperand(0)->getType() == V->getType()) {
10361 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010362 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010363
10364 // This must be extracting from either LHS or RHS.
10365 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10366 // Okay, we can handle this if the vector we are insertinting into is
10367 // transitively ok.
10368 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10369 // If so, update the mask to reflect the inserted value.
10370 if (EI->getOperand(0) == LHS) {
10371 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010372 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010373 } else {
10374 assert(EI->getOperand(0) == RHS);
10375 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010376 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010377
10378 }
10379 return true;
10380 }
10381 }
10382 }
10383 }
10384 }
10385 // TODO: Handle shufflevector here!
10386
10387 return false;
10388}
10389
10390/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10391/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10392/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010393static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010394 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010395 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010396 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010397 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010398 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010399
10400 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010401 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010402 return V;
10403 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010404 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010405 return V;
10406 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10407 // If this is an insert of an extract from some other vector, include it.
10408 Value *VecOp = IEI->getOperand(0);
10409 Value *ScalarOp = IEI->getOperand(1);
10410 Value *IdxOp = IEI->getOperand(2);
10411
10412 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10413 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10414 EI->getOperand(0)->getType() == V->getType()) {
10415 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010416 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10417 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010418
10419 // Either the extracted from or inserted into vector must be RHSVec,
10420 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010421 if (EI->getOperand(0) == RHS || RHS == 0) {
10422 RHS = EI->getOperand(0);
10423 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010424 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010425 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010426 return V;
10427 }
10428
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010429 if (VecOp == RHS) {
10430 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010431 // Everything but the extracted element is replaced with the RHS.
10432 for (unsigned i = 0; i != NumElts; ++i) {
10433 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010434 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010435 }
10436 return V;
10437 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010438
10439 // If this insertelement is a chain that comes from exactly these two
10440 // vectors, return the vector and the effective shuffle.
10441 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10442 return EI->getOperand(0);
10443
Chris Lattnerefb47352006-04-15 01:39:45 +000010444 }
10445 }
10446 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010447 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010448
10449 // Otherwise, can't do anything fancy. Return an identity vector.
10450 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010451 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010452 return V;
10453}
10454
10455Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10456 Value *VecOp = IE.getOperand(0);
10457 Value *ScalarOp = IE.getOperand(1);
10458 Value *IdxOp = IE.getOperand(2);
10459
Chris Lattner599ded12007-04-09 01:11:16 +000010460 // Inserting an undef or into an undefined place, remove this.
10461 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10462 ReplaceInstUsesWith(IE, VecOp);
10463
Chris Lattnerefb47352006-04-15 01:39:45 +000010464 // If the inserted element was extracted from some other vector, and if the
10465 // indexes are constant, try to turn this into a shufflevector operation.
10466 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10467 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10468 EI->getOperand(0)->getType() == IE.getType()) {
10469 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010470 unsigned ExtractedIdx =
10471 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010472 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010473
10474 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10475 return ReplaceInstUsesWith(IE, VecOp);
10476
10477 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10478 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10479
10480 // If we are extracting a value from a vector, then inserting it right
10481 // back into the same place, just use the input vector.
10482 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10483 return ReplaceInstUsesWith(IE, VecOp);
10484
10485 // We could theoretically do this for ANY input. However, doing so could
10486 // turn chains of insertelement instructions into a chain of shufflevector
10487 // instructions, and right now we do not merge shufflevectors. As such,
10488 // only do this in a situation where it is clear that there is benefit.
10489 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10490 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10491 // the values of VecOp, except then one read from EIOp0.
10492 // Build a new shuffle mask.
10493 std::vector<Constant*> Mask;
10494 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010495 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010496 else {
10497 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010498 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010499 NumVectorElts));
10500 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010501 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010502 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010503 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010504 }
10505
10506 // If this insertelement isn't used by some other insertelement, turn it
10507 // (and any insertelements it points to), into one big shuffle.
10508 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10509 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010510 Value *RHS = 0;
10511 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10512 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10513 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010514 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010515 }
10516 }
10517 }
10518
10519 return 0;
10520}
10521
10522
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010523Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10524 Value *LHS = SVI.getOperand(0);
10525 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010526 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010527
10528 bool MadeChange = false;
10529
Chris Lattner867b99f2006-10-05 06:55:50 +000010530 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010531 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010532 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10533
Chris Lattnere4929dd2007-01-05 07:36:08 +000010534 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010535 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010536 if (isa<UndefValue>(SVI.getOperand(1))) {
10537 // Scan to see if there are any references to the RHS. If so, replace them
10538 // with undef element refs and set MadeChange to true.
10539 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10540 if (Mask[i] >= e && Mask[i] != 2*e) {
10541 Mask[i] = 2*e;
10542 MadeChange = true;
10543 }
10544 }
10545
10546 if (MadeChange) {
10547 // Remap any references to RHS to use LHS.
10548 std::vector<Constant*> Elts;
10549 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10550 if (Mask[i] == 2*e)
10551 Elts.push_back(UndefValue::get(Type::Int32Ty));
10552 else
10553 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10554 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010555 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010556 }
10557 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010558
Chris Lattner863bcff2006-05-25 23:48:38 +000010559 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10560 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10561 if (LHS == RHS || isa<UndefValue>(LHS)) {
10562 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010563 // shuffle(undef,undef,mask) -> undef.
10564 return ReplaceInstUsesWith(SVI, LHS);
10565 }
10566
Chris Lattner863bcff2006-05-25 23:48:38 +000010567 // Remap any references to RHS to use LHS.
10568 std::vector<Constant*> Elts;
10569 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010570 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010571 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010572 else {
10573 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10574 (Mask[i] < e && isa<UndefValue>(LHS)))
10575 Mask[i] = 2*e; // Turn into undef.
10576 else
10577 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010578 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010579 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010580 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010581 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010582 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010583 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010584 LHS = SVI.getOperand(0);
10585 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010586 MadeChange = true;
10587 }
10588
Chris Lattner7b2e27922006-05-26 00:29:06 +000010589 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010590 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010591
Chris Lattner863bcff2006-05-25 23:48:38 +000010592 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10593 if (Mask[i] >= e*2) continue; // Ignore undef values.
10594 // Is this an identity shuffle of the LHS value?
10595 isLHSID &= (Mask[i] == i);
10596
10597 // Is this an identity shuffle of the RHS value?
10598 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010599 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010600
Chris Lattner863bcff2006-05-25 23:48:38 +000010601 // Eliminate identity shuffles.
10602 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10603 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010604
Chris Lattner7b2e27922006-05-26 00:29:06 +000010605 // If the LHS is a shufflevector itself, see if we can combine it with this
10606 // one without producing an unusual shuffle. Here we are really conservative:
10607 // we are absolutely afraid of producing a shuffle mask not in the input
10608 // program, because the code gen may not be smart enough to turn a merged
10609 // shuffle into two specific shuffles: it may produce worse code. As such,
10610 // we only merge two shuffles if the result is one of the two input shuffle
10611 // masks. In this case, merging the shuffles just removes one instruction,
10612 // which we know is safe. This is good for things like turning:
10613 // (splat(splat)) -> splat.
10614 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10615 if (isa<UndefValue>(RHS)) {
10616 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10617
10618 std::vector<unsigned> NewMask;
10619 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10620 if (Mask[i] >= 2*e)
10621 NewMask.push_back(2*e);
10622 else
10623 NewMask.push_back(LHSMask[Mask[i]]);
10624
10625 // If the result mask is equal to the src shuffle or this shuffle mask, do
10626 // the replacement.
10627 if (NewMask == LHSMask || NewMask == Mask) {
10628 std::vector<Constant*> Elts;
10629 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10630 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010631 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010632 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010633 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010634 }
10635 }
10636 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10637 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010638 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010639 }
10640 }
10641 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010642
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010643 return MadeChange ? &SVI : 0;
10644}
10645
10646
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010647
Chris Lattnerea1c4542004-12-08 23:43:58 +000010648
10649/// TryToSinkInstruction - Try to move the specified instruction from its
10650/// current block into the beginning of DestBlock, which can only happen if it's
10651/// safe to move the instruction past all of the instructions between it and the
10652/// end of its block.
10653static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10654 assert(I->hasOneUse() && "Invariants didn't hold!");
10655
Chris Lattner108e9022005-10-27 17:13:11 +000010656 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10657 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010658
Chris Lattnerea1c4542004-12-08 23:43:58 +000010659 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010660 if (isa<AllocaInst>(I) && I->getParent() ==
10661 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010662 return false;
10663
Chris Lattner96a52a62004-12-09 07:14:34 +000010664 // We can only sink load instructions if there is nothing between the load and
10665 // the end of block that could change the value.
10666 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010667 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10668 Scan != E; ++Scan)
10669 if (Scan->mayWriteToMemory())
10670 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010671 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010672
10673 BasicBlock::iterator InsertPos = DestBlock->begin();
10674 while (isa<PHINode>(InsertPos)) ++InsertPos;
10675
Chris Lattner4bc5f802005-08-08 19:11:57 +000010676 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010677 ++NumSunkInst;
10678 return true;
10679}
10680
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010681
10682/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10683/// all reachable code to the worklist.
10684///
10685/// This has a couple of tricks to make the code faster and more powerful. In
10686/// particular, we constant fold and DCE instructions as we go, to avoid adding
10687/// them to the worklist (this significantly speeds up instcombine on code where
10688/// many instructions are dead or constant). Additionally, if we find a branch
10689/// whose condition is a known constant, we only visit the reachable successors.
10690///
10691static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010692 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010693 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010694 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010695 std::vector<BasicBlock*> Worklist;
10696 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010697
Chris Lattner2c7718a2007-03-23 19:17:18 +000010698 while (!Worklist.empty()) {
10699 BB = Worklist.back();
10700 Worklist.pop_back();
10701
10702 // We have now visited this block! If we've already been here, ignore it.
10703 if (!Visited.insert(BB)) continue;
10704
10705 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10706 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010707
Chris Lattner2c7718a2007-03-23 19:17:18 +000010708 // DCE instruction if trivially dead.
10709 if (isInstructionTriviallyDead(Inst)) {
10710 ++NumDeadInst;
10711 DOUT << "IC: DCE: " << *Inst;
10712 Inst->eraseFromParent();
10713 continue;
10714 }
10715
10716 // ConstantProp instruction if trivially constant.
10717 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10718 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10719 Inst->replaceAllUsesWith(C);
10720 ++NumConstProp;
10721 Inst->eraseFromParent();
10722 continue;
10723 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010724
Chris Lattner2c7718a2007-03-23 19:17:18 +000010725 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010726 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010727
10728 // Recursively visit successors. If this is a branch or switch on a
10729 // constant, only visit the reachable successor.
10730 TerminatorInst *TI = BB->getTerminator();
10731 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10732 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10733 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10734 Worklist.push_back(BI->getSuccessor(!CondVal));
10735 continue;
10736 }
10737 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10738 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10739 // See if this is an explicit destination.
10740 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10741 if (SI->getCaseValue(i) == Cond) {
10742 Worklist.push_back(SI->getSuccessor(i));
10743 continue;
10744 }
10745
10746 // Otherwise it is the default destination.
10747 Worklist.push_back(SI->getSuccessor(0));
10748 continue;
10749 }
10750 }
10751
10752 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10753 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010754 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010755}
10756
Chris Lattnerec9c3582007-03-03 02:04:50 +000010757bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010758 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010759 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010760
10761 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10762 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010763
Chris Lattnerb3d59702005-07-07 20:40:38 +000010764 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010765 // Do a depth-first traversal of the function, populate the worklist with
10766 // the reachable instructions. Ignore blocks that are not reachable. Keep
10767 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010768 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010769 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010770
Chris Lattnerb3d59702005-07-07 20:40:38 +000010771 // Do a quick scan over the function. If we find any blocks that are
10772 // unreachable, remove any instructions inside of them. This prevents
10773 // the instcombine code from having to deal with some bad special cases.
10774 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10775 if (!Visited.count(BB)) {
10776 Instruction *Term = BB->getTerminator();
10777 while (Term != BB->begin()) { // Remove instrs bottom-up
10778 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010779
Bill Wendlingb7427032006-11-26 09:46:52 +000010780 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010781 ++NumDeadInst;
10782
10783 if (!I->use_empty())
10784 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10785 I->eraseFromParent();
10786 }
10787 }
10788 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010789
Chris Lattnerdbab3862007-03-02 21:28:56 +000010790 while (!Worklist.empty()) {
10791 Instruction *I = RemoveOneFromWorkList();
10792 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010793
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010794 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010795 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010796 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010797 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010798 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010799 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010800
Bill Wendlingb7427032006-11-26 09:46:52 +000010801 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010802
10803 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010804 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010805 continue;
10806 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010807
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010808 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010809 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010810 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010811
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010812 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010813 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010814 ReplaceInstUsesWith(*I, C);
10815
Chris Lattner62b14df2002-09-02 04:59:56 +000010816 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010817 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010818 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010819 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010820 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010821
Chris Lattnerea1c4542004-12-08 23:43:58 +000010822 // See if we can trivially sink this instruction to a successor basic block.
10823 if (I->hasOneUse()) {
10824 BasicBlock *BB = I->getParent();
10825 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10826 if (UserParent != BB) {
10827 bool UserIsSuccessor = false;
10828 // See if the user is one of our successors.
10829 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10830 if (*SI == UserParent) {
10831 UserIsSuccessor = true;
10832 break;
10833 }
10834
10835 // If the user is one of our immediate successors, and if that successor
10836 // only has us as a predecessors (we'd have to split the critical edge
10837 // otherwise), we can keep going.
10838 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10839 next(pred_begin(UserParent)) == pred_end(UserParent))
10840 // Okay, the CFG is simple enough, try to sink this instruction.
10841 Changed |= TryToSinkInstruction(I, UserParent);
10842 }
10843 }
10844
Chris Lattner8a2a3112001-12-14 16:52:21 +000010845 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010846#ifndef NDEBUG
10847 std::string OrigI;
10848#endif
10849 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010850 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010851 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010852 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010853 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010854 DOUT << "IC: Old = " << *I
10855 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010856
Chris Lattnerf523d062004-06-09 05:08:07 +000010857 // Everything uses the new instruction now.
10858 I->replaceAllUsesWith(Result);
10859
10860 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010861 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010862 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010863
Chris Lattner6934a042007-02-11 01:23:03 +000010864 // Move the name to the new instruction first.
10865 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010866
10867 // Insert the new instruction into the basic block...
10868 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010869 BasicBlock::iterator InsertPos = I;
10870
10871 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10872 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10873 ++InsertPos;
10874
10875 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010876
Chris Lattner00d51312004-05-01 23:27:23 +000010877 // Make sure that we reprocess all operands now that we reduced their
10878 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010879 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010880
Chris Lattnerf523d062004-06-09 05:08:07 +000010881 // Instructions can end up on the worklist more than once. Make sure
10882 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010883 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010884
10885 // Erase the old instruction.
10886 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010887 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010888#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010889 DOUT << "IC: Mod = " << OrigI
10890 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010891#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010892
Chris Lattner90ac28c2002-08-02 19:29:35 +000010893 // If the instruction was modified, it's possible that it is now dead.
10894 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010895 if (isInstructionTriviallyDead(I)) {
10896 // Make sure we process all operands now that we are reducing their
10897 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010898 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010899
Chris Lattner00d51312004-05-01 23:27:23 +000010900 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010901 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010902 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010903 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010904 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010905 AddToWorkList(I);
10906 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010907 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010908 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010909 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010910 }
10911 }
10912
Chris Lattnerec9c3582007-03-03 02:04:50 +000010913 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010914
10915 // Do an explicit clear, this shrinks the map if needed.
10916 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010917 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010918}
10919
Chris Lattnerec9c3582007-03-03 02:04:50 +000010920
10921bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010922 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10923
Chris Lattnerec9c3582007-03-03 02:04:50 +000010924 bool EverMadeChange = false;
10925
10926 // Iterate while there is work to do.
10927 unsigned Iteration = 0;
10928 while (DoOneIteration(F, Iteration++))
10929 EverMadeChange = true;
10930 return EverMadeChange;
10931}
10932
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010933FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010934 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010935}
Brian Gaeked0fde302003-11-11 22:41:34 +000010936