blob: ec51508e657656f79d3b7e9bf3d377a230f312e9 [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"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000060#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000071 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000075 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000077 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000078 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000079 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000080 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000081 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107
Chris Lattnerdbab3862007-03-02 21:28:56 +0000108
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000113 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 }
118
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000139 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000146
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000148 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000149
150 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000151
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000153 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000154 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000155 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000156 }
157
Chris Lattner28977af2004-04-05 01:30:19 +0000158 TargetData &getTargetData() const { return *TD; }
159
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000164 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000166 //
Chris Lattner7e708292002-06-25 16:13:24 +0000167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000195
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000199 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000202 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000217 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000222 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000223 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000224 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000225 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000226 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000227 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000228 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231
232 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000234
Chris Lattner9fe38862003-06-19 17:00:31 +0000235 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000236 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000239
Chris Lattner28977af2004-04-05 01:30:19 +0000240 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000241 // InsertNewInstBefore - insert an instruction New before instruction Old
242 // in the program. Add the new instruction to the worklist.
243 //
Chris Lattner955f3312004-09-28 21:48:02 +0000244 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000245 assert(New && New->getParent() == 0 &&
246 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000247 BasicBlock *BB = Old.getParent();
248 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000249 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000250 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000251 }
252
Chris Lattner0c967662004-09-24 15:21:34 +0000253 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254 /// This also adds the cast to the worklist. Finally, this returns the
255 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000256 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000258 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000259
Chris Lattnere2ed0572006-04-06 19:19:17 +0000260 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000261 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262
Reid Spencer17212df2006-12-12 09:18:51 +0000263 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000264 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000265 return C;
266 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000267
268 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270 }
271
Chris Lattner0c967662004-09-24 15:21:34 +0000272
Chris Lattner8b170942002-08-09 23:47:40 +0000273 // ReplaceInstUsesWith - This method is to be used when an instruction is
274 // found to be dead, replacable with another preexisting expression. Here
275 // we add all uses of I to the worklist, replace all uses of I with the new
276 // value, then return I, so that the inst combiner will know that I was
277 // modified.
278 //
279 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000280 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000281 if (&I != V) {
282 I.replaceAllUsesWith(V);
283 return &I;
284 } else {
285 // If we are replacing the instruction with itself, this must be in a
286 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000287 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000288 return &I;
289 }
Chris Lattner8b170942002-08-09 23:47:40 +0000290 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000291
Chris Lattner6dce1a72006-02-07 06:56:34 +0000292 // UpdateValueUsesWith - This method is to be used when an value is
293 // found to be replacable with another preexisting expression or was
294 // updated. Here we add all uses of I to the worklist, replace all uses of
295 // I with the new value (unless the instruction was just updated), then
296 // return true, so that the inst combiner will know that I was modified.
297 //
298 bool UpdateValueUsesWith(Value *Old, Value *New) {
299 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
300 if (Old != New)
301 Old->replaceAllUsesWith(New);
302 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000303 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000304 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000306 return true;
307 }
308
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000316 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000317 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 return 0; // Don't do anything with FI
319 }
320
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000321 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000322 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323 /// InsertBefore instruction. This is specialized a bit to avoid inserting
324 /// casts that are known to not do anything...
325 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000326 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 Instruction *InsertBefore);
329
Reid Spencere4d87aa2006-12-23 06:05:41 +0000330 /// SimplifyCommutative - This performs a few simplifications for
331 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000332 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000333
Reid Spencere4d87aa2006-12-23 06:05:41 +0000334 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335 /// most-complex to least-complex order.
336 bool SimplifyCompare(CmpInst &I);
337
Reid Spencer2ec619a2007-03-23 21:24:59 +0000338 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000340 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
341 APInt& KnownZero, APInt& KnownOne,
342 unsigned Depth = 0);
343
Chris Lattner867b99f2006-10-05 06:55:50 +0000344 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345 uint64_t &UndefElts, unsigned Depth = 0);
346
Chris Lattner4e998b22004-09-29 05:07:12 +0000347 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348 // PHI node as operand #0, see if we can fold the instruction into the PHI
349 // (which is only possible if all operands to the PHI are constants).
350 Instruction *FoldOpIntoPhi(Instruction &I);
351
Chris Lattnerbac32862004-11-14 19:13:23 +0000352 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353 // operator and they all are only used by the PHI, PHI together their
354 // inputs, and do the operation once, to the result of the PHI.
355 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000356 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357
358
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000359 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000364 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000365 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000366 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000367 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000368 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000369 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
Chris Lattnerafe91a52006-06-15 19:07:26 +0000371
Reid Spencerc55b2432006-12-13 18:21:21 +0000372 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000373 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000374
Devang Patel19974732007-05-03 01:11:54 +0000375 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000376 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000377}
378
Chris Lattner4f98c562003-03-10 21:43:22 +0000379// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000381static unsigned getComplexity(Value *V) {
382 if (isa<Instruction>(V)) {
383 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000384 return 3;
385 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000386 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000387 if (isa<Argument>(V)) return 3;
388 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000389}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390
Chris Lattnerc8802d22003-03-11 00:12:48 +0000391// isOnlyUse - Return true if this instruction will be deleted if we stop using
392// it.
393static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000394 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000395}
396
Chris Lattner4cb170c2004-02-23 06:38:22 +0000397// getPromotedType - Return the specified type promoted as it would be to pass
398// though a va_arg area...
399static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000400 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401 if (ITy->getBitWidth() < 32)
402 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000403 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000404 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000405}
406
Reid Spencer3da59db2006-11-27 01:05:10 +0000407/// getBitCastOperand - If the specified operand is a CastInst or a constant
408/// expression bitcast, return the operand value, otherwise return null.
409static Value *getBitCastOperand(Value *V) {
410 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000411 return I->getOperand(0);
412 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000414 return CE->getOperand(0);
415 return 0;
416}
417
Reid Spencer3da59db2006-11-27 01:05:10 +0000418/// This function is a wrapper around CastInst::isEliminableCastPair. It
419/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000420static Instruction::CastOps
421isEliminableCastPair(
422 const CastInst *CI, ///< The first cast instruction
423 unsigned opcode, ///< The opcode of the second cast instruction
424 const Type *DstTy, ///< The target type for the second cast instruction
425 TargetData *TD ///< The target data for pointer size
426) {
427
428 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
429 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000430
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 // Get the opcodes of the two Cast instructions
432 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435 return Instruction::CastOps(
436 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000438}
439
440/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441/// in any code being generated. It does not require codegen if V is simple
442/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
444 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000445 if (V->getType() == Ty || isa<Constant>(V)) return false;
446
Chris Lattner01575b72006-05-25 23:24:33 +0000447 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000448 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000449 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
Reid Spencer17212df2006-12-12 09:18:51 +0000458Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000460 Instruction *InsertBefore) {
461 if (V->getType() == DestTy) return V;
462 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000463 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000464
Reid Spencer17212df2006-12-12 09:18:51 +0000465 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000466}
467
Chris Lattner4f98c562003-03-10 21:43:22 +0000468// SimplifyCommutative - This performs a few simplifications for commutative
469// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000470//
Chris Lattner4f98c562003-03-10 21:43:22 +0000471// 1. Order operands such that they are listed from right (least complex) to
472// left (most complex). This puts constants before unary operators before
473// binary operators.
474//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000475// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000477//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000478bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000479 bool Changed = false;
480 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattner4f98c562003-03-10 21:43:22 +0000483 if (!I.isAssociative()) return Changed;
484 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000485 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000488 Constant *Folded = ConstantExpr::get(I.getOpcode(),
489 cast<Constant>(I.getOperand(1)),
490 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491 I.setOperand(0, Op->getOperand(0));
492 I.setOperand(1, Folded);
493 return true;
494 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496 isOnlyUse(Op) && isOnlyUse(Op1)) {
497 Constant *C1 = cast<Constant>(Op->getOperand(1));
498 Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000501 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000502 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503 Op1->getOperand(0),
504 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000505 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506 I.setOperand(0, New);
507 I.setOperand(1, Folded);
508 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000509 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000512}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000513
Reid Spencere4d87aa2006-12-23 06:05:41 +0000514/// SimplifyCompare - For a CmpInst this function just orders the operands
515/// so that theyare listed from right (least complex) to left (most complex).
516/// This puts constants before unary operators before binary operators.
517bool InstCombiner::SimplifyCompare(CmpInst &I) {
518 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519 return false;
520 I.swapOperands();
521 // Compare instructions are not associative so there's nothing else we can do.
522 return true;
523}
524
Chris Lattner8d969642003-03-10 23:06:50 +0000525// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000527//
Chris Lattner8d969642003-03-10 23:06:50 +0000528static inline Value *dyn_castNegVal(Value *V) {
529 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000530 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000531
Chris Lattner0ce85802004-12-14 20:08:06 +0000532 // Constants can be considered to be negated values if they can be folded.
533 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000535 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000536}
537
Chris Lattner8d969642003-03-10 23:06:50 +0000538static inline Value *dyn_castNotVal(Value *V) {
539 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000540 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000541
542 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000543 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000544 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000545 return 0;
546}
547
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548// dyn_castFoldableMul - If this value is a multiply that can be folded into
549// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000550// non-constant operand of the multiply, and set CST to point to the multiplier.
551// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552//
Chris Lattner50af16a2004-11-13 19:50:12 +0000553static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000554 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000555 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000557 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000559 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000560 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000561 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000562 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000563 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000564 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000565 return I->getOperand(0);
566 }
567 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000569}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000570
Chris Lattner574da9b2005-01-13 20:14:25 +0000571/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572/// expression, return it.
573static User *dyn_castGetElementPtr(Value *V) {
574 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576 if (CE->getOpcode() == Instruction::GetElementPtr)
577 return cast<User>(V);
578 return false;
579}
580
Reid Spencer7177c3a2007-03-25 05:33:51 +0000581/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000582static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000583 APInt Val(C->getValue());
584 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000585}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000586/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000587static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000588 APInt Val(C->getValue());
589 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000590}
591/// Add - Add two ConstantInts together
592static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() + C2->getValue());
594}
595/// And - Bitwise AND two ConstantInts together
596static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() & C2->getValue());
598}
599/// Subtract - Subtract one ConstantInt from another
600static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601 return ConstantInt::get(C1->getValue() - C2->getValue());
602}
603/// Multiply - Multiply two ConstantInts together
604static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000606}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000607/// MultiplyOverflows - True if the multiply can not be expressed in an int
608/// this size.
609static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
610 uint32_t W = C1->getBitWidth();
611 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
612 if (sign) {
613 LHSExt.sext(W * 2);
614 RHSExt.sext(W * 2);
615 } else {
616 LHSExt.zext(W * 2);
617 RHSExt.zext(W * 2);
618 }
619
620 APInt MulExt = LHSExt * RHSExt;
621
622 if (sign) {
623 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
624 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
625 return MulExt.slt(Min) || MulExt.sgt(Max);
626 } else
627 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
628}
Chris Lattner955f3312004-09-28 21:48:02 +0000629
Chris Lattner68d5ff22006-02-09 07:38:58 +0000630/// ComputeMaskedBits - Determine which of the bits specified in Mask are
631/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000632/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
633/// processing.
634/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
635/// we cannot optimize based on the assumption that it is zero without changing
636/// it to be an explicit zero. If we don't change it to zero, other code could
637/// optimized based on the contradictory assumption that it is non-zero.
638/// Because instcombine aggressively folds operations with undef args anyway,
639/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000640static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000641 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000642 assert(V && "No Value?");
643 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000644 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000645 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000646 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000647 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000648 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000649 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
650 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000651 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000652 KnownZero = ~KnownOne & Mask;
653 return;
654 }
655
Reid Spencer3e7594f2007-03-08 01:46:38 +0000656 if (Depth == 6 || Mask == 0)
657 return; // Limit search depth.
658
659 Instruction *I = dyn_cast<Instruction>(V);
660 if (!I) return;
661
Zhou Sheng771dbf72007-03-13 02:23:10 +0000662 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000663 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000664
665 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000666 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000667 // If either the LHS or the RHS are Zero, the result is zero.
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000669 APInt Mask2(Mask & ~KnownZero);
670 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000671 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673
674 // Output known-1 bits are only known if set in both the LHS & RHS.
675 KnownOne &= KnownOne2;
676 // Output known-0 are known to be clear if zero in either the LHS | RHS.
677 KnownZero |= KnownZero2;
678 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000679 }
680 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000682 APInt Mask2(Mask & ~KnownOne);
683 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
685 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
686
687 // Output known-0 bits are only known if clear in both the LHS & RHS.
688 KnownZero &= KnownZero2;
689 // Output known-1 are known to be set if set in either the LHS | RHS.
690 KnownOne |= KnownOne2;
691 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000692 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 case Instruction::Xor: {
694 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
698
699 // Output known-0 bits are known if clear or set in both the LHS & RHS.
700 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
701 // Output known-1 are known to be set if set in only one of the LHS, RHS.
702 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
703 KnownZero = KnownZeroOut;
704 return;
705 }
706 case Instruction::Select:
707 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
708 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
710 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
711
712 // Only known if known in both the LHS and RHS.
713 KnownOne &= KnownOne2;
714 KnownZero &= KnownZero2;
715 return;
716 case Instruction::FPTrunc:
717 case Instruction::FPExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::SIToFP:
721 case Instruction::PtrToInt:
722 case Instruction::UIToFP:
723 case Instruction::IntToPtr:
724 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000725 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000726 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000727 uint32_t SrcBitWidth =
728 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000729 APInt MaskIn(Mask);
730 MaskIn.zext(SrcBitWidth);
731 KnownZero.zext(SrcBitWidth);
732 KnownOne.zext(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000734 KnownZero.trunc(BitWidth);
735 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000736 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000737 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 case Instruction::BitCast: {
739 const Type *SrcTy = I->getOperand(0)->getType();
740 if (SrcTy->isInteger()) {
741 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
742 return;
743 }
744 break;
745 }
746 case Instruction::ZExt: {
747 // Compute the bits in the result that are not present in the input.
748 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000749 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000750
Zhou Shengaa305ab2007-03-28 02:19:03 +0000751 APInt MaskIn(Mask);
752 MaskIn.trunc(SrcBitWidth);
753 KnownZero.trunc(SrcBitWidth);
754 KnownOne.trunc(SrcBitWidth);
755 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000758 KnownZero.zext(BitWidth);
759 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000760 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000761 return;
762 }
763 case Instruction::SExt: {
764 // Compute the bits in the result that are not present in the input.
765 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000766 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000767
Zhou Shengaa305ab2007-03-28 02:19:03 +0000768 APInt MaskIn(Mask);
769 MaskIn.trunc(SrcBitWidth);
770 KnownZero.trunc(SrcBitWidth);
771 KnownOne.trunc(SrcBitWidth);
772 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000774 KnownZero.zext(BitWidth);
775 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000776
777 // If the sign bit of the input is known set or clear, then we know the
778 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000779 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000780 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000781 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000782 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000783 return;
784 }
785 case Instruction::Shl:
786 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
787 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000788 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000789 APInt Mask2(Mask.lshr(ShiftAmt));
790 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000792 KnownZero <<= ShiftAmt;
793 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000794 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000795 return;
796 }
797 break;
798 case Instruction::LShr:
799 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
800 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
801 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000802 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000803
804 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000805 APInt Mask2(Mask.shl(ShiftAmt));
806 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000807 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
808 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
809 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000810 // high bits known zero.
811 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 return;
813 }
814 break;
815 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000816 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000817 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
818 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000819 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820
821 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000822 APInt Mask2(Mask.shl(ShiftAmt));
823 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000824 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
825 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
826 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
827
Zhou Shengaa305ab2007-03-28 02:19:03 +0000828 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
829 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000831 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000832 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000833 return;
834 }
835 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000836 case Instruction::SRem:
837 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
838 APInt RA = Rem->getValue();
839 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
840 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
841 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
842 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
843
844 // The sign of a remainder is equal to the sign of the first
845 // operand (zero being positive).
846 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
847 KnownZero2 |= ~LowBits;
848 else if (KnownOne2[BitWidth-1])
849 KnownOne2 |= ~LowBits;
850
851 KnownZero |= KnownZero2 & Mask;
852 KnownOne |= KnownOne2 & Mask;
853
854 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
855 }
856 }
857 break;
858 case Instruction::URem:
859 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
860 APInt RA = Rem->getValue();
861 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
862 APInt LowBits = (RA - 1) | RA;
863 APInt Mask2 = LowBits & Mask;
864 KnownZero |= ~LowBits & Mask;
865 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
866 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
867 }
868 } else {
869 // Since the result is less than or equal to RHS, any leading zero bits
870 // in RHS must also exist in the result.
871 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
872 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2, Depth+1);
873
874 uint32_t Leaders = KnownZero2.countLeadingOnes();
875 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
876 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
877 }
878 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000879 }
880}
881
Reid Spencere7816b52007-03-08 01:52:58 +0000882/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
883/// this predicate to simplify operations downstream. Mask is known to be zero
884/// for bits that V cannot have.
885static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000886 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000887 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
888 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
889 return (KnownZero & Mask) == Mask;
890}
891
Chris Lattner255d8912006-02-11 09:31:47 +0000892/// ShrinkDemandedConstant - Check to see if the specified operand of the
893/// specified instruction is a constant integer. If so, check to see if there
894/// are any bits set in the constant that are not demanded. If so, shrink the
895/// constant and return true.
896static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000897 APInt Demanded) {
898 assert(I && "No instruction?");
899 assert(OpNo < I->getNumOperands() && "Operand index too large");
900
901 // If the operand is not a constant integer, nothing to do.
902 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
903 if (!OpC) return false;
904
905 // If there are no bits set that aren't demanded, nothing to do.
906 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
907 if ((~Demanded & OpC->getValue()) == 0)
908 return false;
909
910 // This instruction is producing bits that are not demanded. Shrink the RHS.
911 Demanded &= OpC->getValue();
912 I->setOperand(OpNo, ConstantInt::get(Demanded));
913 return true;
914}
915
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000916// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
917// set of known zero and one bits, compute the maximum and minimum values that
918// could have the specified known zero and known one bits, returning them in
919// min/max.
920static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000921 const APInt& KnownZero,
922 const APInt& KnownOne,
923 APInt& Min, APInt& Max) {
924 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
925 assert(KnownZero.getBitWidth() == BitWidth &&
926 KnownOne.getBitWidth() == BitWidth &&
927 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
928 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000929 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000930
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000931 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
932 // bit if it is unknown.
933 Min = KnownOne;
934 Max = KnownOne|UnknownBits;
935
Zhou Sheng4acf1552007-03-28 05:15:57 +0000936 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000937 Min.set(BitWidth-1);
938 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000939 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000940}
941
942// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
943// a set of known zero and one bits, compute the maximum and minimum values that
944// could have the specified known zero and known one bits, returning them in
945// min/max.
946static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000947 const APInt &KnownZero,
948 const APInt &KnownOne,
949 APInt &Min, APInt &Max) {
950 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000951 assert(KnownZero.getBitWidth() == BitWidth &&
952 KnownOne.getBitWidth() == BitWidth &&
953 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
954 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000955 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000956
957 // The minimum value is when the unknown bits are all zeros.
958 Min = KnownOne;
959 // The maximum value is when the unknown bits are all ones.
960 Max = KnownOne|UnknownBits;
961}
Chris Lattner255d8912006-02-11 09:31:47 +0000962
Reid Spencer8cb68342007-03-12 17:25:59 +0000963/// SimplifyDemandedBits - This function attempts to replace V with a simpler
964/// value based on the demanded bits. When this function is called, it is known
965/// that only the bits set in DemandedMask of the result of V are ever used
966/// downstream. Consequently, depending on the mask and V, it may be possible
967/// to replace V with a constant or one of its operands. In such cases, this
968/// function does the replacement and returns true. In all other cases, it
969/// returns false after analyzing the expression and setting KnownOne and known
970/// to be one in the expression. KnownZero contains all the bits that are known
971/// to be zero in the expression. These are provided to potentially allow the
972/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
973/// the expression. KnownOne and KnownZero always follow the invariant that
974/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
975/// the bits in KnownOne and KnownZero may only be accurate for those bits set
976/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
977/// and KnownOne must all be the same.
978bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
979 APInt& KnownZero, APInt& KnownOne,
980 unsigned Depth) {
981 assert(V != 0 && "Null pointer of Value???");
982 assert(Depth <= 6 && "Limit Search Depth");
983 uint32_t BitWidth = DemandedMask.getBitWidth();
984 const IntegerType *VTy = cast<IntegerType>(V->getType());
985 assert(VTy->getBitWidth() == BitWidth &&
986 KnownZero.getBitWidth() == BitWidth &&
987 KnownOne.getBitWidth() == BitWidth &&
988 "Value *V, DemandedMask, KnownZero and KnownOne \
989 must have same BitWidth");
990 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
991 // We know all of the bits for a constant!
992 KnownOne = CI->getValue() & DemandedMask;
993 KnownZero = ~KnownOne & DemandedMask;
994 return false;
995 }
996
Zhou Sheng96704452007-03-14 03:21:24 +0000997 KnownZero.clear();
998 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000999 if (!V->hasOneUse()) { // Other users may use these bits.
1000 if (Depth != 0) { // Not at the root.
1001 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1002 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1003 return false;
1004 }
1005 // If this is the root being simplified, allow it to have multiple uses,
1006 // just set the DemandedMask to all bits.
1007 DemandedMask = APInt::getAllOnesValue(BitWidth);
1008 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1009 if (V != UndefValue::get(VTy))
1010 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1011 return false;
1012 } else if (Depth == 6) { // Limit search depth.
1013 return false;
1014 }
1015
1016 Instruction *I = dyn_cast<Instruction>(V);
1017 if (!I) return false; // Only analyze instructions.
1018
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1020 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1021 switch (I->getOpcode()) {
1022 default: break;
1023 case Instruction::And:
1024 // If either the LHS or the RHS are Zero, the result is zero.
1025 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1026 RHSKnownZero, RHSKnownOne, Depth+1))
1027 return true;
1028 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1029 "Bits known to be one AND zero?");
1030
1031 // If something is known zero on the RHS, the bits aren't demanded on the
1032 // LHS.
1033 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1034 LHSKnownZero, LHSKnownOne, Depth+1))
1035 return true;
1036 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1037 "Bits known to be one AND zero?");
1038
1039 // If all of the demanded bits are known 1 on one side, return the other.
1040 // These bits cannot contribute to the result of the 'and'.
1041 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1042 (DemandedMask & ~LHSKnownZero))
1043 return UpdateValueUsesWith(I, I->getOperand(0));
1044 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1045 (DemandedMask & ~RHSKnownZero))
1046 return UpdateValueUsesWith(I, I->getOperand(1));
1047
1048 // If all of the demanded bits in the inputs are known zeros, return zero.
1049 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1050 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1051
1052 // If the RHS is a constant, see if we can simplify it.
1053 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1054 return UpdateValueUsesWith(I, I);
1055
1056 // Output known-1 bits are only known if set in both the LHS & RHS.
1057 RHSKnownOne &= LHSKnownOne;
1058 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1059 RHSKnownZero |= LHSKnownZero;
1060 break;
1061 case Instruction::Or:
1062 // If either the LHS or the RHS are One, the result is One.
1063 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1064 RHSKnownZero, RHSKnownOne, Depth+1))
1065 return true;
1066 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1067 "Bits known to be one AND zero?");
1068 // If something is known one on the RHS, the bits aren't demanded on the
1069 // LHS.
1070 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1071 LHSKnownZero, LHSKnownOne, Depth+1))
1072 return true;
1073 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1074 "Bits known to be one AND zero?");
1075
1076 // If all of the demanded bits are known zero on one side, return the other.
1077 // These bits cannot contribute to the result of the 'or'.
1078 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1079 (DemandedMask & ~LHSKnownOne))
1080 return UpdateValueUsesWith(I, I->getOperand(0));
1081 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1082 (DemandedMask & ~RHSKnownOne))
1083 return UpdateValueUsesWith(I, I->getOperand(1));
1084
1085 // If all of the potentially set bits on one side are known to be set on
1086 // the other side, just use the 'other' side.
1087 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1088 (DemandedMask & (~RHSKnownZero)))
1089 return UpdateValueUsesWith(I, I->getOperand(0));
1090 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1091 (DemandedMask & (~LHSKnownZero)))
1092 return UpdateValueUsesWith(I, I->getOperand(1));
1093
1094 // If the RHS is a constant, see if we can simplify it.
1095 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1096 return UpdateValueUsesWith(I, I);
1097
1098 // Output known-0 bits are only known if clear in both the LHS & RHS.
1099 RHSKnownZero &= LHSKnownZero;
1100 // Output known-1 are known to be set if set in either the LHS | RHS.
1101 RHSKnownOne |= LHSKnownOne;
1102 break;
1103 case Instruction::Xor: {
1104 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1105 RHSKnownZero, RHSKnownOne, Depth+1))
1106 return true;
1107 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1108 "Bits known to be one AND zero?");
1109 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1110 LHSKnownZero, LHSKnownOne, Depth+1))
1111 return true;
1112 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1113 "Bits known to be one AND zero?");
1114
1115 // If all of the demanded bits are known zero on one side, return the other.
1116 // These bits cannot contribute to the result of the 'xor'.
1117 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1118 return UpdateValueUsesWith(I, I->getOperand(0));
1119 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1120 return UpdateValueUsesWith(I, I->getOperand(1));
1121
1122 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1123 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1124 (RHSKnownOne & LHSKnownOne);
1125 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1126 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1127 (RHSKnownOne & LHSKnownZero);
1128
1129 // If all of the demanded bits are known to be zero on one side or the
1130 // other, turn this into an *inclusive* or.
1131 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1132 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1133 Instruction *Or =
1134 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1135 I->getName());
1136 InsertNewInstBefore(Or, *I);
1137 return UpdateValueUsesWith(I, Or);
1138 }
1139
1140 // If all of the demanded bits on one side are known, and all of the set
1141 // bits on that side are also known to be set on the other side, turn this
1142 // into an AND, as we know the bits will be cleared.
1143 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1144 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1145 // all known
1146 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1147 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1148 Instruction *And =
1149 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1150 InsertNewInstBefore(And, *I);
1151 return UpdateValueUsesWith(I, And);
1152 }
1153 }
1154
1155 // If the RHS is a constant, see if we can simplify it.
1156 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1157 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1158 return UpdateValueUsesWith(I, I);
1159
1160 RHSKnownZero = KnownZeroOut;
1161 RHSKnownOne = KnownOneOut;
1162 break;
1163 }
1164 case Instruction::Select:
1165 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1166 RHSKnownZero, RHSKnownOne, Depth+1))
1167 return true;
1168 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1169 LHSKnownZero, LHSKnownOne, Depth+1))
1170 return true;
1171 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1172 "Bits known to be one AND zero?");
1173 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1174 "Bits known to be one AND zero?");
1175
1176 // If the operands are constants, see if we can simplify them.
1177 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1178 return UpdateValueUsesWith(I, I);
1179 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1180 return UpdateValueUsesWith(I, I);
1181
1182 // Only known if known in both the LHS and RHS.
1183 RHSKnownOne &= LHSKnownOne;
1184 RHSKnownZero &= LHSKnownZero;
1185 break;
1186 case Instruction::Trunc: {
1187 uint32_t truncBf =
1188 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001189 DemandedMask.zext(truncBf);
1190 RHSKnownZero.zext(truncBf);
1191 RHSKnownOne.zext(truncBf);
1192 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1193 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001194 return true;
1195 DemandedMask.trunc(BitWidth);
1196 RHSKnownZero.trunc(BitWidth);
1197 RHSKnownOne.trunc(BitWidth);
1198 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1199 "Bits known to be one AND zero?");
1200 break;
1201 }
1202 case Instruction::BitCast:
1203 if (!I->getOperand(0)->getType()->isInteger())
1204 return false;
1205
1206 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1207 RHSKnownZero, RHSKnownOne, Depth+1))
1208 return true;
1209 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1210 "Bits known to be one AND zero?");
1211 break;
1212 case Instruction::ZExt: {
1213 // Compute the bits in the result that are not present in the input.
1214 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001215 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
Zhou Shengd48653a2007-03-29 04:45:55 +00001217 DemandedMask.trunc(SrcBitWidth);
1218 RHSKnownZero.trunc(SrcBitWidth);
1219 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001220 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1221 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 return true;
1223 DemandedMask.zext(BitWidth);
1224 RHSKnownZero.zext(BitWidth);
1225 RHSKnownOne.zext(BitWidth);
1226 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1227 "Bits known to be one AND zero?");
1228 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001229 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 break;
1231 }
1232 case Instruction::SExt: {
1233 // Compute the bits in the result that are not present in the input.
1234 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001235 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001236
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001238 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001239
Zhou Sheng01542f32007-03-29 02:26:30 +00001240 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 // If any of the sign extended bits are demanded, we know that the sign
1242 // bit is demanded.
1243 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001244 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001245
Zhou Shengd48653a2007-03-29 04:45:55 +00001246 InputDemandedBits.trunc(SrcBitWidth);
1247 RHSKnownZero.trunc(SrcBitWidth);
1248 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001249 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1250 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 return true;
1252 InputDemandedBits.zext(BitWidth);
1253 RHSKnownZero.zext(BitWidth);
1254 RHSKnownOne.zext(BitWidth);
1255 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1256 "Bits known to be one AND zero?");
1257
1258 // If the sign bit of the input is known set or clear, then we know the
1259 // top bits of the result.
1260
1261 // If the input sign bit is known zero, or if the NewBits are not demanded
1262 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001263 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001264 {
1265 // Convert to ZExt cast
1266 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1267 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 }
1271 break;
1272 }
1273 case Instruction::Add: {
1274 // Figure out what the input bits are. If the top bits of the and result
1275 // are not demanded, then the add doesn't demand them from its input
1276 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001277 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001278
1279 // If there is a constant on the RHS, there are a variety of xformations
1280 // we can do.
1281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1282 // If null, this should be simplified elsewhere. Some of the xforms here
1283 // won't work if the RHS is zero.
1284 if (RHS->isZero())
1285 break;
1286
1287 // If the top bit of the output is demanded, demand everything from the
1288 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
1291 // Find information about known zero/one bits in the input.
1292 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1293 LHSKnownZero, LHSKnownOne, Depth+1))
1294 return true;
1295
1296 // If the RHS of the add has bits set that can't affect the input, reduce
1297 // the constant.
1298 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1299 return UpdateValueUsesWith(I, I);
1300
1301 // Avoid excess work.
1302 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1303 break;
1304
1305 // Turn it into OR if input bits are zero.
1306 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1307 Instruction *Or =
1308 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1309 I->getName());
1310 InsertNewInstBefore(Or, *I);
1311 return UpdateValueUsesWith(I, Or);
1312 }
1313
1314 // We can say something about the output known-zero and known-one bits,
1315 // depending on potential carries from the input constant and the
1316 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1317 // bits set and the RHS constant is 0x01001, then we know we have a known
1318 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1319
1320 // To compute this, we first compute the potential carry bits. These are
1321 // the bits which may be modified. I'm not aware of a better way to do
1322 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001323 const APInt& RHSVal = RHS->getValue();
1324 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
1326 // Now that we know which bits have carries, compute the known-1/0 sets.
1327
1328 // Bits are known one if they are known zero in one operand and one in the
1329 // other, and there is no input carry.
1330 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1331 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1332
1333 // Bits are known zero if they are known zero in both operands and there
1334 // is no input carry.
1335 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1336 } else {
1337 // If the high-bits of this ADD are not demanded, then it does not demand
1338 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001339 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 // Right fill the mask of bits for this ADD to demand the most
1341 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001342 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1344 LHSKnownZero, LHSKnownOne, Depth+1))
1345 return true;
1346 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1347 LHSKnownZero, LHSKnownOne, Depth+1))
1348 return true;
1349 }
1350 }
1351 break;
1352 }
1353 case Instruction::Sub:
1354 // If the high-bits of this SUB are not demanded, then it does not demand
1355 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001356 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001357 // Right fill the mask of bits for this SUB to demand the most
1358 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001359 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001360 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001361 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1362 LHSKnownZero, LHSKnownOne, Depth+1))
1363 return true;
1364 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1365 LHSKnownZero, LHSKnownOne, Depth+1))
1366 return true;
1367 }
1368 break;
1369 case Instruction::Shl:
1370 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001371 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001372 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1373 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 RHSKnownZero, RHSKnownOne, Depth+1))
1375 return true;
1376 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1377 "Bits known to be one AND zero?");
1378 RHSKnownZero <<= ShiftAmt;
1379 RHSKnownOne <<= ShiftAmt;
1380 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001381 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001382 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001383 }
1384 break;
1385 case Instruction::LShr:
1386 // For a logical shift right
1387 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001388 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001389
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001391 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1392 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001393 RHSKnownZero, RHSKnownOne, Depth+1))
1394 return true;
1395 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1396 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001397 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1398 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001399 if (ShiftAmt) {
1400 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001402 RHSKnownZero |= HighBits; // high bits known zero.
1403 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 }
1405 break;
1406 case Instruction::AShr:
1407 // If this is an arithmetic shift right and only the low-bit is set, we can
1408 // always convert this into a logical shr, even if the shift amount is
1409 // variable. The low bit of the shift cannot be an input sign bit unless
1410 // the shift amount is >= the size of the datatype, which is undefined.
1411 if (DemandedMask == 1) {
1412 // Perform the logical shift right.
1413 Value *NewVal = BinaryOperator::createLShr(
1414 I->getOperand(0), I->getOperand(1), I->getName());
1415 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1416 return UpdateValueUsesWith(I, NewVal);
1417 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001418
1419 // If the sign bit is the only bit demanded by this ashr, then there is no
1420 // need to do it, the shift doesn't change the high bit.
1421 if (DemandedMask.isSignBit())
1422 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001423
1424 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001425 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001426
Reid Spencer8cb68342007-03-12 17:25:59 +00001427 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001428 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001429 // If any of the "high bits" are demanded, we should set the sign bit as
1430 // demanded.
1431 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1432 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001433 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001434 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 RHSKnownZero, RHSKnownOne, Depth+1))
1436 return true;
1437 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1438 "Bits known to be one AND zero?");
1439 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001440 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001441 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1442 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1443
1444 // Handle the sign bits.
1445 APInt SignBit(APInt::getSignBit(BitWidth));
1446 // Adjust to where it is now in the mask.
1447 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1448
1449 // If the input sign bit is known to be zero, or if none of the top bits
1450 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001451 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001452 (HighBits & ~DemandedMask) == HighBits) {
1453 // Perform the logical shift right.
1454 Value *NewVal = BinaryOperator::createLShr(
1455 I->getOperand(0), SA, I->getName());
1456 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1457 return UpdateValueUsesWith(I, NewVal);
1458 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1459 RHSKnownOne |= HighBits;
1460 }
1461 }
1462 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001463 case Instruction::SRem:
1464 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1465 APInt RA = Rem->getValue();
1466 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1467 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1468 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1469 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1470 LHSKnownZero, LHSKnownOne, Depth+1))
1471 return true;
1472
1473 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1474 LHSKnownZero |= ~LowBits;
1475 else if (LHSKnownOne[BitWidth-1])
1476 LHSKnownOne |= ~LowBits;
1477
1478 KnownZero |= LHSKnownZero & DemandedMask;
1479 KnownOne |= LHSKnownOne & DemandedMask;
1480
1481 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1482 }
1483 }
1484 break;
1485 case Instruction::URem:
1486 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1487 APInt RA = Rem->getValue();
1488 if (RA.isPowerOf2()) {
1489 APInt LowBits = (RA - 1) | RA;
1490 APInt Mask2 = LowBits & DemandedMask;
1491 KnownZero |= ~LowBits & DemandedMask;
1492 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1493 KnownZero, KnownOne, Depth+1))
1494 return true;
1495
1496 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1497 }
1498 } else {
1499 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1500 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1501 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1502 KnownZero2, KnownOne2, Depth+1))
1503 return true;
1504
1505 uint32_t Leaders = KnownZero2.countLeadingOnes();
1506 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1507 }
1508 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001509 }
1510
1511 // If the client is only demanding bits that we know, return the known
1512 // constant.
1513 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1514 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1515 return false;
1516}
1517
Chris Lattner867b99f2006-10-05 06:55:50 +00001518
1519/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1520/// 64 or fewer elements. DemandedElts contains the set of elements that are
1521/// actually used by the caller. This method analyzes which elements of the
1522/// operand are undef and returns that information in UndefElts.
1523///
1524/// If the information about demanded elements can be used to simplify the
1525/// operation, the operation is simplified, then the resultant value is
1526/// returned. This returns null if no change was made.
1527Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1528 uint64_t &UndefElts,
1529 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001530 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 assert(VWidth <= 64 && "Vector too wide to analyze!");
1532 uint64_t EltMask = ~0ULL >> (64-VWidth);
1533 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1534 "Invalid DemandedElts!");
1535
1536 if (isa<UndefValue>(V)) {
1537 // If the entire vector is undefined, just return this info.
1538 UndefElts = EltMask;
1539 return 0;
1540 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1541 UndefElts = EltMask;
1542 return UndefValue::get(V->getType());
1543 }
1544
1545 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001546 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1547 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 Constant *Undef = UndefValue::get(EltTy);
1549
1550 std::vector<Constant*> Elts;
1551 for (unsigned i = 0; i != VWidth; ++i)
1552 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1553 Elts.push_back(Undef);
1554 UndefElts |= (1ULL << i);
1555 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1556 Elts.push_back(Undef);
1557 UndefElts |= (1ULL << i);
1558 } else { // Otherwise, defined.
1559 Elts.push_back(CP->getOperand(i));
1560 }
1561
1562 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001563 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001564 return NewCP != CP ? NewCP : 0;
1565 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001566 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001568 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001569 Constant *Zero = Constant::getNullValue(EltTy);
1570 Constant *Undef = UndefValue::get(EltTy);
1571 std::vector<Constant*> Elts;
1572 for (unsigned i = 0; i != VWidth; ++i)
1573 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1574 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001575 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001576 }
1577
1578 if (!V->hasOneUse()) { // Other users may use these bits.
1579 if (Depth != 0) { // Not at the root.
1580 // TODO: Just compute the UndefElts information recursively.
1581 return false;
1582 }
1583 return false;
1584 } else if (Depth == 10) { // Limit search depth.
1585 return false;
1586 }
1587
1588 Instruction *I = dyn_cast<Instruction>(V);
1589 if (!I) return false; // Only analyze instructions.
1590
1591 bool MadeChange = false;
1592 uint64_t UndefElts2;
1593 Value *TmpV;
1594 switch (I->getOpcode()) {
1595 default: break;
1596
1597 case Instruction::InsertElement: {
1598 // If this is a variable index, we don't know which element it overwrites.
1599 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001600 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001601 if (Idx == 0) {
1602 // Note that we can't propagate undef elt info, because we don't know
1603 // which elt is getting updated.
1604 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605 UndefElts2, Depth+1);
1606 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607 break;
1608 }
1609
1610 // If this is inserting an element that isn't demanded, remove this
1611 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001612 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001613 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1614 return AddSoonDeadInstToWorklist(*I, 0);
1615
1616 // Otherwise, the element inserted overwrites whatever was there, so the
1617 // input demanded set is simpler than the output set.
1618 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1619 DemandedElts & ~(1ULL << IdxNo),
1620 UndefElts, Depth+1);
1621 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1622
1623 // The inserted element is defined.
1624 UndefElts |= 1ULL << IdxNo;
1625 break;
1626 }
Chris Lattner69878332007-04-14 22:29:23 +00001627 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001628 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001629 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1630 if (!VTy) break;
1631 unsigned InVWidth = VTy->getNumElements();
1632 uint64_t InputDemandedElts = 0;
1633 unsigned Ratio;
1634
1635 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001636 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001637 // elements as are demanded of us.
1638 Ratio = 1;
1639 InputDemandedElts = DemandedElts;
1640 } else if (VWidth > InVWidth) {
1641 // Untested so far.
1642 break;
1643
1644 // If there are more elements in the result than there are in the source,
1645 // then an input element is live if any of the corresponding output
1646 // elements are live.
1647 Ratio = VWidth/InVWidth;
1648 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1649 if (DemandedElts & (1ULL << OutIdx))
1650 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1651 }
1652 } else {
1653 // Untested so far.
1654 break;
1655
1656 // If there are more elements in the source than there are in the result,
1657 // then an input element is live if the corresponding output element is
1658 // live.
1659 Ratio = InVWidth/VWidth;
1660 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1661 if (DemandedElts & (1ULL << InIdx/Ratio))
1662 InputDemandedElts |= 1ULL << InIdx;
1663 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001664
Chris Lattner69878332007-04-14 22:29:23 +00001665 // div/rem demand all inputs, because they don't want divide by zero.
1666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1667 UndefElts2, Depth+1);
1668 if (TmpV) {
1669 I->setOperand(0, TmpV);
1670 MadeChange = true;
1671 }
1672
1673 UndefElts = UndefElts2;
1674 if (VWidth > InVWidth) {
1675 assert(0 && "Unimp");
1676 // If there are more elements in the result than there are in the source,
1677 // then an output element is undef if the corresponding input element is
1678 // undef.
1679 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1680 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1681 UndefElts |= 1ULL << OutIdx;
1682 } else if (VWidth < InVWidth) {
1683 assert(0 && "Unimp");
1684 // If there are more elements in the source than there are in the result,
1685 // then a result element is undef if all of the corresponding input
1686 // elements are undef.
1687 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1688 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1689 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1690 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1691 }
1692 break;
1693 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001694 case Instruction::And:
1695 case Instruction::Or:
1696 case Instruction::Xor:
1697 case Instruction::Add:
1698 case Instruction::Sub:
1699 case Instruction::Mul:
1700 // div/rem demand all inputs, because they don't want divide by zero.
1701 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1702 UndefElts, Depth+1);
1703 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1705 UndefElts2, Depth+1);
1706 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1707
1708 // Output elements are undefined if both are undefined. Consider things
1709 // like undef&0. The result is known zero, not undef.
1710 UndefElts &= UndefElts2;
1711 break;
1712
1713 case Instruction::Call: {
1714 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1715 if (!II) break;
1716 switch (II->getIntrinsicID()) {
1717 default: break;
1718
1719 // Binary vector operations that work column-wise. A dest element is a
1720 // function of the corresponding input elements from the two inputs.
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse_mul_ss:
1723 case Intrinsic::x86_sse_min_ss:
1724 case Intrinsic::x86_sse_max_ss:
1725 case Intrinsic::x86_sse2_sub_sd:
1726 case Intrinsic::x86_sse2_mul_sd:
1727 case Intrinsic::x86_sse2_min_sd:
1728 case Intrinsic::x86_sse2_max_sd:
1729 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1730 UndefElts, Depth+1);
1731 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1732 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1733 UndefElts2, Depth+1);
1734 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1735
1736 // If only the low elt is demanded and this is a scalarizable intrinsic,
1737 // scalarize it now.
1738 if (DemandedElts == 1) {
1739 switch (II->getIntrinsicID()) {
1740 default: break;
1741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse_mul_ss:
1743 case Intrinsic::x86_sse2_sub_sd:
1744 case Intrinsic::x86_sse2_mul_sd:
1745 // TODO: Lower MIN/MAX/ABS/etc
1746 Value *LHS = II->getOperand(1);
1747 Value *RHS = II->getOperand(2);
1748 // Extract the element as scalars.
1749 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1750 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1751
1752 switch (II->getIntrinsicID()) {
1753 default: assert(0 && "Case stmts out of sync!");
1754 case Intrinsic::x86_sse_sub_ss:
1755 case Intrinsic::x86_sse2_sub_sd:
1756 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1757 II->getName()), *II);
1758 break;
1759 case Intrinsic::x86_sse_mul_ss:
1760 case Intrinsic::x86_sse2_mul_sd:
1761 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1762 II->getName()), *II);
1763 break;
1764 }
1765
1766 Instruction *New =
1767 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1768 II->getName());
1769 InsertNewInstBefore(New, *II);
1770 AddSoonDeadInstToWorklist(*II, 0);
1771 return New;
1772 }
1773 }
1774
1775 // Output elements are undefined if both are undefined. Consider things
1776 // like undef&0. The result is known zero, not undef.
1777 UndefElts &= UndefElts2;
1778 break;
1779 }
1780 break;
1781 }
1782 }
1783 return MadeChange ? I : 0;
1784}
1785
Nick Lewycky455e1762007-09-06 02:40:25 +00001786/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001787/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001788/// @brief Determine if the icmp Predicate is true when both operands are equal
1789static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001790 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1791 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1792 pred == ICmpInst::ICMP_SLE;
1793}
1794
Nick Lewycky455e1762007-09-06 02:40:25 +00001795/// @returns true if the specified compare instruction is
1796/// true when both operands are equal...
1797/// @brief Determine if the ICmpInst returns true when both operands are equal
1798static bool isTrueWhenEqual(ICmpInst &ICI) {
1799 return isTrueWhenEqual(ICI.getPredicate());
1800}
1801
Chris Lattner564a7272003-08-13 19:01:45 +00001802/// AssociativeOpt - Perform an optimization on an associative operator. This
1803/// function is designed to check a chain of associative operators for a
1804/// potential to apply a certain optimization. Since the optimization may be
1805/// applicable if the expression was reassociated, this checks the chain, then
1806/// reassociates the expression as necessary to expose the optimization
1807/// opportunity. This makes use of a special Functor, which must define
1808/// 'shouldApply' and 'apply' methods.
1809///
1810template<typename Functor>
1811Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1812 unsigned Opcode = Root.getOpcode();
1813 Value *LHS = Root.getOperand(0);
1814
1815 // Quick check, see if the immediate LHS matches...
1816 if (F.shouldApply(LHS))
1817 return F.apply(Root);
1818
1819 // Otherwise, if the LHS is not of the same opcode as the root, return.
1820 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001821 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001822 // Should we apply this transform to the RHS?
1823 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1824
1825 // If not to the RHS, check to see if we should apply to the LHS...
1826 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1827 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1828 ShouldApply = true;
1829 }
1830
1831 // If the functor wants to apply the optimization to the RHS of LHSI,
1832 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1833 if (ShouldApply) {
1834 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001835
Chris Lattner564a7272003-08-13 19:01:45 +00001836 // Now all of the instructions are in the current basic block, go ahead
1837 // and perform the reassociation.
1838 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1839
1840 // First move the selected RHS to the LHS of the root...
1841 Root.setOperand(0, LHSI->getOperand(1));
1842
1843 // Make what used to be the LHS of the root be the user of the root...
1844 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001845 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001846 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1847 return 0;
1848 }
Chris Lattner65725312004-04-16 18:08:07 +00001849 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001850 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001851 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1852 BasicBlock::iterator ARI = &Root; ++ARI;
1853 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1854 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001855
1856 // Now propagate the ExtraOperand down the chain of instructions until we
1857 // get to LHSI.
1858 while (TmpLHSI != LHSI) {
1859 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001860 // Move the instruction to immediately before the chain we are
1861 // constructing to avoid breaking dominance properties.
1862 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1863 BB->getInstList().insert(ARI, NextLHSI);
1864 ARI = NextLHSI;
1865
Chris Lattner564a7272003-08-13 19:01:45 +00001866 Value *NextOp = NextLHSI->getOperand(1);
1867 NextLHSI->setOperand(1, ExtraOperand);
1868 TmpLHSI = NextLHSI;
1869 ExtraOperand = NextOp;
1870 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001871
Chris Lattner564a7272003-08-13 19:01:45 +00001872 // Now that the instructions are reassociated, have the functor perform
1873 // the transformation...
1874 return F.apply(Root);
1875 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001876
Chris Lattner564a7272003-08-13 19:01:45 +00001877 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1878 }
1879 return 0;
1880}
1881
1882
1883// AddRHS - Implements: X + X --> X << 1
1884struct AddRHS {
1885 Value *RHS;
1886 AddRHS(Value *rhs) : RHS(rhs) {}
1887 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1888 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001889 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001890 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001891 }
1892};
1893
1894// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1895// iff C1&C2 == 0
1896struct AddMaskingAnd {
1897 Constant *C2;
1898 AddMaskingAnd(Constant *c) : C2(c) {}
1899 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001900 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001901 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001902 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001903 }
1904 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001905 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001906 }
1907};
1908
Chris Lattner6e7ba452005-01-01 16:22:27 +00001909static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001910 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001911 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001913 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001914
Reid Spencer3da59db2006-11-27 01:05:10 +00001915 return IC->InsertNewInstBefore(CastInst::create(
1916 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001917 }
1918
Chris Lattner2eefe512004-04-09 19:05:30 +00001919 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001920 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1921 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001922
Chris Lattner2eefe512004-04-09 19:05:30 +00001923 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1924 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1926 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001927 }
1928
1929 Value *Op0 = SO, *Op1 = ConstOperand;
1930 if (!ConstIsRHS)
1931 std::swap(Op0, Op1);
1932 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001933 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1934 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001935 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1936 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1937 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001938 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001939 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001940 abort();
1941 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001942 return IC->InsertNewInstBefore(New, I);
1943}
1944
1945// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1946// constant as the other operand, try to fold the binary operator into the
1947// select arguments. This also works for Cast instructions, which obviously do
1948// not have a second operand.
1949static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1950 InstCombiner *IC) {
1951 // Don't modify shared select instructions
1952 if (!SI->hasOneUse()) return 0;
1953 Value *TV = SI->getOperand(1);
1954 Value *FV = SI->getOperand(2);
1955
1956 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001957 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001958 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001959
Chris Lattner6e7ba452005-01-01 16:22:27 +00001960 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1961 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1962
1963 return new SelectInst(SI->getCondition(), SelectTrueVal,
1964 SelectFalseVal);
1965 }
1966 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001967}
1968
Chris Lattner4e998b22004-09-29 05:07:12 +00001969
1970/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1971/// node as operand #0, see if we can fold the instruction into the PHI (which
1972/// is only possible if all operands to the PHI are constants).
1973Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1974 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001975 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001976 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001977
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001978 // Check to see if all of the operands of the PHI are constants. If there is
1979 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001980 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001981 BasicBlock *NonConstBB = 0;
1982 for (unsigned i = 0; i != NumPHIValues; ++i)
1983 if (!isa<Constant>(PN->getIncomingValue(i))) {
1984 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001985 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001986 NonConstBB = PN->getIncomingBlock(i);
1987
1988 // If the incoming non-constant value is in I's block, we have an infinite
1989 // loop.
1990 if (NonConstBB == I.getParent())
1991 return 0;
1992 }
1993
1994 // If there is exactly one non-constant value, we can insert a copy of the
1995 // operation in that block. However, if this is a critical edge, we would be
1996 // inserting the computation one some other paths (e.g. inside a loop). Only
1997 // do this if the pred block is unconditionally branching into the phi block.
1998 if (NonConstBB) {
1999 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2000 if (!BI || !BI->isUnconditional()) return 0;
2001 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002002
2003 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002004 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002005 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002006 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002007 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002008
2009 // Next, add all of the operands to the PHI.
2010 if (I.getNumOperands() == 2) {
2011 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002012 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002013 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002014 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002015 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2016 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2017 else
2018 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019 } else {
2020 assert(PN->getIncomingBlock(i) == NonConstBB);
2021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2022 InV = BinaryOperator::create(BO->getOpcode(),
2023 PN->getIncomingValue(i), C, "phitmp",
2024 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002025 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2026 InV = CmpInst::create(CI->getOpcode(),
2027 CI->getPredicate(),
2028 PN->getIncomingValue(i), C, "phitmp",
2029 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002030 else
2031 assert(0 && "Unknown binop!");
2032
Chris Lattnerdbab3862007-03-02 21:28:56 +00002033 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002034 }
2035 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002036 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002037 } else {
2038 CastInst *CI = cast<CastInst>(&I);
2039 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002040 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002041 Value *InV;
2042 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002043 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044 } else {
2045 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002046 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2047 I.getType(), "phitmp",
2048 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002049 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002050 }
2051 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002052 }
2053 }
2054 return ReplaceInstUsesWith(I, NewPN);
2055}
2056
Chris Lattner2454a2e2008-01-29 06:52:45 +00002057
2058/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2059/// value is never equal to -0.0.
2060///
2061/// Note that this function will need to be revisited when we support nondefault
2062/// rounding modes!
2063///
2064static bool CannotBeNegativeZero(const Value *V) {
2065 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2066 return !CFP->getValueAPF().isNegZero();
2067
2068 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2069 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2070 if (I->getOpcode() == Instruction::Add &&
2071 isa<ConstantFP>(I->getOperand(1)) &&
2072 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2073 return true;
2074
2075 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2076 if (II->getIntrinsicID() == Intrinsic::sqrt)
2077 return CannotBeNegativeZero(II->getOperand(1));
2078
2079 if (const CallInst *CI = dyn_cast<CallInst>(I))
2080 if (const Function *F = CI->getCalledFunction()) {
2081 if (F->isDeclaration()) {
2082 switch (F->getNameLen()) {
2083 case 3: // abs(x) != -0.0
2084 if (!strcmp(F->getNameStart(), "abs")) return true;
2085 break;
2086 case 4: // abs[lf](x) != -0.0
2087 if (!strcmp(F->getNameStart(), "absf")) return true;
2088 if (!strcmp(F->getNameStart(), "absl")) return true;
2089 break;
2090 }
2091 }
2092 }
2093 }
2094
2095 return false;
2096}
2097
2098
Chris Lattner7e708292002-06-25 16:13:24 +00002099Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002100 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002101 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002102
Chris Lattner66331a42004-04-10 22:01:55 +00002103 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002104 // X + undef -> undef
2105 if (isa<UndefValue>(RHS))
2106 return ReplaceInstUsesWith(I, RHS);
2107
Chris Lattner66331a42004-04-10 22:01:55 +00002108 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002109 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002110 if (RHSC->isNullValue())
2111 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002112 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002113 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2114 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002115 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002116 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002117
Chris Lattner66331a42004-04-10 22:01:55 +00002118 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002119 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002120 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002121 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002122 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002123 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002124
2125 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2126 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002127 if (!isa<VectorType>(I.getType())) {
2128 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2129 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2130 KnownZero, KnownOne))
2131 return &I;
2132 }
Chris Lattner66331a42004-04-10 22:01:55 +00002133 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002134
2135 if (isa<PHINode>(LHS))
2136 if (Instruction *NV = FoldOpIntoPhi(I))
2137 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002138
Chris Lattner4f637d42006-01-06 17:59:59 +00002139 ConstantInt *XorRHS = 0;
2140 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002141 if (isa<ConstantInt>(RHSC) &&
2142 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002143 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002144 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002145
Zhou Sheng4351c642007-04-02 08:20:41 +00002146 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002147 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2148 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002149 do {
2150 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002151 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2152 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002153 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2154 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002155 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002156 if (!MaskedValueIsZero(XorLHS,
2157 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002158 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002159 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002160 }
2161 }
2162 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002163 C0080Val = APIntOps::lshr(C0080Val, Size);
2164 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2165 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002166
Reid Spencer35c38852007-03-28 01:36:16 +00002167 // FIXME: This shouldn't be necessary. When the backends can handle types
2168 // with funny bit widths then this whole cascade of if statements should
2169 // be removed. It is just here to get the size of the "middle" type back
2170 // up to something that the back ends can handle.
2171 const Type *MiddleType = 0;
2172 switch (Size) {
2173 default: break;
2174 case 32: MiddleType = Type::Int32Ty; break;
2175 case 16: MiddleType = Type::Int16Ty; break;
2176 case 8: MiddleType = Type::Int8Ty; break;
2177 }
2178 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002179 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002180 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002181 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002182 }
2183 }
Chris Lattner66331a42004-04-10 22:01:55 +00002184 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002185
Chris Lattner564a7272003-08-13 19:01:45 +00002186 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002187 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002188 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002189
2190 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2191 if (RHSI->getOpcode() == Instruction::Sub)
2192 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2193 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2194 }
2195 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2196 if (LHSI->getOpcode() == Instruction::Sub)
2197 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2198 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2199 }
Robert Bocchino71698282004-07-27 21:02:21 +00002200 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002201
Chris Lattner5c4afb92002-05-08 22:46:53 +00002202 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002203 // -A + -B --> -(A + B)
2204 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002205 if (LHS->getType()->isIntOrIntVector()) {
2206 if (Value *RHSV = dyn_castNegVal(RHS)) {
2207 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2208 InsertNewInstBefore(NewAdd, I);
2209 return BinaryOperator::createNeg(NewAdd);
2210 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002211 }
2212
2213 return BinaryOperator::createSub(RHS, LHSV);
2214 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002215
2216 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002217 if (!isa<Constant>(RHS))
2218 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002219 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002220
Misha Brukmanfd939082005-04-21 23:48:37 +00002221
Chris Lattner50af16a2004-11-13 19:50:12 +00002222 ConstantInt *C2;
2223 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2224 if (X == RHS) // X*C + X --> X * (C+1)
2225 return BinaryOperator::createMul(RHS, AddOne(C2));
2226
2227 // X*C1 + X*C2 --> X * (C1+C2)
2228 ConstantInt *C1;
2229 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002230 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002231 }
2232
2233 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002234 if (dyn_castFoldableMul(RHS, C2) == LHS)
2235 return BinaryOperator::createMul(LHS, AddOne(C2));
2236
Chris Lattnere617c9e2007-01-05 02:17:46 +00002237 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002238 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2239 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002240
Chris Lattnerad3448c2003-02-18 19:57:07 +00002241
Chris Lattner564a7272003-08-13 19:01:45 +00002242 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002243 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002244 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2245 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002246
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002247 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002248 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002249 Value *W, *X, *Y, *Z;
2250 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2251 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2252 if (W != Y) {
2253 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002254 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002256 std::swap(W, X);
2257 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002258 std::swap(Y, Z);
2259 std::swap(W, X);
2260 }
2261 }
2262
2263 if (W == Y) {
2264 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2265 LHS->getName()), I);
2266 return BinaryOperator::createMul(W, NewAdd);
2267 }
2268 }
2269 }
2270
Chris Lattner6b032052003-10-02 15:11:26 +00002271 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002272 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002273 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2274 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002275
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002276 // (X & FF00) + xx00 -> (X+xx00) & FF00
2277 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002278 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002279 if (Anded == CRHS) {
2280 // See if all bits from the first bit set in the Add RHS up are included
2281 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002282 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002283
2284 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002285 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002286
2287 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002288 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002289
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002290 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2291 // Okay, the xform is safe. Insert the new add pronto.
2292 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2293 LHS->getName()), I);
2294 return BinaryOperator::createAnd(NewAdd, C2);
2295 }
2296 }
2297 }
2298
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002299 // Try to fold constant add into select arguments.
2300 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002301 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002302 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002303 }
2304
Reid Spencer1628cec2006-10-26 06:15:43 +00002305 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002306 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002307 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002308 CastInst *CI = dyn_cast<CastInst>(LHS);
2309 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002310 if (!CI) {
2311 CI = dyn_cast<CastInst>(RHS);
2312 Other = LHS;
2313 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002314 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002315 (CI->getType()->getPrimitiveSizeInBits() ==
2316 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002317 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002318 unsigned AS =
2319 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002320 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2321 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002322 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002323 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002324 }
2325 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002326
Chris Lattner42790482007-12-20 01:56:58 +00002327 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002328 {
2329 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2330 Value *Other = RHS;
2331 if (!SI) {
2332 SI = dyn_cast<SelectInst>(RHS);
2333 Other = LHS;
2334 }
Chris Lattner42790482007-12-20 01:56:58 +00002335 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002336 Value *TV = SI->getTrueValue();
2337 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002338 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002339
2340 // Can we fold the add into the argument of the select?
2341 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002342 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2343 A == Other) // Fold the add into the true select value.
2344 return new SelectInst(SI->getCondition(), N, A);
2345 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2346 A == Other) // Fold the add into the false select value.
2347 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002348 }
2349 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002350
2351 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2352 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2353 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2354 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002355
Chris Lattner7e708292002-06-25 16:13:24 +00002356 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002357}
2358
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002359// isSignBit - Return true if the value represented by the constant only has the
2360// highest order bit set.
2361static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002362 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002363 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002364}
2365
Chris Lattner7e708292002-06-25 16:13:24 +00002366Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002367 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002368
Chris Lattner233f7dc2002-08-12 21:17:25 +00002369 if (Op0 == Op1) // sub X, X -> 0
2370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002371
Chris Lattner233f7dc2002-08-12 21:17:25 +00002372 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002373 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002374 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002375
Chris Lattnere87597f2004-10-16 18:11:37 +00002376 if (isa<UndefValue>(Op0))
2377 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2378 if (isa<UndefValue>(Op1))
2379 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2380
Chris Lattnerd65460f2003-11-05 01:06:05 +00002381 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2382 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002383 if (C->isAllOnesValue())
2384 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002385
Chris Lattnerd65460f2003-11-05 01:06:05 +00002386 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002387 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002388 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002389 return BinaryOperator::createAdd(X, AddOne(C));
2390
Chris Lattner76b7a062007-01-15 07:02:54 +00002391 // -(X >>u 31) -> (X >>s 31)
2392 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002393 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002394 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002395 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002396 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002397 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002398 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002399 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002400 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002401 return BinaryOperator::create(Instruction::AShr,
2402 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002403 }
2404 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002405 }
2406 else if (SI->getOpcode() == Instruction::AShr) {
2407 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2408 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002409 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002410 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002411 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002412 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002413 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002414 }
2415 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002416 }
2417 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002418 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002419
2420 // Try to fold constant sub into select arguments.
2421 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002423 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002424
2425 if (isa<PHINode>(Op0))
2426 if (Instruction *NV = FoldOpIntoPhi(I))
2427 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002428 }
2429
Chris Lattner43d84d62005-04-07 16:15:25 +00002430 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2431 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002432 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002433 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002434 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002435 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002436 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002437 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2438 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2439 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002440 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002441 Op1I->getOperand(0));
2442 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002443 }
2444
Chris Lattnerfd059242003-10-15 16:48:29 +00002445 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002446 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2447 // is not used by anyone else...
2448 //
Chris Lattner0517e722004-02-02 20:09:56 +00002449 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002450 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002451 // Swap the two operands of the subexpr...
2452 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2453 Op1I->setOperand(0, IIOp1);
2454 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002455
Chris Lattnera2881962003-02-18 19:28:33 +00002456 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002457 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002458 }
2459
2460 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2461 //
2462 if (Op1I->getOpcode() == Instruction::And &&
2463 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2464 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2465
Chris Lattnerf523d062004-06-09 05:08:07 +00002466 Value *NewNot =
2467 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002468 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002469 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002470
Reid Spencerac5209e2006-10-16 23:08:08 +00002471 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002472 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002473 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002474 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002475 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002476 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002477 ConstantExpr::getNeg(DivRHS));
2478
Chris Lattnerad3448c2003-02-18 19:57:07 +00002479 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002480 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002481 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002482 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002483 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002484 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002485
2486 // X - ((X / Y) * Y) --> X % Y
2487 if (Op1I->getOpcode() == Instruction::Mul)
2488 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2489 if (Op0 == I->getOperand(0) &&
2490 Op1I->getOperand(1) == I->getOperand(1)) {
2491 if (I->getOpcode() == Instruction::SDiv)
2492 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2493 if (I->getOpcode() == Instruction::UDiv)
2494 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2495 }
Chris Lattner40371712002-05-09 01:29:19 +00002496 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002497 }
Chris Lattnera2881962003-02-18 19:28:33 +00002498
Chris Lattner9919e3d2006-12-02 00:13:08 +00002499 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002500 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002501 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002502 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2503 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2504 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2505 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002506 } else if (Op0I->getOpcode() == Instruction::Sub) {
2507 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2508 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002509 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002510 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002511
Chris Lattner50af16a2004-11-13 19:50:12 +00002512 ConstantInt *C1;
2513 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002514 if (X == Op1) // X*C - X --> X * (C-1)
2515 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002516
Chris Lattner50af16a2004-11-13 19:50:12 +00002517 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2518 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002519 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002520 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002521 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002522}
2523
Chris Lattnera0141b92007-07-15 20:42:37 +00002524/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2525/// comparison only checks the sign bit. If it only checks the sign bit, set
2526/// TrueIfSigned if the result of the comparison is true when the input value is
2527/// signed.
2528static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2529 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002530 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002531 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2532 TrueIfSigned = true;
2533 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002534 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2535 TrueIfSigned = true;
2536 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002537 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2538 TrueIfSigned = false;
2539 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002540 case ICmpInst::ICMP_UGT:
2541 // True if LHS u> RHS and RHS == high-bit-mask - 1
2542 TrueIfSigned = true;
2543 return RHS->getValue() ==
2544 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2545 case ICmpInst::ICMP_UGE:
2546 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2547 TrueIfSigned = true;
2548 return RHS->getValue() ==
2549 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002550 default:
2551 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002552 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002553}
2554
Chris Lattner7e708292002-06-25 16:13:24 +00002555Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002556 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002557 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002558
Chris Lattnere87597f2004-10-16 18:11:37 +00002559 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2561
Chris Lattner233f7dc2002-08-12 21:17:25 +00002562 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002563 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2564 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002565
2566 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002567 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002568 if (SI->getOpcode() == Instruction::Shl)
2569 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002570 return BinaryOperator::createMul(SI->getOperand(0),
2571 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002572
Zhou Sheng843f07672007-04-19 05:39:12 +00002573 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002574 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2575 if (CI->equalsInt(1)) // X * 1 == X
2576 return ReplaceInstUsesWith(I, Op0);
2577 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002578 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002579
Zhou Sheng97b52c22007-03-29 01:57:21 +00002580 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002581 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002582 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002583 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002584 }
Robert Bocchino71698282004-07-27 21:02:21 +00002585 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002586 if (Op1F->isNullValue())
2587 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002588
Chris Lattnera2881962003-02-18 19:28:33 +00002589 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2590 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002591 // We need a better interface for long double here.
2592 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2593 if (Op1F->isExactlyValue(1.0))
2594 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002595 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002596
2597 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2598 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2599 isa<ConstantInt>(Op0I->getOperand(1))) {
2600 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2601 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2602 Op1, "tmp");
2603 InsertNewInstBefore(Add, I);
2604 Value *C1C2 = ConstantExpr::getMul(Op1,
2605 cast<Constant>(Op0I->getOperand(1)));
2606 return BinaryOperator::createAdd(Add, C1C2);
2607
2608 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002609
2610 // Try to fold constant mul into select arguments.
2611 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002612 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002613 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002614
2615 if (isa<PHINode>(Op0))
2616 if (Instruction *NV = FoldOpIntoPhi(I))
2617 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002618 }
2619
Chris Lattnera4f445b2003-03-10 23:23:04 +00002620 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2621 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002622 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002623
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002624 // If one of the operands of the multiply is a cast from a boolean value, then
2625 // we know the bool is either zero or one, so this is a 'masking' multiply.
2626 // See if we can simplify things based on how the boolean was originally
2627 // formed.
2628 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002629 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002630 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002631 BoolCast = CI;
2632 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002633 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002634 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002635 BoolCast = CI;
2636 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002637 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002638 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2639 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002640 bool TIS = false;
2641
Reid Spencere4d87aa2006-12-23 06:05:41 +00002642 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002643 // multiply into a shift/and combination.
2644 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002645 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2646 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002647 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002648 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002649 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002650 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002651 InsertNewInstBefore(
2652 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002653 BoolCast->getOperand(0)->getName()+
2654 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002655
2656 // If the multiply type is not the same as the source type, sign extend
2657 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002658 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002659 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2660 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002661 Instruction::CastOps opcode =
2662 (SrcBits == DstBits ? Instruction::BitCast :
2663 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2664 V = InsertCastBefore(opcode, V, I.getType(), I);
2665 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002666
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002667 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002668 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002669 }
2670 }
2671 }
2672
Chris Lattner7e708292002-06-25 16:13:24 +00002673 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002674}
2675
Reid Spencer1628cec2006-10-26 06:15:43 +00002676/// This function implements the transforms on div instructions that work
2677/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2678/// used by the visitors to those instructions.
2679/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002680Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002682
Chris Lattner50b2ca42008-02-19 06:12:18 +00002683 // undef / X -> 0 for integer.
2684 // undef / X -> undef for FP (the undef could be a snan).
2685 if (isa<UndefValue>(Op0)) {
2686 if (Op0->getType()->isFPOrFPVector())
2687 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002689 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002690
2691 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002692 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002693 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002694
Chris Lattner25feae52008-01-28 00:58:18 +00002695 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2696 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002697 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002698 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2699 // the same basic block, then we replace the select with Y, and the
2700 // condition of the select with false (if the cond value is in the same BB).
2701 // If the select has uses other than the div, this allows them to be
2702 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2703 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002704 if (ST->isNullValue()) {
2705 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2706 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002707 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002708 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2709 I.setOperand(1, SI->getOperand(2));
2710 else
2711 UpdateValueUsesWith(SI, SI->getOperand(2));
2712 return &I;
2713 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002714
Chris Lattner25feae52008-01-28 00:58:18 +00002715 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2716 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002717 if (ST->isNullValue()) {
2718 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2719 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002720 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002721 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2722 I.setOperand(1, SI->getOperand(1));
2723 else
2724 UpdateValueUsesWith(SI, SI->getOperand(1));
2725 return &I;
2726 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002727 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002728
Reid Spencer1628cec2006-10-26 06:15:43 +00002729 return 0;
2730}
Misha Brukmanfd939082005-04-21 23:48:37 +00002731
Reid Spencer1628cec2006-10-26 06:15:43 +00002732/// This function implements the transforms common to both integer division
2733/// instructions (udiv and sdiv). It is called by the visitors to those integer
2734/// division instructions.
2735/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002736Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2738
2739 if (Instruction *Common = commonDivTransforms(I))
2740 return Common;
2741
2742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2743 // div X, 1 == X
2744 if (RHS->equalsInt(1))
2745 return ReplaceInstUsesWith(I, Op0);
2746
2747 // (X / C1) / C2 -> X / (C1*C2)
2748 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2749 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2750 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002751 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2752 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2753 else
2754 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2755 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002756 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002757
Reid Spencerbca0e382007-03-23 20:05:17 +00002758 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002759 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2760 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2761 return R;
2762 if (isa<PHINode>(Op0))
2763 if (Instruction *NV = FoldOpIntoPhi(I))
2764 return NV;
2765 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002766 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002767
Chris Lattnera2881962003-02-18 19:28:33 +00002768 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002769 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002770 if (LHS->equalsInt(0))
2771 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2772
Reid Spencer1628cec2006-10-26 06:15:43 +00002773 return 0;
2774}
2775
2776Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2778
2779 // Handle the integer div common cases
2780 if (Instruction *Common = commonIDivTransforms(I))
2781 return Common;
2782
2783 // X udiv C^2 -> X >> C
2784 // Check to see if this is an unsigned division with an exact power of 2,
2785 // if so, convert to a right shift.
2786 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002787 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002788 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002789 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002790 }
2791
2792 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002793 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002794 if (RHSI->getOpcode() == Instruction::Shl &&
2795 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002796 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002797 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002798 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002799 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002800 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002801 Constant *C2V = ConstantInt::get(NTy, C2);
2802 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002803 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002804 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002805 }
2806 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002807 }
2808
Reid Spencer1628cec2006-10-26 06:15:43 +00002809 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2810 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002811 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002812 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002813 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002814 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002815 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002816 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002817 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002818 // Construct the "on true" case of the select
2819 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2820 Instruction *TSI = BinaryOperator::createLShr(
2821 Op0, TC, SI->getName()+".t");
2822 TSI = InsertNewInstBefore(TSI, I);
2823
2824 // Construct the "on false" case of the select
2825 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2826 Instruction *FSI = BinaryOperator::createLShr(
2827 Op0, FC, SI->getName()+".f");
2828 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002829
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002830 // construct the select instruction and return it.
2831 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002832 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002833 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002834 return 0;
2835}
2836
Reid Spencer1628cec2006-10-26 06:15:43 +00002837Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2838 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2839
2840 // Handle the integer div common cases
2841 if (Instruction *Common = commonIDivTransforms(I))
2842 return Common;
2843
2844 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2845 // sdiv X, -1 == -X
2846 if (RHS->isAllOnesValue())
2847 return BinaryOperator::createNeg(Op0);
2848
2849 // -X/C -> X/-C
2850 if (Value *LHSNeg = dyn_castNegVal(Op0))
2851 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2852 }
2853
2854 // If the sign bits of both operands are zero (i.e. we can prove they are
2855 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002856 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002857 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002858 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002859 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002860 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2861 }
2862 }
2863
2864 return 0;
2865}
2866
2867Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2868 return commonDivTransforms(I);
2869}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002870
Reid Spencer0a783f72006-11-02 01:53:59 +00002871/// This function implements the transforms on rem instructions that work
2872/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2873/// is used by the visitors to those instructions.
2874/// @brief Transforms common to all three rem instructions
2875Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002877
Chris Lattner50b2ca42008-02-19 06:12:18 +00002878 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002879 if (Constant *LHS = dyn_cast<Constant>(Op0))
2880 if (LHS->isNullValue())
2881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2882
Chris Lattner50b2ca42008-02-19 06:12:18 +00002883 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2884 if (I.getType()->isFPOrFPVector())
2885 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002887 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002888 if (isa<UndefValue>(Op1))
2889 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002890
2891 // Handle cases involving: rem X, (select Cond, Y, Z)
2892 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2893 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2894 // the same basic block, then we replace the select with Y, and the
2895 // condition of the select with false (if the cond value is in the same
2896 // BB). If the select has uses other than the div, this allows them to be
2897 // simplified also.
2898 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2899 if (ST->isNullValue()) {
2900 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2901 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002902 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002903 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2904 I.setOperand(1, SI->getOperand(2));
2905 else
2906 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002907 return &I;
2908 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002909 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2910 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2911 if (ST->isNullValue()) {
2912 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2913 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002914 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002915 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2916 I.setOperand(1, SI->getOperand(1));
2917 else
2918 UpdateValueUsesWith(SI, SI->getOperand(1));
2919 return &I;
2920 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002921 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002922
Reid Spencer0a783f72006-11-02 01:53:59 +00002923 return 0;
2924}
2925
2926/// This function implements the transforms common to both integer remainder
2927/// instructions (urem and srem). It is called by the visitors to those integer
2928/// remainder instructions.
2929/// @brief Common integer remainder transforms
2930Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2932
2933 if (Instruction *common = commonRemTransforms(I))
2934 return common;
2935
Chris Lattner857e8cd2004-12-12 21:48:58 +00002936 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002937 // X % 0 == undef, we don't need to preserve faults!
2938 if (RHS->equalsInt(0))
2939 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2940
Chris Lattnera2881962003-02-18 19:28:33 +00002941 if (RHS->equalsInt(1)) // X % 1 == 0
2942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2943
Chris Lattner97943922006-02-28 05:49:21 +00002944 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2945 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2946 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2947 return R;
2948 } else if (isa<PHINode>(Op0I)) {
2949 if (Instruction *NV = FoldOpIntoPhi(I))
2950 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002951 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002952
2953 // See if we can fold away this rem instruction.
2954 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2955 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2956 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2957 KnownZero, KnownOne))
2958 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002959 }
Chris Lattnera2881962003-02-18 19:28:33 +00002960 }
2961
Reid Spencer0a783f72006-11-02 01:53:59 +00002962 return 0;
2963}
2964
2965Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2967
2968 if (Instruction *common = commonIRemTransforms(I))
2969 return common;
2970
2971 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2972 // X urem C^2 -> X and C
2973 // Check to see if this is an unsigned remainder with an exact power of 2,
2974 // if so, convert to a bitwise and.
2975 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002976 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002977 return BinaryOperator::createAnd(Op0, SubOne(C));
2978 }
2979
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002980 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002981 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2982 if (RHSI->getOpcode() == Instruction::Shl &&
2983 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002984 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002985 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2986 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2987 "tmp"), I);
2988 return BinaryOperator::createAnd(Op0, Add);
2989 }
2990 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002991 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002992
Reid Spencer0a783f72006-11-02 01:53:59 +00002993 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2994 // where C1&C2 are powers of two.
2995 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2996 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2997 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2998 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002999 if ((STO->getValue().isPowerOf2()) &&
3000 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003001 Value *TrueAnd = InsertNewInstBefore(
3002 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3003 Value *FalseAnd = InsertNewInstBefore(
3004 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3005 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3006 }
3007 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003008 }
3009
Chris Lattner3f5b8772002-05-06 16:14:14 +00003010 return 0;
3011}
3012
Reid Spencer0a783f72006-11-02 01:53:59 +00003013Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3015
Dan Gohmancff55092007-11-05 23:16:33 +00003016 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003017 if (Instruction *common = commonIRemTransforms(I))
3018 return common;
3019
3020 if (Value *RHSNeg = dyn_castNegVal(Op1))
3021 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003022 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003023 // X % -Y -> X % Y
3024 AddUsesToWorkList(I);
3025 I.setOperand(1, RHSNeg);
3026 return &I;
3027 }
3028
Dan Gohmancff55092007-11-05 23:16:33 +00003029 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003030 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003031 if (I.getType()->isInteger()) {
3032 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3033 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3034 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3035 return BinaryOperator::createURem(Op0, Op1, I.getName());
3036 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003037 }
3038
3039 return 0;
3040}
3041
3042Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003043 return commonRemTransforms(I);
3044}
3045
Chris Lattner8b170942002-08-09 23:47:40 +00003046// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003047static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003048 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003049 if (!isSigned)
3050 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3051 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003052}
3053
3054// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003055static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003056 if (!isSigned)
3057 return C->getValue() == 1; // unsigned
3058
3059 // Calculate 1111111111000000000000
3060 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3061 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003062}
3063
Chris Lattner457dd822004-06-09 07:59:58 +00003064// isOneBitSet - Return true if there is exactly one bit set in the specified
3065// constant.
3066static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003067 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003068}
3069
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003070// isHighOnes - Return true if the constant is of the form 1+0+.
3071// This is the same as lowones(~X).
3072static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003073 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003074}
3075
Reid Spencere4d87aa2006-12-23 06:05:41 +00003076/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003077/// are carefully arranged to allow folding of expressions such as:
3078///
3079/// (A < B) | (A > B) --> (A != B)
3080///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003081/// Note that this is only valid if the first and second predicates have the
3082/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003083///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003084/// Three bits are used to represent the condition, as follows:
3085/// 0 A > B
3086/// 1 A == B
3087/// 2 A < B
3088///
3089/// <=> Value Definition
3090/// 000 0 Always false
3091/// 001 1 A > B
3092/// 010 2 A == B
3093/// 011 3 A >= B
3094/// 100 4 A < B
3095/// 101 5 A != B
3096/// 110 6 A <= B
3097/// 111 7 Always true
3098///
3099static unsigned getICmpCode(const ICmpInst *ICI) {
3100 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003101 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003102 case ICmpInst::ICMP_UGT: return 1; // 001
3103 case ICmpInst::ICMP_SGT: return 1; // 001
3104 case ICmpInst::ICMP_EQ: return 2; // 010
3105 case ICmpInst::ICMP_UGE: return 3; // 011
3106 case ICmpInst::ICMP_SGE: return 3; // 011
3107 case ICmpInst::ICMP_ULT: return 4; // 100
3108 case ICmpInst::ICMP_SLT: return 4; // 100
3109 case ICmpInst::ICMP_NE: return 5; // 101
3110 case ICmpInst::ICMP_ULE: return 6; // 110
3111 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003112 // True -> 7
3113 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003114 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003115 return 0;
3116 }
3117}
3118
Reid Spencere4d87aa2006-12-23 06:05:41 +00003119/// getICmpValue - This is the complement of getICmpCode, which turns an
3120/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003121/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003122/// of predicate to use in new icmp instructions.
3123static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3124 switch (code) {
3125 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003126 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003127 case 1:
3128 if (sign)
3129 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3130 else
3131 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3132 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3133 case 3:
3134 if (sign)
3135 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3136 else
3137 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3138 case 4:
3139 if (sign)
3140 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3141 else
3142 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3143 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3144 case 6:
3145 if (sign)
3146 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3147 else
3148 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003149 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003150 }
3151}
3152
Reid Spencere4d87aa2006-12-23 06:05:41 +00003153static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3154 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3155 (ICmpInst::isSignedPredicate(p1) &&
3156 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3157 (ICmpInst::isSignedPredicate(p2) &&
3158 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3159}
3160
3161namespace {
3162// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3163struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003164 InstCombiner &IC;
3165 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003166 ICmpInst::Predicate pred;
3167 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3168 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3169 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003170 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003171 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3172 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003173 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3174 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003175 return false;
3176 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003177 Instruction *apply(Instruction &Log) const {
3178 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3179 if (ICI->getOperand(0) != LHS) {
3180 assert(ICI->getOperand(1) == LHS);
3181 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003182 }
3183
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003184 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003185 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003186 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003187 unsigned Code;
3188 switch (Log.getOpcode()) {
3189 case Instruction::And: Code = LHSCode & RHSCode; break;
3190 case Instruction::Or: Code = LHSCode | RHSCode; break;
3191 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003192 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003193 }
3194
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003195 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3196 ICmpInst::isSignedPredicate(ICI->getPredicate());
3197
3198 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003199 if (Instruction *I = dyn_cast<Instruction>(RV))
3200 return I;
3201 // Otherwise, it's a constant boolean value...
3202 return IC.ReplaceInstUsesWith(Log, RV);
3203 }
3204};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003205} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003206
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003207// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3208// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003209// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003210Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003211 ConstantInt *OpRHS,
3212 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003213 BinaryOperator &TheAnd) {
3214 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003215 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003216 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003217 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003218
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003219 switch (Op->getOpcode()) {
3220 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003221 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003222 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003223 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003224 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003225 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003226 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003227 }
3228 break;
3229 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003230 if (Together == AndRHS) // (X | C) & C --> C
3231 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003232
Chris Lattner6e7ba452005-01-01 16:22:27 +00003233 if (Op->hasOneUse() && Together != OpRHS) {
3234 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003235 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003236 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003237 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003238 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003239 }
3240 break;
3241 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003242 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003243 // Adding a one to a single bit bit-field should be turned into an XOR
3244 // of the bit. First thing to check is to see if this AND is with a
3245 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003246 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003247
3248 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003249 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003250 // Ok, at this point, we know that we are masking the result of the
3251 // ADD down to exactly one bit. If the constant we are adding has
3252 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003253 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003254
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003255 // Check to see if any bits below the one bit set in AndRHSV are set.
3256 if ((AddRHS & (AndRHSV-1)) == 0) {
3257 // If not, the only thing that can effect the output of the AND is
3258 // the bit specified by AndRHSV. If that bit is set, the effect of
3259 // the XOR is to toggle the bit. If it is clear, then the ADD has
3260 // no effect.
3261 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3262 TheAnd.setOperand(0, X);
3263 return &TheAnd;
3264 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003265 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003266 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003267 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003268 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003269 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003270 }
3271 }
3272 }
3273 }
3274 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003275
3276 case Instruction::Shl: {
3277 // We know that the AND will not produce any of the bits shifted in, so if
3278 // the anded constant includes them, clear them now!
3279 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003280 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003281 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003282 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3283 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003284
Zhou Sheng290bec52007-03-29 08:15:12 +00003285 if (CI->getValue() == ShlMask) {
3286 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003287 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3288 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003289 TheAnd.setOperand(1, CI);
3290 return &TheAnd;
3291 }
3292 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003293 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003294 case Instruction::LShr:
3295 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003296 // We know that the AND will not produce any of the bits shifted in, so if
3297 // the anded constant includes them, clear them now! This only applies to
3298 // unsigned shifts, because a signed shr may bring in set bits!
3299 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003300 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003301 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003302 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3303 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003304
Zhou Sheng290bec52007-03-29 08:15:12 +00003305 if (CI->getValue() == ShrMask) {
3306 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003307 return ReplaceInstUsesWith(TheAnd, Op);
3308 } else if (CI != AndRHS) {
3309 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3310 return &TheAnd;
3311 }
3312 break;
3313 }
3314 case Instruction::AShr:
3315 // Signed shr.
3316 // See if this is shifting in some sign extension, then masking it out
3317 // with an and.
3318 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003319 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003320 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003321 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3322 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003323 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003324 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003325 // Make the argument unsigned.
3326 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003327 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003328 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003329 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003330 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003331 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003332 }
3333 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003334 }
3335 return 0;
3336}
3337
Chris Lattner8b170942002-08-09 23:47:40 +00003338
Chris Lattnera96879a2004-09-29 17:40:11 +00003339/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3340/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003341/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3342/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003343/// insert new instructions.
3344Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003345 bool isSigned, bool Inside,
3346 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003347 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003348 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003349 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003350
Chris Lattnera96879a2004-09-29 17:40:11 +00003351 if (Inside) {
3352 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003353 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003354
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003356 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003357 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003358 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3359 return new ICmpInst(pred, V, Hi);
3360 }
3361
3362 // Emit V-Lo <u Hi-Lo
3363 Constant *NegLo = ConstantExpr::getNeg(Lo);
3364 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003365 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3367 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003368 }
3369
3370 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003371 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003372
Reid Spencere4e40032007-03-21 23:19:50 +00003373 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003374 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003375 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376 ICmpInst::Predicate pred = (isSigned ?
3377 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3378 return new ICmpInst(pred, V, Hi);
3379 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003380
Reid Spencere4e40032007-03-21 23:19:50 +00003381 // Emit V-Lo >u Hi-1-Lo
3382 // Note that Hi has already had one subtracted from it, above.
3383 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003385 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3387 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003388}
3389
Chris Lattner7203e152005-09-18 07:22:02 +00003390// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3391// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3392// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3393// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003394static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003395 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003396 uint32_t BitWidth = Val->getType()->getBitWidth();
3397 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003398
3399 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003400 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003401 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003402 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003403 return true;
3404}
3405
Chris Lattner7203e152005-09-18 07:22:02 +00003406/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3407/// where isSub determines whether the operator is a sub. If we can fold one of
3408/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003409///
3410/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3411/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3412/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3413///
3414/// return (A +/- B).
3415///
3416Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003417 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003418 Instruction &I) {
3419 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3420 if (!LHSI || LHSI->getNumOperands() != 2 ||
3421 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3422
3423 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3424
3425 switch (LHSI->getOpcode()) {
3426 default: return 0;
3427 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003428 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003429 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003430 if ((Mask->getValue().countLeadingZeros() +
3431 Mask->getValue().countPopulation()) ==
3432 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003433 break;
3434
3435 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3436 // part, we don't need any explicit masks to take them out of A. If that
3437 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003438 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003439 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003440 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003441 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003442 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003443 break;
3444 }
3445 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003446 return 0;
3447 case Instruction::Or:
3448 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003449 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003450 if ((Mask->getValue().countLeadingZeros() +
3451 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003452 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003453 break;
3454 return 0;
3455 }
3456
3457 Instruction *New;
3458 if (isSub)
3459 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3460 else
3461 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3462 return InsertNewInstBefore(New, I);
3463}
3464
Chris Lattner7e708292002-06-25 16:13:24 +00003465Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003466 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003467 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003468
Chris Lattnere87597f2004-10-16 18:11:37 +00003469 if (isa<UndefValue>(Op1)) // X & undef -> 0
3470 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3471
Chris Lattner6e7ba452005-01-01 16:22:27 +00003472 // and X, X = X
3473 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003474 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003475
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003476 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003477 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003478 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003479 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3480 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3481 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003482 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003483 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003484 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003485 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003486 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003487 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003488 } else if (isa<ConstantAggregateZero>(Op1)) {
3489 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003490 }
3491 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003492
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003493 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003494 const APInt& AndRHSMask = AndRHS->getValue();
3495 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003496
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003497 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003498 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003499 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003500 Value *Op0LHS = Op0I->getOperand(0);
3501 Value *Op0RHS = Op0I->getOperand(1);
3502 switch (Op0I->getOpcode()) {
3503 case Instruction::Xor:
3504 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003505 // If the mask is only needed on one incoming arm, push it up.
3506 if (Op0I->hasOneUse()) {
3507 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3508 // Not masking anything out for the LHS, move to RHS.
3509 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3510 Op0RHS->getName()+".masked");
3511 InsertNewInstBefore(NewRHS, I);
3512 return BinaryOperator::create(
3513 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003514 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003515 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003516 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3517 // Not masking anything out for the RHS, move to LHS.
3518 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3519 Op0LHS->getName()+".masked");
3520 InsertNewInstBefore(NewLHS, I);
3521 return BinaryOperator::create(
3522 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3523 }
3524 }
3525
Chris Lattner6e7ba452005-01-01 16:22:27 +00003526 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003527 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003528 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3529 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3530 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3531 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3532 return BinaryOperator::createAnd(V, AndRHS);
3533 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3534 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003535 break;
3536
3537 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003538 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3539 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3540 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3541 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3542 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003543 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003544 }
3545
Chris Lattner58403262003-07-23 19:25:52 +00003546 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003547 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003548 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003549 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003550 // If this is an integer truncation or change from signed-to-unsigned, and
3551 // if the source is an and/or with immediate, transform it. This
3552 // frequently occurs for bitfield accesses.
3553 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003554 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003555 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003556 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003557 if (CastOp->getOpcode() == Instruction::And) {
3558 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003559 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3560 // This will fold the two constants together, which may allow
3561 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003562 Instruction *NewCast = CastInst::createTruncOrBitCast(
3563 CastOp->getOperand(0), I.getType(),
3564 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003565 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003566 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003567 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003568 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003569 return BinaryOperator::createAnd(NewCast, C3);
3570 } else if (CastOp->getOpcode() == Instruction::Or) {
3571 // Change: and (cast (or X, C1) to T), C2
3572 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003573 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003574 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3575 return ReplaceInstUsesWith(I, AndRHS);
3576 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003577 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003578 }
Chris Lattner06782f82003-07-23 19:36:21 +00003579 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003580
3581 // Try to fold constant and into select arguments.
3582 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003583 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003584 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003585 if (isa<PHINode>(Op0))
3586 if (Instruction *NV = FoldOpIntoPhi(I))
3587 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003588 }
3589
Chris Lattner8d969642003-03-10 23:06:50 +00003590 Value *Op0NotVal = dyn_castNotVal(Op0);
3591 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003592
Chris Lattner5b62aa72004-06-18 06:07:51 +00003593 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3595
Misha Brukmancb6267b2004-07-30 12:50:08 +00003596 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003597 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003598 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3599 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003600 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003601 return BinaryOperator::createNot(Or);
3602 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003603
3604 {
Chris Lattner003b6202007-06-15 05:58:24 +00003605 Value *A = 0, *B = 0, *C = 0, *D = 0;
3606 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003607 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3608 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003609
3610 // (A|B) & ~(A&B) -> A^B
3611 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3612 if ((A == C && B == D) || (A == D && B == C))
3613 return BinaryOperator::createXor(A, B);
3614 }
3615 }
3616
3617 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003618 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3619 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003620
3621 // ~(A&B) & (A|B) -> A^B
3622 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3623 if ((A == C && B == D) || (A == D && B == C))
3624 return BinaryOperator::createXor(A, B);
3625 }
3626 }
Chris Lattner64daab52006-04-01 08:03:55 +00003627
3628 if (Op0->hasOneUse() &&
3629 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3630 if (A == Op1) { // (A^B)&A -> A&(A^B)
3631 I.swapOperands(); // Simplify below
3632 std::swap(Op0, Op1);
3633 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3634 cast<BinaryOperator>(Op0)->swapOperands();
3635 I.swapOperands(); // Simplify below
3636 std::swap(Op0, Op1);
3637 }
3638 }
3639 if (Op1->hasOneUse() &&
3640 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3641 if (B == Op0) { // B&(A^B) -> B&(B^A)
3642 cast<BinaryOperator>(Op1)->swapOperands();
3643 std::swap(A, B);
3644 }
3645 if (A == Op0) { // A&(A^B) -> A & ~B
3646 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3647 InsertNewInstBefore(NotB, I);
3648 return BinaryOperator::createAnd(A, NotB);
3649 }
3650 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003651 }
3652
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3654 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3655 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003656 return R;
3657
Chris Lattner955f3312004-09-28 21:48:02 +00003658 Value *LHSVal, *RHSVal;
3659 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 ICmpInst::Predicate LHSCC, RHSCC;
3661 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3662 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3663 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3664 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3665 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3666 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3667 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003668 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3669
3670 // Don't try to fold ICMP_SLT + ICMP_ULT.
3671 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3672 ICmpInst::isSignedPredicate(LHSCC) ==
3673 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003674 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003675 ICmpInst::Predicate GT;
3676 if (ICmpInst::isSignedPredicate(LHSCC) ||
3677 (ICmpInst::isEquality(LHSCC) &&
3678 ICmpInst::isSignedPredicate(RHSCC)))
3679 GT = ICmpInst::ICMP_SGT;
3680 else
3681 GT = ICmpInst::ICMP_UGT;
3682
Reid Spencere4d87aa2006-12-23 06:05:41 +00003683 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3684 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003685 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003686 std::swap(LHS, RHS);
3687 std::swap(LHSCst, RHSCst);
3688 std::swap(LHSCC, RHSCC);
3689 }
3690
Reid Spencere4d87aa2006-12-23 06:05:41 +00003691 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003692 // comparing a value against two constants and and'ing the result
3693 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003694 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3695 // (from the FoldICmpLogical check above), that the two constants
3696 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003697 assert(LHSCst != RHSCst && "Compares not folded above?");
3698
3699 switch (LHSCC) {
3700 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003702 switch (RHSCC) {
3703 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3705 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3706 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003708 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3709 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3710 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003711 return ReplaceInstUsesWith(I, LHS);
3712 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003713 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003714 switch (RHSCC) {
3715 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716 case ICmpInst::ICMP_ULT:
3717 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3718 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3719 break; // (X != 13 & X u< 15) -> no change
3720 case ICmpInst::ICMP_SLT:
3721 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3722 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3723 break; // (X != 13 & X s< 15) -> no change
3724 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3725 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3726 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003727 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003728 case ICmpInst::ICMP_NE:
3729 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003730 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3731 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3732 LHSVal->getName()+".off");
3733 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003734 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3735 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003736 }
3737 break; // (X != 13 & X != 15) -> no change
3738 }
3739 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003740 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003741 switch (RHSCC) {
3742 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003743 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3744 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003745 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003746 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3747 break;
3748 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3749 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003750 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003751 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3752 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003753 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003754 break;
3755 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003756 switch (RHSCC) {
3757 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3759 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003760 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003761 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3762 break;
3763 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3764 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003765 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003766 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3767 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003768 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003769 break;
3770 case ICmpInst::ICMP_UGT:
3771 switch (RHSCC) {
3772 default: assert(0 && "Unknown integer condition code!");
3773 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3774 return ReplaceInstUsesWith(I, LHS);
3775 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3776 return ReplaceInstUsesWith(I, RHS);
3777 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3778 break;
3779 case ICmpInst::ICMP_NE:
3780 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3781 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3782 break; // (X u> 13 & X != 15) -> no change
3783 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3784 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3785 true, I);
3786 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3787 break;
3788 }
3789 break;
3790 case ICmpInst::ICMP_SGT:
3791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003793 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003794 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3795 return ReplaceInstUsesWith(I, RHS);
3796 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3797 break;
3798 case ICmpInst::ICMP_NE:
3799 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3800 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3801 break; // (X s> 13 & X != 15) -> no change
3802 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3803 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3804 true, I);
3805 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3806 break;
3807 }
3808 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003809 }
3810 }
3811 }
3812
Chris Lattner6fc205f2006-05-05 06:39:07 +00003813 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003814 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3815 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3816 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3817 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003818 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003819 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003820 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3821 I.getType(), TD) &&
3822 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3823 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003824 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3825 Op1C->getOperand(0),
3826 I.getName());
3827 InsertNewInstBefore(NewOp, I);
3828 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3829 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003830 }
Chris Lattnere511b742006-11-14 07:46:50 +00003831
3832 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003833 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3834 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3835 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003836 SI0->getOperand(1) == SI1->getOperand(1) &&
3837 (SI0->hasOneUse() || SI1->hasOneUse())) {
3838 Instruction *NewOp =
3839 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3840 SI1->getOperand(0),
3841 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003842 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3843 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003844 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003845 }
3846
Chris Lattner99c65742007-10-24 05:38:08 +00003847 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3848 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3849 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3850 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3851 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3852 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3853 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3854 // If either of the constants are nans, then the whole thing returns
3855 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003856 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003857 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3858 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3859 RHS->getOperand(0));
3860 }
3861 }
3862 }
3863
Chris Lattner7e708292002-06-25 16:13:24 +00003864 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003865}
3866
Chris Lattnerafe91a52006-06-15 19:07:26 +00003867/// CollectBSwapParts - Look to see if the specified value defines a single byte
3868/// in the result. If it does, and if the specified byte hasn't been filled in
3869/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003870static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003871 Instruction *I = dyn_cast<Instruction>(V);
3872 if (I == 0) return true;
3873
3874 // If this is an or instruction, it is an inner node of the bswap.
3875 if (I->getOpcode() == Instruction::Or)
3876 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3877 CollectBSwapParts(I->getOperand(1), ByteValues);
3878
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003879 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003880 // If this is a shift by a constant int, and it is "24", then its operand
3881 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003882 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003883 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003884 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003885 8*(ByteValues.size()-1))
3886 return true;
3887
3888 unsigned DestNo;
3889 if (I->getOpcode() == Instruction::Shl) {
3890 // X << 24 defines the top byte with the lowest of the input bytes.
3891 DestNo = ByteValues.size()-1;
3892 } else {
3893 // X >>u 24 defines the low byte with the highest of the input bytes.
3894 DestNo = 0;
3895 }
3896
3897 // If the destination byte value is already defined, the values are or'd
3898 // together, which isn't a bswap (unless it's an or of the same bits).
3899 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3900 return true;
3901 ByteValues[DestNo] = I->getOperand(0);
3902 return false;
3903 }
3904
3905 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3906 // don't have this.
3907 Value *Shift = 0, *ShiftLHS = 0;
3908 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3909 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3910 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3911 return true;
3912 Instruction *SI = cast<Instruction>(Shift);
3913
3914 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003915 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3916 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003917 return true;
3918
3919 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3920 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003921 if (AndAmt->getValue().getActiveBits() > 64)
3922 return true;
3923 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003924 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003925 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003926 break;
3927 // Unknown mask for bswap.
3928 if (DestByte == ByteValues.size()) return true;
3929
Reid Spencerb83eb642006-10-20 07:07:24 +00003930 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003931 unsigned SrcByte;
3932 if (SI->getOpcode() == Instruction::Shl)
3933 SrcByte = DestByte - ShiftBytes;
3934 else
3935 SrcByte = DestByte + ShiftBytes;
3936
3937 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3938 if (SrcByte != ByteValues.size()-DestByte-1)
3939 return true;
3940
3941 // If the destination byte value is already defined, the values are or'd
3942 // together, which isn't a bswap (unless it's an or of the same bits).
3943 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3944 return true;
3945 ByteValues[DestByte] = SI->getOperand(0);
3946 return false;
3947}
3948
3949/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3950/// If so, insert the new bswap intrinsic and return it.
3951Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003952 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3953 if (!ITy || ITy->getBitWidth() % 16)
3954 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003955
3956 /// ByteValues - For each byte of the result, we keep track of which value
3957 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003958 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003959 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003960
3961 // Try to find all the pieces corresponding to the bswap.
3962 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3963 CollectBSwapParts(I.getOperand(1), ByteValues))
3964 return 0;
3965
3966 // Check to see if all of the bytes come from the same value.
3967 Value *V = ByteValues[0];
3968 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3969
3970 // Check to make sure that all of the bytes come from the same value.
3971 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3972 if (ByteValues[i] != V)
3973 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003974 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003975 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003976 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003977 return new CallInst(F, V);
3978}
3979
3980
Chris Lattner7e708292002-06-25 16:13:24 +00003981Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003982 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003984
Chris Lattner42593e62007-03-24 23:56:43 +00003985 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003986 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003987
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003988 // or X, X = X
3989 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003990 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003991
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003992 // See if we can simplify any instructions used by the instruction whose sole
3993 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003994 if (!isa<VectorType>(I.getType())) {
3995 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3996 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3997 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3998 KnownZero, KnownOne))
3999 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004000 } else if (isa<ConstantAggregateZero>(Op1)) {
4001 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4002 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4003 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4004 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004005 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004006
4007
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004008
Chris Lattner3f5b8772002-05-06 16:14:14 +00004009 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004010 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004011 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004012 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4013 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004014 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004015 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004016 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004017 return BinaryOperator::createAnd(Or,
4018 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004019 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004020
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004021 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4022 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004023 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004024 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004025 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004026 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004027 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004028 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004029
4030 // Try to fold constant and into select arguments.
4031 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004032 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004033 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004034 if (isa<PHINode>(Op0))
4035 if (Instruction *NV = FoldOpIntoPhi(I))
4036 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004037 }
4038
Chris Lattner4f637d42006-01-06 17:59:59 +00004039 Value *A = 0, *B = 0;
4040 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004041
4042 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4043 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4044 return ReplaceInstUsesWith(I, Op1);
4045 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4046 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4047 return ReplaceInstUsesWith(I, Op0);
4048
Chris Lattner6423d4c2006-07-10 20:25:24 +00004049 // (A | B) | C and A | (B | C) -> bswap if possible.
4050 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004051 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004052 match(Op1, m_Or(m_Value(), m_Value())) ||
4053 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4054 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004055 if (Instruction *BSwap = MatchBSwap(I))
4056 return BSwap;
4057 }
4058
Chris Lattner6e4c6492005-05-09 04:58:36 +00004059 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4060 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004061 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004062 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4063 InsertNewInstBefore(NOr, I);
4064 NOr->takeName(Op0);
4065 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004066 }
4067
4068 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4069 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004070 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004071 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4072 InsertNewInstBefore(NOr, I);
4073 NOr->takeName(Op0);
4074 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004075 }
4076
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004077 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004078 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004079 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4080 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004081 Value *V1 = 0, *V2 = 0, *V3 = 0;
4082 C1 = dyn_cast<ConstantInt>(C);
4083 C2 = dyn_cast<ConstantInt>(D);
4084 if (C1 && C2) { // (A & C1)|(B & C2)
4085 // If we have: ((V + N) & C1) | (V & C2)
4086 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4087 // replace with V+N.
4088 if (C1->getValue() == ~C2->getValue()) {
4089 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4090 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4091 // Add commutes, try both ways.
4092 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4093 return ReplaceInstUsesWith(I, A);
4094 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4095 return ReplaceInstUsesWith(I, A);
4096 }
4097 // Or commutes, try both ways.
4098 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4099 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4100 // Add commutes, try both ways.
4101 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4102 return ReplaceInstUsesWith(I, B);
4103 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4104 return ReplaceInstUsesWith(I, B);
4105 }
4106 }
Chris Lattner044e5332007-04-08 08:01:49 +00004107 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004108 }
4109
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004110 // Check to see if we have any common things being and'ed. If so, find the
4111 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004112 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4113 if (A == B) // (A & C)|(A & D) == A & (C|D)
4114 V1 = A, V2 = C, V3 = D;
4115 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4116 V1 = A, V2 = B, V3 = C;
4117 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4118 V1 = C, V2 = A, V3 = D;
4119 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4120 V1 = C, V2 = A, V3 = B;
4121
4122 if (V1) {
4123 Value *Or =
4124 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4125 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004126 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004127 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004128 }
Chris Lattnere511b742006-11-14 07:46:50 +00004129
4130 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004131 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4132 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4133 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004134 SI0->getOperand(1) == SI1->getOperand(1) &&
4135 (SI0->hasOneUse() || SI1->hasOneUse())) {
4136 Instruction *NewOp =
4137 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4138 SI1->getOperand(0),
4139 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004140 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4141 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004142 }
4143 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004144
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004145 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4146 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004147 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004148 } else {
4149 A = 0;
4150 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004151 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004152 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4153 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004154 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004155
Misha Brukmancb6267b2004-07-30 12:50:08 +00004156 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004157 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4158 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4159 I.getName()+".demorgan"), I);
4160 return BinaryOperator::createNot(And);
4161 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004162 }
Chris Lattnera2881962003-02-18 19:28:33 +00004163
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4165 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4166 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004167 return R;
4168
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004169 Value *LHSVal, *RHSVal;
4170 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004171 ICmpInst::Predicate LHSCC, RHSCC;
4172 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4173 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4174 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4175 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4176 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4177 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4178 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004179 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4180 // We can't fold (ugt x, C) | (sgt x, C2).
4181 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004182 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004184 bool NeedsSwap;
4185 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004186 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004187 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004188 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004189
4190 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004191 std::swap(LHS, RHS);
4192 std::swap(LHSCst, RHSCst);
4193 std::swap(LHSCC, RHSCC);
4194 }
4195
Reid Spencere4d87aa2006-12-23 06:05:41 +00004196 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004197 // comparing a value against two constants and or'ing the result
4198 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004199 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4200 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004201 // equal.
4202 assert(LHSCst != RHSCst && "Compares not folded above?");
4203
4204 switch (LHSCC) {
4205 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004206 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004207 switch (RHSCC) {
4208 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004209 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004210 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4211 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4212 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4213 LHSVal->getName()+".off");
4214 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004215 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004216 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004217 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 break; // (X == 13 | X == 15) -> no change
4219 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4220 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004221 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004222 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4223 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4224 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004225 return ReplaceInstUsesWith(I, RHS);
4226 }
4227 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004228 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004229 switch (RHSCC) {
4230 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004231 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4232 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4233 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004234 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004235 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4236 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4237 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004238 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004239 }
4240 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004242 switch (RHSCC) {
4243 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004244 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004245 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004246 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004247 // If RHSCst is [us]MAXINT, it is always false. Not handling
4248 // this can cause overflow.
4249 if (RHSCst->isMaxValue(false))
4250 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004251 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4252 false, I);
4253 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4254 break;
4255 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4256 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004257 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004258 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4259 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004260 }
4261 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004263 switch (RHSCC) {
4264 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004265 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4266 break;
4267 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004268 // If RHSCst is [us]MAXINT, it is always false. Not handling
4269 // this can cause overflow.
4270 if (RHSCst->isMaxValue(true))
4271 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4273 false, I);
4274 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4275 break;
4276 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4277 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4278 return ReplaceInstUsesWith(I, RHS);
4279 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4280 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004281 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004282 break;
4283 case ICmpInst::ICMP_UGT:
4284 switch (RHSCC) {
4285 default: assert(0 && "Unknown integer condition code!");
4286 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4287 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4288 return ReplaceInstUsesWith(I, LHS);
4289 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4290 break;
4291 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4292 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004293 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004294 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4295 break;
4296 }
4297 break;
4298 case ICmpInst::ICMP_SGT:
4299 switch (RHSCC) {
4300 default: assert(0 && "Unknown integer condition code!");
4301 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4302 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4303 return ReplaceInstUsesWith(I, LHS);
4304 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4305 break;
4306 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4307 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004308 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4310 break;
4311 }
4312 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004313 }
4314 }
4315 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004316
4317 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004318 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004319 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004320 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4321 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004322 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004323 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004324 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4325 I.getType(), TD) &&
4326 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4327 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004328 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4329 Op1C->getOperand(0),
4330 I.getName());
4331 InsertNewInstBefore(NewOp, I);
4332 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4333 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004334 }
Chris Lattner99c65742007-10-24 05:38:08 +00004335 }
4336
4337
4338 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4339 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4340 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4341 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004342 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4343 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004344 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4345 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4346 // If either of the constants are nans, then the whole thing returns
4347 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004348 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004349 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4350
4351 // Otherwise, no need to compare the two constants, compare the
4352 // rest.
4353 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4354 RHS->getOperand(0));
4355 }
4356 }
4357 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004358
Chris Lattner7e708292002-06-25 16:13:24 +00004359 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004360}
4361
Chris Lattnerc317d392004-02-16 01:20:27 +00004362// XorSelf - Implements: X ^ X --> 0
4363struct XorSelf {
4364 Value *RHS;
4365 XorSelf(Value *rhs) : RHS(rhs) {}
4366 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4367 Instruction *apply(BinaryOperator &Xor) const {
4368 return &Xor;
4369 }
4370};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004371
4372
Chris Lattner7e708292002-06-25 16:13:24 +00004373Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004374 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004376
Chris Lattnere87597f2004-10-16 18:11:37 +00004377 if (isa<UndefValue>(Op1))
4378 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4379
Chris Lattnerc317d392004-02-16 01:20:27 +00004380 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4381 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004382 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004383 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004384 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004385
4386 // See if we can simplify any instructions used by the instruction whose sole
4387 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004388 if (!isa<VectorType>(I.getType())) {
4389 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4390 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4391 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4392 KnownZero, KnownOne))
4393 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004394 } else if (isa<ConstantAggregateZero>(Op1)) {
4395 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004396 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004397
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004398 // Is this a ~ operation?
4399 if (Value *NotOp = dyn_castNotVal(&I)) {
4400 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4401 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4402 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4403 if (Op0I->getOpcode() == Instruction::And ||
4404 Op0I->getOpcode() == Instruction::Or) {
4405 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4406 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4407 Instruction *NotY =
4408 BinaryOperator::createNot(Op0I->getOperand(1),
4409 Op0I->getOperand(1)->getName()+".not");
4410 InsertNewInstBefore(NotY, I);
4411 if (Op0I->getOpcode() == Instruction::And)
4412 return BinaryOperator::createOr(Op0NotVal, NotY);
4413 else
4414 return BinaryOperator::createAnd(Op0NotVal, NotY);
4415 }
4416 }
4417 }
4418 }
4419
4420
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004421 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004422 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4423 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4424 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004425 return new ICmpInst(ICI->getInversePredicate(),
4426 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004427
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004428 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4429 return new FCmpInst(FCI->getInversePredicate(),
4430 FCI->getOperand(0), FCI->getOperand(1));
4431 }
4432
Reid Spencere4d87aa2006-12-23 06:05:41 +00004433 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004434 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004435 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4436 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004437 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4438 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004439 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004440 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004441 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004442
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004443 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004444 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004445 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004446 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004447 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4448 return BinaryOperator::createSub(
4449 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004450 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004451 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004452 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004453 // (X + C) ^ signbit -> (X + C + signbit)
4454 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4455 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004456
Chris Lattner7c4049c2004-01-12 19:35:11 +00004457 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004458 } else if (Op0I->getOpcode() == Instruction::Or) {
4459 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004460 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004461 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4462 // Anything in both C1 and C2 is known to be zero, remove it from
4463 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004464 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004465 NewRHS = ConstantExpr::getAnd(NewRHS,
4466 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004467 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004468 I.setOperand(0, Op0I->getOperand(0));
4469 I.setOperand(1, NewRHS);
4470 return &I;
4471 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004472 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004473 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004474 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004475
4476 // Try to fold constant and into select arguments.
4477 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004478 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004479 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004480 if (isa<PHINode>(Op0))
4481 if (Instruction *NV = FoldOpIntoPhi(I))
4482 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004483 }
4484
Chris Lattner8d969642003-03-10 23:06:50 +00004485 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004486 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004487 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004488
Chris Lattner8d969642003-03-10 23:06:50 +00004489 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004490 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004491 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004492
Chris Lattner318bf792007-03-18 22:51:34 +00004493
4494 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4495 if (Op1I) {
4496 Value *A, *B;
4497 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4498 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004499 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004500 I.swapOperands();
4501 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004502 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004503 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004504 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004505 }
Chris Lattner318bf792007-03-18 22:51:34 +00004506 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4507 if (Op0 == A) // A^(A^B) == B
4508 return ReplaceInstUsesWith(I, B);
4509 else if (Op0 == B) // A^(B^A) == B
4510 return ReplaceInstUsesWith(I, A);
4511 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004512 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004513 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004514 std::swap(A, B);
4515 }
Chris Lattner318bf792007-03-18 22:51:34 +00004516 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004517 I.swapOperands(); // Simplified below.
4518 std::swap(Op0, Op1);
4519 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004520 }
Chris Lattner318bf792007-03-18 22:51:34 +00004521 }
4522
4523 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4524 if (Op0I) {
4525 Value *A, *B;
4526 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4527 if (A == Op1) // (B|A)^B == (A|B)^B
4528 std::swap(A, B);
4529 if (B == Op1) { // (A|B)^B == A & ~B
4530 Instruction *NotB =
4531 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4532 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004533 }
Chris Lattner318bf792007-03-18 22:51:34 +00004534 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4535 if (Op1 == A) // (A^B)^A == B
4536 return ReplaceInstUsesWith(I, B);
4537 else if (Op1 == B) // (B^A)^A == B
4538 return ReplaceInstUsesWith(I, A);
4539 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4540 if (A == Op1) // (A&B)^A -> (B&A)^A
4541 std::swap(A, B);
4542 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004543 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004544 Instruction *N =
4545 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004546 return BinaryOperator::createAnd(N, Op1);
4547 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004548 }
Chris Lattner318bf792007-03-18 22:51:34 +00004549 }
4550
4551 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4552 if (Op0I && Op1I && Op0I->isShift() &&
4553 Op0I->getOpcode() == Op1I->getOpcode() &&
4554 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4555 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4556 Instruction *NewOp =
4557 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4558 Op1I->getOperand(0),
4559 Op0I->getName()), I);
4560 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4561 Op1I->getOperand(1));
4562 }
4563
4564 if (Op0I && Op1I) {
4565 Value *A, *B, *C, *D;
4566 // (A & B)^(A | B) -> A ^ B
4567 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4568 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4569 if ((A == C && B == D) || (A == D && B == C))
4570 return BinaryOperator::createXor(A, B);
4571 }
4572 // (A | B)^(A & B) -> A ^ B
4573 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4574 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4575 if ((A == C && B == D) || (A == D && B == C))
4576 return BinaryOperator::createXor(A, B);
4577 }
4578
4579 // (A & B)^(C & D)
4580 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4581 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4582 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4583 // (X & Y)^(X & Y) -> (Y^Z) & X
4584 Value *X = 0, *Y = 0, *Z = 0;
4585 if (A == C)
4586 X = A, Y = B, Z = D;
4587 else if (A == D)
4588 X = A, Y = B, Z = C;
4589 else if (B == C)
4590 X = B, Y = A, Z = D;
4591 else if (B == D)
4592 X = B, Y = A, Z = C;
4593
4594 if (X) {
4595 Instruction *NewOp =
4596 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4597 return BinaryOperator::createAnd(NewOp, X);
4598 }
4599 }
4600 }
4601
Reid Spencere4d87aa2006-12-23 06:05:41 +00004602 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4603 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4604 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004605 return R;
4606
Chris Lattner6fc205f2006-05-05 06:39:07 +00004607 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004608 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004609 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004610 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4611 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004612 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004613 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004614 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4615 I.getType(), TD) &&
4616 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4617 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004618 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4619 Op1C->getOperand(0),
4620 I.getName());
4621 InsertNewInstBefore(NewOp, I);
4622 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4623 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004624 }
Chris Lattner99c65742007-10-24 05:38:08 +00004625 }
Chris Lattner7e708292002-06-25 16:13:24 +00004626 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004627}
4628
Chris Lattnera96879a2004-09-29 17:40:11 +00004629/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4630/// overflowed for this type.
4631static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004632 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004633 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004634
Reid Spencere4e40032007-03-21 23:19:50 +00004635 if (IsSigned)
4636 if (In2->getValue().isNegative())
4637 return Result->getValue().sgt(In1->getValue());
4638 else
4639 return Result->getValue().slt(In1->getValue());
4640 else
4641 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004642}
4643
Chris Lattner574da9b2005-01-13 20:14:25 +00004644/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4645/// code necessary to compute the offset from the base pointer (without adding
4646/// in the base pointer). Return the result as a signed integer of intptr size.
4647static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4648 TargetData &TD = IC.getTargetData();
4649 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004650 const Type *IntPtrTy = TD.getIntPtrType();
4651 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004652
4653 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004654 unsigned IntPtrWidth = TD.getPointerSize()*8;
4655 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004656
Chris Lattner574da9b2005-01-13 20:14:25 +00004657 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4658 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004659 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004660 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4661 if (OpC->isZero()) continue;
4662
4663 // Handle a struct index, which adds its field offset to the pointer.
4664 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4665 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4666
4667 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4668 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004669 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004670 Result = IC.InsertNewInstBefore(
4671 BinaryOperator::createAdd(Result,
4672 ConstantInt::get(IntPtrTy, Size),
4673 GEP->getName()+".offs"), I);
4674 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004675 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004676
4677 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4678 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4679 Scale = ConstantExpr::getMul(OC, Scale);
4680 if (Constant *RC = dyn_cast<Constant>(Result))
4681 Result = ConstantExpr::getAdd(RC, Scale);
4682 else {
4683 // Emit an add instruction.
4684 Result = IC.InsertNewInstBefore(
4685 BinaryOperator::createAdd(Result, Scale,
4686 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004687 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004688 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004689 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004690 // Convert to correct type.
4691 if (Op->getType() != IntPtrTy) {
4692 if (Constant *OpC = dyn_cast<Constant>(Op))
4693 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4694 else
4695 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4696 Op->getName()+".c"), I);
4697 }
4698 if (Size != 1) {
4699 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4700 if (Constant *OpC = dyn_cast<Constant>(Op))
4701 Op = ConstantExpr::getMul(OpC, Scale);
4702 else // We'll let instcombine(mul) convert this to a shl if possible.
4703 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4704 GEP->getName()+".idx"), I);
4705 }
4706
4707 // Emit an add instruction.
4708 if (isa<Constant>(Op) && isa<Constant>(Result))
4709 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4710 cast<Constant>(Result));
4711 else
4712 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4713 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004714 }
4715 return Result;
4716}
4717
Reid Spencere4d87aa2006-12-23 06:05:41 +00004718/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004719/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004720Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4721 ICmpInst::Predicate Cond,
4722 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004723 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004724
4725 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4726 if (isa<PointerType>(CI->getOperand(0)->getType()))
4727 RHS = CI->getOperand(0);
4728
Chris Lattner574da9b2005-01-13 20:14:25 +00004729 Value *PtrBase = GEPLHS->getOperand(0);
4730 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004731 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4732 // This transformation is valid because we know pointers can't overflow.
4733 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4735 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004736 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004737 // If the base pointers are different, but the indices are the same, just
4738 // compare the base pointer.
4739 if (PtrBase != GEPRHS->getOperand(0)) {
4740 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004741 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004742 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004743 if (IndicesTheSame)
4744 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4745 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4746 IndicesTheSame = false;
4747 break;
4748 }
4749
4750 // If all indices are the same, just compare the base pointers.
4751 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004752 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4753 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004754
4755 // Otherwise, the base pointers are different and the indices are
4756 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004757 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004758 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004759
Chris Lattnere9d782b2005-01-13 22:25:21 +00004760 // If one of the GEPs has all zero indices, recurse.
4761 bool AllZeros = true;
4762 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4763 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4764 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4765 AllZeros = false;
4766 break;
4767 }
4768 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004769 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4770 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004771
4772 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004773 AllZeros = true;
4774 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4775 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4776 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4777 AllZeros = false;
4778 break;
4779 }
4780 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004781 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004782
Chris Lattner4401c9c2005-01-14 00:20:05 +00004783 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4784 // If the GEPs only differ by one index, compare it.
4785 unsigned NumDifferences = 0; // Keep track of # differences.
4786 unsigned DiffOperand = 0; // The operand that differs.
4787 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4788 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004789 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4790 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004791 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004792 NumDifferences = 2;
4793 break;
4794 } else {
4795 if (NumDifferences++) break;
4796 DiffOperand = i;
4797 }
4798 }
4799
4800 if (NumDifferences == 0) // SAME GEP?
4801 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004802 ConstantInt::get(Type::Int1Ty,
4803 isTrueWhenEqual(Cond)));
4804
Chris Lattner4401c9c2005-01-14 00:20:05 +00004805 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004806 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4807 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004808 // Make sure we do a signed comparison here.
4809 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004810 }
4811 }
4812
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004814 // the result to fold to a constant!
4815 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4816 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4817 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4818 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4819 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004821 }
4822 }
4823 return 0;
4824}
4825
Reid Spencere4d87aa2006-12-23 06:05:41 +00004826Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4827 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004828 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004829
Chris Lattner58e97462007-01-14 19:42:17 +00004830 // Fold trivial predicates.
4831 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4832 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4833 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4834 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4835
4836 // Simplify 'fcmp pred X, X'
4837 if (Op0 == Op1) {
4838 switch (I.getPredicate()) {
4839 default: assert(0 && "Unknown predicate!");
4840 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4841 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4842 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4843 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4844 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4845 case FCmpInst::FCMP_OLT: // True if ordered and less than
4846 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4847 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4848
4849 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4850 case FCmpInst::FCMP_ULT: // True if unordered or less than
4851 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4852 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4853 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4854 I.setPredicate(FCmpInst::FCMP_UNO);
4855 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4856 return &I;
4857
4858 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4859 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4860 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4861 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4862 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4863 I.setPredicate(FCmpInst::FCMP_ORD);
4864 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4865 return &I;
4866 }
4867 }
4868
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004870 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004871
Reid Spencere4d87aa2006-12-23 06:05:41 +00004872 // Handle fcmp with constant RHS
4873 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4874 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4875 switch (LHSI->getOpcode()) {
4876 case Instruction::PHI:
4877 if (Instruction *NV = FoldOpIntoPhi(I))
4878 return NV;
4879 break;
4880 case Instruction::Select:
4881 // If either operand of the select is a constant, we can fold the
4882 // comparison into the select arms, which will cause one to be
4883 // constant folded and the select turned into a bitwise or.
4884 Value *Op1 = 0, *Op2 = 0;
4885 if (LHSI->hasOneUse()) {
4886 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4887 // Fold the known value into the constant operand.
4888 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4889 // Insert a new FCmp of the other select operand.
4890 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4891 LHSI->getOperand(2), RHSC,
4892 I.getName()), I);
4893 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4894 // Fold the known value into the constant operand.
4895 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4896 // Insert a new FCmp of the other select operand.
4897 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4898 LHSI->getOperand(1), RHSC,
4899 I.getName()), I);
4900 }
4901 }
4902
4903 if (Op1)
4904 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4905 break;
4906 }
4907 }
4908
4909 return Changed ? &I : 0;
4910}
4911
4912Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4913 bool Changed = SimplifyCompare(I);
4914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4915 const Type *Ty = Op0->getType();
4916
4917 // icmp X, X
4918 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004919 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4920 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004921
4922 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004923 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004924
Reid Spencere4d87aa2006-12-23 06:05:41 +00004925 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004926 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004927 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4928 isa<ConstantPointerNull>(Op0)) &&
4929 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004930 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004931 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4932 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004933
Reid Spencere4d87aa2006-12-23 06:05:41 +00004934 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004935 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004936 switch (I.getPredicate()) {
4937 default: assert(0 && "Invalid icmp instruction!");
4938 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004939 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004940 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004941 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004942 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004944 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004945
Reid Spencere4d87aa2006-12-23 06:05:41 +00004946 case ICmpInst::ICMP_UGT:
4947 case ICmpInst::ICMP_SGT:
4948 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004949 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004950 case ICmpInst::ICMP_ULT:
4951 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004952 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4953 InsertNewInstBefore(Not, I);
4954 return BinaryOperator::createAnd(Not, Op1);
4955 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004956 case ICmpInst::ICMP_UGE:
4957 case ICmpInst::ICMP_SGE:
4958 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004959 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004960 case ICmpInst::ICMP_ULE:
4961 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004962 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4963 InsertNewInstBefore(Not, I);
4964 return BinaryOperator::createOr(Not, Op1);
4965 }
4966 }
Chris Lattner8b170942002-08-09 23:47:40 +00004967 }
4968
Chris Lattner2be51ae2004-06-09 04:24:29 +00004969 // See if we are doing a comparison between a constant and an instruction that
4970 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004971 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004972 Value *A, *B;
4973
Chris Lattnerb6566012008-01-05 01:18:20 +00004974 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4975 if (I.isEquality() && CI->isNullValue() &&
4976 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4977 // (icmp cond A B) if cond is equality
4978 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004979 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004980
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981 switch (I.getPredicate()) {
4982 default: break;
4983 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4984 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004985 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004986 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4987 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4988 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4989 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004990 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4991 if (CI->isMinValue(true))
4992 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4993 ConstantInt::getAllOnesValue(Op0->getType()));
4994
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004996
Reid Spencere4d87aa2006-12-23 06:05:41 +00004997 case ICmpInst::ICMP_SLT:
4998 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004999 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5001 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5002 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5003 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5004 break;
5005
5006 case ICmpInst::ICMP_UGT:
5007 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005008 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005009 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5010 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5011 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5012 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005013
5014 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5015 if (CI->isMaxValue(true))
5016 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5017 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005018 break;
5019
5020 case ICmpInst::ICMP_SGT:
5021 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005022 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005023 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5024 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5025 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5026 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5027 break;
5028
5029 case ICmpInst::ICMP_ULE:
5030 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005031 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005032 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5033 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5034 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5035 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5036 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005037
Reid Spencere4d87aa2006-12-23 06:05:41 +00005038 case ICmpInst::ICMP_SLE:
5039 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005040 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005041 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5042 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5043 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5044 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5045 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005046
Reid Spencere4d87aa2006-12-23 06:05:41 +00005047 case ICmpInst::ICMP_UGE:
5048 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005049 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005050 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5051 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5052 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5053 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5054 break;
5055
5056 case ICmpInst::ICMP_SGE:
5057 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005058 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005059 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5060 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5061 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5062 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5063 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005064 }
5065
Reid Spencere4d87aa2006-12-23 06:05:41 +00005066 // If we still have a icmp le or icmp ge instruction, turn it into the
5067 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005068 // already been handled above, this requires little checking.
5069 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005070 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005071 default: break;
5072 case ICmpInst::ICMP_ULE:
5073 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5074 case ICmpInst::ICMP_SLE:
5075 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5076 case ICmpInst::ICMP_UGE:
5077 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5078 case ICmpInst::ICMP_SGE:
5079 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005080 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005081
5082 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005083 // in the input. If this comparison is a normal comparison, it demands all
5084 // bits, if it is a sign bit comparison, it only demands the sign bit.
5085
5086 bool UnusedBit;
5087 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5088
Reid Spencer0460fb32007-03-22 20:36:03 +00005089 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5090 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005091 if (SimplifyDemandedBits(Op0,
5092 isSignBit ? APInt::getSignBit(BitWidth)
5093 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005094 KnownZero, KnownOne, 0))
5095 return &I;
5096
5097 // Given the known and unknown bits, compute a range that the LHS could be
5098 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005099 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005100 // Compute the Min, Max and RHS values based on the known bits. For the
5101 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005102 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5103 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005104 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005105 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5106 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005107 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005108 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5109 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 }
5111 switch (I.getPredicate()) { // LE/GE have been folded already.
5112 default: assert(0 && "Unknown icmp opcode!");
5113 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005114 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005115 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005116 break;
5117 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005118 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005119 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005120 break;
5121 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005122 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005123 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005124 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005125 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 break;
5127 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005128 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005129 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005130 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005131 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005132 break;
5133 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005134 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005135 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005136 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005137 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005138 break;
5139 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005140 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005141 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005142 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005143 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005144 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005145 }
5146 }
5147
Reid Spencere4d87aa2006-12-23 06:05:41 +00005148 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005149 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005150 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005151 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005152 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5153 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005154 }
5155
Chris Lattner01deb9d2007-04-03 17:43:25 +00005156 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005157 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5158 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5159 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005160 case Instruction::GetElementPtr:
5161 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005162 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005163 bool isAllZeros = true;
5164 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5165 if (!isa<Constant>(LHSI->getOperand(i)) ||
5166 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5167 isAllZeros = false;
5168 break;
5169 }
5170 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005172 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5173 }
5174 break;
5175
Chris Lattner6970b662005-04-23 15:31:55 +00005176 case Instruction::PHI:
5177 if (Instruction *NV = FoldOpIntoPhi(I))
5178 return NV;
5179 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005180 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005181 // If either operand of the select is a constant, we can fold the
5182 // comparison into the select arms, which will cause one to be
5183 // constant folded and the select turned into a bitwise or.
5184 Value *Op1 = 0, *Op2 = 0;
5185 if (LHSI->hasOneUse()) {
5186 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5187 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005188 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5189 // Insert a new ICmp of the other select operand.
5190 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5191 LHSI->getOperand(2), RHSC,
5192 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005193 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5194 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5196 // Insert a new ICmp of the other select operand.
5197 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5198 LHSI->getOperand(1), RHSC,
5199 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005200 }
5201 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005202
Chris Lattner6970b662005-04-23 15:31:55 +00005203 if (Op1)
5204 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5205 break;
5206 }
Chris Lattner4802d902007-04-06 18:57:34 +00005207 case Instruction::Malloc:
5208 // If we have (malloc != null), and if the malloc has a single use, we
5209 // can assume it is successful and remove the malloc.
5210 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5211 AddToWorkList(LHSI);
5212 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5213 !isTrueWhenEqual(I)));
5214 }
5215 break;
5216 }
Chris Lattner6970b662005-04-23 15:31:55 +00005217 }
5218
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005220 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005221 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005222 return NI;
5223 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005224 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5225 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005226 return NI;
5227
Reid Spencere4d87aa2006-12-23 06:05:41 +00005228 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005229 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5230 // now.
5231 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5232 if (isa<PointerType>(Op0->getType()) &&
5233 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005234 // We keep moving the cast from the left operand over to the right
5235 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005236 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005237
Chris Lattner57d86372007-01-06 01:45:59 +00005238 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5239 // so eliminate it as well.
5240 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5241 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005242
Chris Lattnerde90b762003-11-03 04:25:02 +00005243 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005244 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005245 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005246 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005247 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005248 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005249 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005250 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005251 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005252 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005253 }
Chris Lattner57d86372007-01-06 01:45:59 +00005254 }
5255
5256 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005257 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005258 // This comes up when you have code like
5259 // int X = A < B;
5260 // if (X) ...
5261 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005262 // with a constant or another cast from the same type.
5263 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005264 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005265 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005266 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005267
Chris Lattner65b72ba2006-09-18 04:22:48 +00005268 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005269 Value *A, *B, *C, *D;
5270 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5271 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5272 Value *OtherVal = A == Op1 ? B : A;
5273 return new ICmpInst(I.getPredicate(), OtherVal,
5274 Constant::getNullValue(A->getType()));
5275 }
5276
5277 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5278 // A^c1 == C^c2 --> A == C^(c1^c2)
5279 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5280 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5281 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005282 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005283 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5284 return new ICmpInst(I.getPredicate(), A,
5285 InsertNewInstBefore(Xor, I));
5286 }
5287
5288 // A^B == A^D -> B == D
5289 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5290 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5291 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5292 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5293 }
5294 }
5295
5296 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5297 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005298 // A == (A^B) -> B == 0
5299 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005300 return new ICmpInst(I.getPredicate(), OtherVal,
5301 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005302 }
5303 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005304 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005305 return new ICmpInst(I.getPredicate(), B,
5306 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005307 }
5308 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005309 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005310 return new ICmpInst(I.getPredicate(), B,
5311 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005312 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005313
Chris Lattner9c2328e2006-11-14 06:06:06 +00005314 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5315 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5316 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5317 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5318 Value *X = 0, *Y = 0, *Z = 0;
5319
5320 if (A == C) {
5321 X = B; Y = D; Z = A;
5322 } else if (A == D) {
5323 X = B; Y = C; Z = A;
5324 } else if (B == C) {
5325 X = A; Y = D; Z = B;
5326 } else if (B == D) {
5327 X = A; Y = C; Z = B;
5328 }
5329
5330 if (X) { // Build (X^Y) & Z
5331 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5332 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5333 I.setOperand(0, Op1);
5334 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5335 return &I;
5336 }
5337 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005338 }
Chris Lattner7e708292002-06-25 16:13:24 +00005339 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005340}
5341
Chris Lattner562ef782007-06-20 23:46:26 +00005342
5343/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5344/// and CmpRHS are both known to be integer constants.
5345Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5346 ConstantInt *DivRHS) {
5347 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5348 const APInt &CmpRHSV = CmpRHS->getValue();
5349
5350 // FIXME: If the operand types don't match the type of the divide
5351 // then don't attempt this transform. The code below doesn't have the
5352 // logic to deal with a signed divide and an unsigned compare (and
5353 // vice versa). This is because (x /s C1) <s C2 produces different
5354 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5355 // (x /u C1) <u C2. Simply casting the operands and result won't
5356 // work. :( The if statement below tests that condition and bails
5357 // if it finds it.
5358 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5359 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5360 return 0;
5361 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005362 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005363
5364 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5365 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5366 // C2 (CI). By solving for X we can turn this into a range check
5367 // instead of computing a divide.
5368 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5369
5370 // Determine if the product overflows by seeing if the product is
5371 // not equal to the divide. Make sure we do the same kind of divide
5372 // as in the LHS instruction that we're folding.
5373 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5374 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5375
5376 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005377 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005378
Chris Lattner1dbfd482007-06-21 18:11:19 +00005379 // Figure out the interval that is being checked. For example, a comparison
5380 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5381 // Compute this interval based on the constants involved and the signedness of
5382 // the compare/divide. This computes a half-open interval, keeping track of
5383 // whether either value in the interval overflows. After analysis each
5384 // overflow variable is set to 0 if it's corresponding bound variable is valid
5385 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5386 int LoOverflow = 0, HiOverflow = 0;
5387 ConstantInt *LoBound = 0, *HiBound = 0;
5388
5389
Chris Lattner562ef782007-06-20 23:46:26 +00005390 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005391 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005392 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005393 HiOverflow = LoOverflow = ProdOV;
5394 if (!HiOverflow)
5395 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005396 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005397 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005398 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005399 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5400 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005401 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005402 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5403 HiOverflow = LoOverflow = ProdOV;
5404 if (!HiOverflow)
5405 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005406 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005407 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005408 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5409 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005410 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005411 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005412 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005413 }
Dan Gohman76491272008-02-13 22:09:18 +00005414 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005415 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005416 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005417 LoBound = AddOne(DivRHS);
5418 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005419 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5420 HiOverflow = 1; // [INTMIN+1, overflow)
5421 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5422 }
Dan Gohman76491272008-02-13 22:09:18 +00005423 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005424 // e.g. X/-5 op 3 --> [-19, -14)
5425 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005426 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005427 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005428 HiBound = AddOne(Prod);
5429 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005430 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005431 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005432 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005433 HiBound = Subtract(Prod, DivRHS);
5434 }
5435
Chris Lattner1dbfd482007-06-21 18:11:19 +00005436 // Dividing by a negative swaps the condition. LT <-> GT
5437 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005438 }
5439
5440 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005441 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005442 default: assert(0 && "Unhandled icmp opcode!");
5443 case ICmpInst::ICMP_EQ:
5444 if (LoOverflow && HiOverflow)
5445 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5446 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005447 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005448 ICmpInst::ICMP_UGE, X, LoBound);
5449 else if (LoOverflow)
5450 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5451 ICmpInst::ICMP_ULT, X, HiBound);
5452 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005453 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005454 case ICmpInst::ICMP_NE:
5455 if (LoOverflow && HiOverflow)
5456 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5457 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005458 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005459 ICmpInst::ICMP_ULT, X, LoBound);
5460 else if (LoOverflow)
5461 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5462 ICmpInst::ICMP_UGE, X, HiBound);
5463 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005464 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005465 case ICmpInst::ICMP_ULT:
5466 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005467 if (LoOverflow == +1) // Low bound is greater than input range.
5468 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5469 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005470 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005471 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005472 case ICmpInst::ICMP_UGT:
5473 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005474 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005475 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005476 else if (HiOverflow == -1) // High bound less than input range.
5477 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5478 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005479 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5480 else
5481 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5482 }
5483}
5484
5485
Chris Lattner01deb9d2007-04-03 17:43:25 +00005486/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5487///
5488Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5489 Instruction *LHSI,
5490 ConstantInt *RHS) {
5491 const APInt &RHSV = RHS->getValue();
5492
5493 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005494 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005495 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5496 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5497 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005498 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5499 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005500 Value *CompareVal = LHSI->getOperand(0);
5501
5502 // If the sign bit of the XorCST is not set, there is no change to
5503 // the operation, just stop using the Xor.
5504 if (!XorCST->getValue().isNegative()) {
5505 ICI.setOperand(0, CompareVal);
5506 AddToWorkList(LHSI);
5507 return &ICI;
5508 }
5509
5510 // Was the old condition true if the operand is positive?
5511 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5512
5513 // If so, the new one isn't.
5514 isTrueIfPositive ^= true;
5515
5516 if (isTrueIfPositive)
5517 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5518 else
5519 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5520 }
5521 }
5522 break;
5523 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5524 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5525 LHSI->getOperand(0)->hasOneUse()) {
5526 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5527
5528 // If the LHS is an AND of a truncating cast, we can widen the
5529 // and/compare to be the input width without changing the value
5530 // produced, eliminating a cast.
5531 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5532 // We can do this transformation if either the AND constant does not
5533 // have its sign bit set or if it is an equality comparison.
5534 // Extending a relational comparison when we're checking the sign
5535 // bit would not work.
5536 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005537 (ICI.isEquality() ||
5538 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005539 uint32_t BitWidth =
5540 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5541 APInt NewCST = AndCST->getValue();
5542 NewCST.zext(BitWidth);
5543 APInt NewCI = RHSV;
5544 NewCI.zext(BitWidth);
5545 Instruction *NewAnd =
5546 BinaryOperator::createAnd(Cast->getOperand(0),
5547 ConstantInt::get(NewCST),LHSI->getName());
5548 InsertNewInstBefore(NewAnd, ICI);
5549 return new ICmpInst(ICI.getPredicate(), NewAnd,
5550 ConstantInt::get(NewCI));
5551 }
5552 }
5553
5554 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5555 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5556 // happens a LOT in code produced by the C front-end, for bitfield
5557 // access.
5558 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5559 if (Shift && !Shift->isShift())
5560 Shift = 0;
5561
5562 ConstantInt *ShAmt;
5563 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5564 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5565 const Type *AndTy = AndCST->getType(); // Type of the and.
5566
5567 // We can fold this as long as we can't shift unknown bits
5568 // into the mask. This can only happen with signed shift
5569 // rights, as they sign-extend.
5570 if (ShAmt) {
5571 bool CanFold = Shift->isLogicalShift();
5572 if (!CanFold) {
5573 // To test for the bad case of the signed shr, see if any
5574 // of the bits shifted in could be tested after the mask.
5575 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5576 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5577
5578 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5579 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5580 AndCST->getValue()) == 0)
5581 CanFold = true;
5582 }
5583
5584 if (CanFold) {
5585 Constant *NewCst;
5586 if (Shift->getOpcode() == Instruction::Shl)
5587 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5588 else
5589 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5590
5591 // Check to see if we are shifting out any of the bits being
5592 // compared.
5593 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5594 // If we shifted bits out, the fold is not going to work out.
5595 // As a special case, check to see if this means that the
5596 // result is always true or false now.
5597 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5598 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5599 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5600 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5601 } else {
5602 ICI.setOperand(1, NewCst);
5603 Constant *NewAndCST;
5604 if (Shift->getOpcode() == Instruction::Shl)
5605 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5606 else
5607 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5608 LHSI->setOperand(1, NewAndCST);
5609 LHSI->setOperand(0, Shift->getOperand(0));
5610 AddToWorkList(Shift); // Shift is dead.
5611 AddUsesToWorkList(ICI);
5612 return &ICI;
5613 }
5614 }
5615 }
5616
5617 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5618 // preferable because it allows the C<<Y expression to be hoisted out
5619 // of a loop if Y is invariant and X is not.
5620 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5621 ICI.isEquality() && !Shift->isArithmeticShift() &&
5622 isa<Instruction>(Shift->getOperand(0))) {
5623 // Compute C << Y.
5624 Value *NS;
5625 if (Shift->getOpcode() == Instruction::LShr) {
5626 NS = BinaryOperator::createShl(AndCST,
5627 Shift->getOperand(1), "tmp");
5628 } else {
5629 // Insert a logical shift.
5630 NS = BinaryOperator::createLShr(AndCST,
5631 Shift->getOperand(1), "tmp");
5632 }
5633 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5634
5635 // Compute X & (C << Y).
5636 Instruction *NewAnd =
5637 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5638 InsertNewInstBefore(NewAnd, ICI);
5639
5640 ICI.setOperand(0, NewAnd);
5641 return &ICI;
5642 }
5643 }
5644 break;
5645
Chris Lattnera0141b92007-07-15 20:42:37 +00005646 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5647 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5648 if (!ShAmt) break;
5649
5650 uint32_t TypeBits = RHSV.getBitWidth();
5651
5652 // Check that the shift amount is in range. If not, don't perform
5653 // undefined shifts. When the shift is visited it will be
5654 // simplified.
5655 if (ShAmt->uge(TypeBits))
5656 break;
5657
5658 if (ICI.isEquality()) {
5659 // If we are comparing against bits always shifted out, the
5660 // comparison cannot succeed.
5661 Constant *Comp =
5662 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5663 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5664 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5665 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5666 return ReplaceInstUsesWith(ICI, Cst);
5667 }
5668
5669 if (LHSI->hasOneUse()) {
5670 // Otherwise strength reduce the shift into an and.
5671 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5672 Constant *Mask =
5673 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005674
Chris Lattnera0141b92007-07-15 20:42:37 +00005675 Instruction *AndI =
5676 BinaryOperator::createAnd(LHSI->getOperand(0),
5677 Mask, LHSI->getName()+".mask");
5678 Value *And = InsertNewInstBefore(AndI, ICI);
5679 return new ICmpInst(ICI.getPredicate(), And,
5680 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005681 }
5682 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005683
5684 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5685 bool TrueIfSigned = false;
5686 if (LHSI->hasOneUse() &&
5687 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5688 // (X << 31) <s 0 --> (X&1) != 0
5689 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5690 (TypeBits-ShAmt->getZExtValue()-1));
5691 Instruction *AndI =
5692 BinaryOperator::createAnd(LHSI->getOperand(0),
5693 Mask, LHSI->getName()+".mask");
5694 Value *And = InsertNewInstBefore(AndI, ICI);
5695
5696 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5697 And, Constant::getNullValue(And->getType()));
5698 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005699 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005700 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005701
5702 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005703 case Instruction::AShr: {
5704 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5705 if (!ShAmt) break;
5706
5707 if (ICI.isEquality()) {
5708 // Check that the shift amount is in range. If not, don't perform
5709 // undefined shifts. When the shift is visited it will be
5710 // simplified.
5711 uint32_t TypeBits = RHSV.getBitWidth();
5712 if (ShAmt->uge(TypeBits))
5713 break;
5714 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5715
5716 // If we are comparing against bits always shifted out, the
5717 // comparison cannot succeed.
5718 APInt Comp = RHSV << ShAmtVal;
5719 if (LHSI->getOpcode() == Instruction::LShr)
5720 Comp = Comp.lshr(ShAmtVal);
5721 else
5722 Comp = Comp.ashr(ShAmtVal);
5723
5724 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5725 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5726 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5727 return ReplaceInstUsesWith(ICI, Cst);
5728 }
5729
5730 if (LHSI->hasOneUse() || RHSV == 0) {
5731 // Otherwise strength reduce the shift into an and.
5732 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5733 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005734
Chris Lattnera0141b92007-07-15 20:42:37 +00005735 Instruction *AndI =
5736 BinaryOperator::createAnd(LHSI->getOperand(0),
5737 Mask, LHSI->getName()+".mask");
5738 Value *And = InsertNewInstBefore(AndI, ICI);
5739 return new ICmpInst(ICI.getPredicate(), And,
5740 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005741 }
5742 }
5743 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005744 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005745
5746 case Instruction::SDiv:
5747 case Instruction::UDiv:
5748 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5749 // Fold this div into the comparison, producing a range check.
5750 // Determine, based on the divide type, what the range is being
5751 // checked. If there is an overflow on the low or high side, remember
5752 // it, otherwise compute the range [low, hi) bounding the new value.
5753 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005754 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5755 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5756 DivRHS))
5757 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005758 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005759
5760 case Instruction::Add:
5761 // Fold: icmp pred (add, X, C1), C2
5762
5763 if (!ICI.isEquality()) {
5764 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5765 if (!LHSC) break;
5766 const APInt &LHSV = LHSC->getValue();
5767
5768 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5769 .subtract(LHSV);
5770
5771 if (ICI.isSignedPredicate()) {
5772 if (CR.getLower().isSignBit()) {
5773 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5774 ConstantInt::get(CR.getUpper()));
5775 } else if (CR.getUpper().isSignBit()) {
5776 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5777 ConstantInt::get(CR.getLower()));
5778 }
5779 } else {
5780 if (CR.getLower().isMinValue()) {
5781 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5782 ConstantInt::get(CR.getUpper()));
5783 } else if (CR.getUpper().isMinValue()) {
5784 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5785 ConstantInt::get(CR.getLower()));
5786 }
5787 }
5788 }
5789 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005790 }
5791
5792 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5793 if (ICI.isEquality()) {
5794 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5795
5796 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5797 // the second operand is a constant, simplify a bit.
5798 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5799 switch (BO->getOpcode()) {
5800 case Instruction::SRem:
5801 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5802 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5803 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5804 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5805 Instruction *NewRem =
5806 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5807 BO->getName());
5808 InsertNewInstBefore(NewRem, ICI);
5809 return new ICmpInst(ICI.getPredicate(), NewRem,
5810 Constant::getNullValue(BO->getType()));
5811 }
5812 }
5813 break;
5814 case Instruction::Add:
5815 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5816 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5817 if (BO->hasOneUse())
5818 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5819 Subtract(RHS, BOp1C));
5820 } else if (RHSV == 0) {
5821 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5822 // efficiently invertible, or if the add has just this one use.
5823 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5824
5825 if (Value *NegVal = dyn_castNegVal(BOp1))
5826 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5827 else if (Value *NegVal = dyn_castNegVal(BOp0))
5828 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5829 else if (BO->hasOneUse()) {
5830 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5831 InsertNewInstBefore(Neg, ICI);
5832 Neg->takeName(BO);
5833 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5834 }
5835 }
5836 break;
5837 case Instruction::Xor:
5838 // For the xor case, we can xor two constants together, eliminating
5839 // the explicit xor.
5840 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5841 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5842 ConstantExpr::getXor(RHS, BOC));
5843
5844 // FALLTHROUGH
5845 case Instruction::Sub:
5846 // Replace (([sub|xor] A, B) != 0) with (A != B)
5847 if (RHSV == 0)
5848 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5849 BO->getOperand(1));
5850 break;
5851
5852 case Instruction::Or:
5853 // If bits are being or'd in that are not present in the constant we
5854 // are comparing against, then the comparison could never succeed!
5855 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5856 Constant *NotCI = ConstantExpr::getNot(RHS);
5857 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5858 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5859 isICMP_NE));
5860 }
5861 break;
5862
5863 case Instruction::And:
5864 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5865 // If bits are being compared against that are and'd out, then the
5866 // comparison can never succeed!
5867 if ((RHSV & ~BOC->getValue()) != 0)
5868 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5869 isICMP_NE));
5870
5871 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5872 if (RHS == BOC && RHSV.isPowerOf2())
5873 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5874 ICmpInst::ICMP_NE, LHSI,
5875 Constant::getNullValue(RHS->getType()));
5876
5877 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5878 if (isSignBit(BOC)) {
5879 Value *X = BO->getOperand(0);
5880 Constant *Zero = Constant::getNullValue(X->getType());
5881 ICmpInst::Predicate pred = isICMP_NE ?
5882 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5883 return new ICmpInst(pred, X, Zero);
5884 }
5885
5886 // ((X & ~7) == 0) --> X < 8
5887 if (RHSV == 0 && isHighOnes(BOC)) {
5888 Value *X = BO->getOperand(0);
5889 Constant *NegX = ConstantExpr::getNeg(BOC);
5890 ICmpInst::Predicate pred = isICMP_NE ?
5891 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5892 return new ICmpInst(pred, X, NegX);
5893 }
5894 }
5895 default: break;
5896 }
5897 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5898 // Handle icmp {eq|ne} <intrinsic>, intcst.
5899 if (II->getIntrinsicID() == Intrinsic::bswap) {
5900 AddToWorkList(II);
5901 ICI.setOperand(0, II->getOperand(1));
5902 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5903 return &ICI;
5904 }
5905 }
5906 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005907 // If the LHS is a cast from an integral value of the same size,
5908 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005909 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5910 Value *CastOp = Cast->getOperand(0);
5911 const Type *SrcTy = CastOp->getType();
5912 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5913 if (SrcTy->isInteger() &&
5914 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5915 // If this is an unsigned comparison, try to make the comparison use
5916 // smaller constant values.
5917 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5918 // X u< 128 => X s> -1
5919 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5920 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5921 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5922 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5923 // X u> 127 => X s< 0
5924 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5925 Constant::getNullValue(SrcTy));
5926 }
5927 }
5928 }
5929 }
5930 return 0;
5931}
5932
5933/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5934/// We only handle extending casts so far.
5935///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005936Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5937 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005938 Value *LHSCIOp = LHSCI->getOperand(0);
5939 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005941 Value *RHSCIOp;
5942
Chris Lattner8c756c12007-05-05 22:41:33 +00005943 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5944 // integer type is the same size as the pointer type.
5945 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5946 getTargetData().getPointerSizeInBits() ==
5947 cast<IntegerType>(DestTy)->getBitWidth()) {
5948 Value *RHSOp = 0;
5949 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005950 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005951 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5952 RHSOp = RHSC->getOperand(0);
5953 // If the pointer types don't match, insert a bitcast.
5954 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005955 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005956 }
5957
5958 if (RHSOp)
5959 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5960 }
5961
5962 // The code below only handles extension cast instructions, so far.
5963 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 if (LHSCI->getOpcode() != Instruction::ZExt &&
5965 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005966 return 0;
5967
Reid Spencere4d87aa2006-12-23 06:05:41 +00005968 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5969 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005970
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005972 // Not an extension from the same type?
5973 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 if (RHSCIOp->getType() != LHSCIOp->getType())
5975 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005976
Nick Lewycky4189a532008-01-28 03:48:02 +00005977 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00005978 // and the other is a zext), then we can't handle this.
5979 if (CI->getOpcode() != LHSCI->getOpcode())
5980 return 0;
5981
Nick Lewycky4189a532008-01-28 03:48:02 +00005982 // Deal with equality cases early.
5983 if (ICI.isEquality())
5984 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5985
5986 // A signed comparison of sign extended values simplifies into a
5987 // signed comparison.
5988 if (isSignedCmp && isSignedExt)
5989 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5990
5991 // The other three cases all fold into an unsigned comparison.
5992 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005993 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005994
Reid Spencere4d87aa2006-12-23 06:05:41 +00005995 // If we aren't dealing with a constant on the RHS, exit early
5996 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5997 if (!CI)
5998 return 0;
5999
6000 // Compute the constant that would happen if we truncated to SrcTy then
6001 // reextended to DestTy.
6002 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6003 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6004
6005 // If the re-extended constant didn't change...
6006 if (Res2 == CI) {
6007 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6008 // For example, we might have:
6009 // %A = sext short %X to uint
6010 // %B = icmp ugt uint %A, 1330
6011 // It is incorrect to transform this into
6012 // %B = icmp ugt short %X, 1330
6013 // because %A may have negative value.
6014 //
6015 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6016 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006017 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6019 else
6020 return 0;
6021 }
6022
6023 // The re-extended constant changed so the constant cannot be represented
6024 // in the shorter type. Consequently, we cannot emit a simple comparison.
6025
6026 // First, handle some easy cases. We know the result cannot be equal at this
6027 // point so handle the ICI.isEquality() cases
6028 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006029 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006030 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006031 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006032
6033 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6034 // should have been folded away previously and not enter in here.
6035 Value *Result;
6036 if (isSignedCmp) {
6037 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006038 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006039 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006040 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006041 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006042 } else {
6043 // We're performing an unsigned comparison.
6044 if (isSignedExt) {
6045 // We're performing an unsigned comp with a sign extended value.
6046 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006047 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006048 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6049 NegOne, ICI.getName()), ICI);
6050 } else {
6051 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006052 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006053 }
6054 }
6055
6056 // Finally, return the value computed.
6057 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6058 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6059 return ReplaceInstUsesWith(ICI, Result);
6060 } else {
6061 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6062 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6063 "ICmp should be folded!");
6064 if (Constant *CI = dyn_cast<Constant>(Result))
6065 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6066 else
6067 return BinaryOperator::createNot(Result);
6068 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006069}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006070
Reid Spencer832254e2007-02-02 02:16:23 +00006071Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6072 return commonShiftTransforms(I);
6073}
6074
6075Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6076 return commonShiftTransforms(I);
6077}
6078
6079Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006080 if (Instruction *R = commonShiftTransforms(I))
6081 return R;
6082
6083 Value *Op0 = I.getOperand(0);
6084
6085 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6086 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6087 if (CSI->isAllOnesValue())
6088 return ReplaceInstUsesWith(I, CSI);
6089
6090 // See if we can turn a signed shr into an unsigned shr.
6091 if (MaskedValueIsZero(Op0,
6092 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6093 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6094
6095 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006096}
6097
6098Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6099 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006101
6102 // shl X, 0 == X and shr X, 0 == X
6103 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006104 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006105 Op0 == Constant::getNullValue(Op0->getType()))
6106 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006107
Reid Spencere4d87aa2006-12-23 06:05:41 +00006108 if (isa<UndefValue>(Op0)) {
6109 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006110 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006111 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006112 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6113 }
6114 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006115 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6116 return ReplaceInstUsesWith(I, Op0);
6117 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006118 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006119 }
6120
Chris Lattner2eefe512004-04-09 19:05:30 +00006121 // Try to fold constant and into select arguments.
6122 if (isa<Constant>(Op0))
6123 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006124 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006125 return R;
6126
Reid Spencerb83eb642006-10-20 07:07:24 +00006127 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006128 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6129 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006130 return 0;
6131}
6132
Reid Spencerb83eb642006-10-20 07:07:24 +00006133Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006134 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006135 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006136
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006137 // See if we can simplify any instructions used by the instruction whose sole
6138 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006139 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6140 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6141 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006142 KnownZero, KnownOne))
6143 return &I;
6144
Chris Lattner4d5542c2006-01-06 07:12:35 +00006145 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6146 // of a signed value.
6147 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006148 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006149 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006150 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6151 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006152 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006153 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006154 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006155 }
6156
6157 // ((X*C1) << C2) == (X * (C1 << C2))
6158 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6159 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6160 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6161 return BinaryOperator::createMul(BO->getOperand(0),
6162 ConstantExpr::getShl(BOOp, Op1));
6163
6164 // Try to fold constant and into select arguments.
6165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6166 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6167 return R;
6168 if (isa<PHINode>(Op0))
6169 if (Instruction *NV = FoldOpIntoPhi(I))
6170 return NV;
6171
Chris Lattner8999dd32007-12-22 09:07:47 +00006172 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6173 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6174 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6175 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6176 // place. Don't try to do this transformation in this case. Also, we
6177 // require that the input operand is a shift-by-constant so that we have
6178 // confidence that the shifts will get folded together. We could do this
6179 // xform in more cases, but it is unlikely to be profitable.
6180 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6181 isa<ConstantInt>(TrOp->getOperand(1))) {
6182 // Okay, we'll do this xform. Make the shift of shift.
6183 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6184 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6185 I.getName());
6186 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6187
6188 // For logical shifts, the truncation has the effect of making the high
6189 // part of the register be zeros. Emulate this by inserting an AND to
6190 // clear the top bits as needed. This 'and' will usually be zapped by
6191 // other xforms later if dead.
6192 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6193 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6194 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6195
6196 // The mask we constructed says what the trunc would do if occurring
6197 // between the shifts. We want to know the effect *after* the second
6198 // shift. We know that it is a logical shift by a constant, so adjust the
6199 // mask as appropriate.
6200 if (I.getOpcode() == Instruction::Shl)
6201 MaskV <<= Op1->getZExtValue();
6202 else {
6203 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6204 MaskV = MaskV.lshr(Op1->getZExtValue());
6205 }
6206
6207 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6208 TI->getName());
6209 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6210
6211 // Return the value truncated to the interesting size.
6212 return new TruncInst(And, I.getType());
6213 }
6214 }
6215
Chris Lattner4d5542c2006-01-06 07:12:35 +00006216 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006217 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6218 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6219 Value *V1, *V2;
6220 ConstantInt *CC;
6221 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006222 default: break;
6223 case Instruction::Add:
6224 case Instruction::And:
6225 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006226 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006227 // These operators commute.
6228 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006229 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6230 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006231 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006232 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006233 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006234 Op0BO->getName());
6235 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006236 Instruction *X =
6237 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6238 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006239 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006240 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006241 return BinaryOperator::createAnd(X, ConstantInt::get(
6242 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006243 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006244
Chris Lattner150f12a2005-09-18 06:30:59 +00006245 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006246 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006247 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006248 match(Op0BOOp1,
6249 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006250 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6251 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006252 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006253 Op0BO->getOperand(0), Op1,
6254 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006255 InsertNewInstBefore(YS, I); // (Y << C)
6256 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006257 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006258 V1->getName()+".mask");
6259 InsertNewInstBefore(XM, I); // X & (CC << C)
6260
6261 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6262 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006263 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006264
Reid Spencera07cb7d2007-02-02 14:41:37 +00006265 // FALL THROUGH.
6266 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006267 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006268 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6269 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006270 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006271 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006272 Op0BO->getOperand(1), Op1,
6273 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006274 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006275 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006276 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006277 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006278 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006279 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006280 return BinaryOperator::createAnd(X, ConstantInt::get(
6281 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006282 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006283
Chris Lattner13d4ab42006-05-31 21:14:00 +00006284 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006285 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6286 match(Op0BO->getOperand(0),
6287 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006288 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006289 cast<BinaryOperator>(Op0BO->getOperand(0))
6290 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006291 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006292 Op0BO->getOperand(1), Op1,
6293 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006294 InsertNewInstBefore(YS, I); // (Y << C)
6295 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006296 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006297 V1->getName()+".mask");
6298 InsertNewInstBefore(XM, I); // X & (CC << C)
6299
Chris Lattner13d4ab42006-05-31 21:14:00 +00006300 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006301 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006302
Chris Lattner11021cb2005-09-18 05:12:10 +00006303 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006304 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006305 }
6306
6307
6308 // If the operand is an bitwise operator with a constant RHS, and the
6309 // shift is the only use, we can pull it out of the shift.
6310 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6311 bool isValid = true; // Valid only for And, Or, Xor
6312 bool highBitSet = false; // Transform if high bit of constant set?
6313
6314 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006315 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006316 case Instruction::Add:
6317 isValid = isLeftShift;
6318 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006319 case Instruction::Or:
6320 case Instruction::Xor:
6321 highBitSet = false;
6322 break;
6323 case Instruction::And:
6324 highBitSet = true;
6325 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006326 }
6327
6328 // If this is a signed shift right, and the high bit is modified
6329 // by the logical operation, do not perform the transformation.
6330 // The highBitSet boolean indicates the value of the high bit of
6331 // the constant which would cause it to be modified for this
6332 // operation.
6333 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006334 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006335 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006336
6337 if (isValid) {
6338 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6339
6340 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006341 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006342 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006343 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006344
6345 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6346 NewRHS);
6347 }
6348 }
6349 }
6350 }
6351
Chris Lattnerad0124c2006-01-06 07:52:12 +00006352 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006353 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6354 if (ShiftOp && !ShiftOp->isShift())
6355 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006356
Reid Spencerb83eb642006-10-20 07:07:24 +00006357 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006358 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006359 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6360 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006361 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6362 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6363 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006364
Zhou Sheng4351c642007-04-02 08:20:41 +00006365 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006366 if (AmtSum > TypeBits)
6367 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006368
6369 const IntegerType *Ty = cast<IntegerType>(I.getType());
6370
6371 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006372 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006373 return BinaryOperator::create(I.getOpcode(), X,
6374 ConstantInt::get(Ty, AmtSum));
6375 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6376 I.getOpcode() == Instruction::AShr) {
6377 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6378 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6379 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6380 I.getOpcode() == Instruction::LShr) {
6381 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6382 Instruction *Shift =
6383 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6384 InsertNewInstBefore(Shift, I);
6385
Zhou Shenge9e03f62007-03-28 15:02:20 +00006386 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006387 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006388 }
6389
Chris Lattnerb87056f2007-02-05 00:57:54 +00006390 // Okay, if we get here, one shift must be left, and the other shift must be
6391 // right. See if the amounts are equal.
6392 if (ShiftAmt1 == ShiftAmt2) {
6393 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6394 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006395 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006396 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006397 }
6398 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6399 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006400 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006401 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006402 }
6403 // We can simplify ((X << C) >>s C) into a trunc + sext.
6404 // NOTE: we could do this for any C, but that would make 'unusual' integer
6405 // types. For now, just stick to ones well-supported by the code
6406 // generators.
6407 const Type *SExtType = 0;
6408 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006409 case 1 :
6410 case 8 :
6411 case 16 :
6412 case 32 :
6413 case 64 :
6414 case 128:
6415 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6416 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006417 default: break;
6418 }
6419 if (SExtType) {
6420 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6421 InsertNewInstBefore(NewTrunc, I);
6422 return new SExtInst(NewTrunc, Ty);
6423 }
6424 // Otherwise, we can't handle it yet.
6425 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006426 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006427
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006428 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006429 if (I.getOpcode() == Instruction::Shl) {
6430 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6431 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006432 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006433 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006434 InsertNewInstBefore(Shift, I);
6435
Reid Spencer55702aa2007-03-25 21:11:44 +00006436 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6437 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006438 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006439
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006440 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006441 if (I.getOpcode() == Instruction::LShr) {
6442 assert(ShiftOp->getOpcode() == Instruction::Shl);
6443 Instruction *Shift =
6444 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6445 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006446
Reid Spencerd5e30f02007-03-26 17:18:58 +00006447 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006448 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006449 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006450
6451 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6452 } else {
6453 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006454 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006455
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006456 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006457 if (I.getOpcode() == Instruction::Shl) {
6458 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6459 ShiftOp->getOpcode() == Instruction::AShr);
6460 Instruction *Shift =
6461 BinaryOperator::create(ShiftOp->getOpcode(), X,
6462 ConstantInt::get(Ty, ShiftDiff));
6463 InsertNewInstBefore(Shift, I);
6464
Reid Spencer55702aa2007-03-25 21:11:44 +00006465 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006466 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006467 }
6468
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006469 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006470 if (I.getOpcode() == Instruction::LShr) {
6471 assert(ShiftOp->getOpcode() == Instruction::Shl);
6472 Instruction *Shift =
6473 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6474 InsertNewInstBefore(Shift, I);
6475
Reid Spencer68d27cf2007-03-26 23:45:51 +00006476 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006477 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006478 }
6479
6480 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006481 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006482 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006483 return 0;
6484}
6485
Chris Lattnera1be5662002-05-02 17:06:02 +00006486
Chris Lattnercfd65102005-10-29 04:36:15 +00006487/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6488/// expression. If so, decompose it, returning some value X, such that Val is
6489/// X*Scale+Offset.
6490///
6491static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006492 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006493 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006495 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006496 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006497 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006498 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6499 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6500 if (I->getOpcode() == Instruction::Shl) {
6501 // This is a value scaled by '1 << the shift amt'.
6502 Scale = 1U << RHS->getZExtValue();
6503 Offset = 0;
6504 return I->getOperand(0);
6505 } else if (I->getOpcode() == Instruction::Mul) {
6506 // This value is scaled by 'RHS'.
6507 Scale = RHS->getZExtValue();
6508 Offset = 0;
6509 return I->getOperand(0);
6510 } else if (I->getOpcode() == Instruction::Add) {
6511 // We have X+C. Check to see if we really have (X*C2)+C1,
6512 // where C1 is divisible by C2.
6513 unsigned SubScale;
6514 Value *SubVal =
6515 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6516 Offset += RHS->getZExtValue();
6517 Scale = SubScale;
6518 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006519 }
6520 }
6521 }
6522
6523 // Otherwise, we can't look past this.
6524 Scale = 1;
6525 Offset = 0;
6526 return Val;
6527}
6528
6529
Chris Lattnerb3f83972005-10-24 06:03:58 +00006530/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6531/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006532Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006533 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006534 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006535
Chris Lattnerb53c2382005-10-24 06:22:12 +00006536 // Remove any uses of AI that are dead.
6537 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006538
Chris Lattnerb53c2382005-10-24 06:22:12 +00006539 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6540 Instruction *User = cast<Instruction>(*UI++);
6541 if (isInstructionTriviallyDead(User)) {
6542 while (UI != E && *UI == User)
6543 ++UI; // If this instruction uses AI more than once, don't break UI.
6544
Chris Lattnerb53c2382005-10-24 06:22:12 +00006545 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006546 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006547 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006548 }
6549 }
6550
Chris Lattnerb3f83972005-10-24 06:03:58 +00006551 // Get the type really allocated and the type casted to.
6552 const Type *AllocElTy = AI.getAllocatedType();
6553 const Type *CastElTy = PTy->getElementType();
6554 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006555
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006556 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6557 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006558 if (CastElTyAlign < AllocElTyAlign) return 0;
6559
Chris Lattner39387a52005-10-24 06:35:18 +00006560 // If the allocation has multiple uses, only promote it if we are strictly
6561 // increasing the alignment of the resultant allocation. If we keep it the
6562 // same, we open the door to infinite loops of various kinds.
6563 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6564
Duncan Sands514ab342007-11-01 20:53:16 +00006565 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6566 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006567 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006568
Chris Lattner455fcc82005-10-29 03:19:53 +00006569 // See if we can satisfy the modulus by pulling a scale out of the array
6570 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006571 unsigned ArraySizeScale;
6572 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006573 Value *NumElements = // See if the array size is a decomposable linear expr.
6574 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6575
Chris Lattner455fcc82005-10-29 03:19:53 +00006576 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6577 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006578 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6579 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006580
Chris Lattner455fcc82005-10-29 03:19:53 +00006581 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6582 Value *Amt = 0;
6583 if (Scale == 1) {
6584 Amt = NumElements;
6585 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006586 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006587 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6588 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006589 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006590 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006591 else if (Scale != 1) {
6592 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6593 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006594 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006595 }
6596
Jeff Cohen86796be2007-04-04 16:58:57 +00006597 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6598 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006599 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6600 Amt = InsertNewInstBefore(Tmp, AI);
6601 }
6602
Chris Lattnerb3f83972005-10-24 06:03:58 +00006603 AllocationInst *New;
6604 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006605 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006606 else
Chris Lattner6934a042007-02-11 01:23:03 +00006607 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006608 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006609 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006610
6611 // If the allocation has multiple uses, insert a cast and change all things
6612 // that used it to use the new cast. This will also hack on CI, but it will
6613 // die soon.
6614 if (!AI.hasOneUse()) {
6615 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006616 // New is the allocation instruction, pointer typed. AI is the original
6617 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6618 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006619 InsertNewInstBefore(NewCast, AI);
6620 AI.replaceAllUsesWith(NewCast);
6621 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006622 return ReplaceInstUsesWith(CI, New);
6623}
6624
Chris Lattner70074e02006-05-13 02:06:03 +00006625/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006626/// and return it as type Ty without inserting any new casts and without
6627/// changing the computed value. This is used by code that tries to decide
6628/// whether promoting or shrinking integer operations to wider or smaller types
6629/// will allow us to eliminate a truncate or extend.
6630///
6631/// This is a truncation operation if Ty is smaller than V->getType(), or an
6632/// extension operation if Ty is larger.
6633static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006634 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006635 // We can always evaluate constants in another type.
6636 if (isa<ConstantInt>(V))
6637 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006638
6639 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006640 if (!I) return false;
6641
6642 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006643
Chris Lattner951626b2007-08-02 06:11:14 +00006644 // If this is an extension or truncate, we can often eliminate it.
6645 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6646 // If this is a cast from the destination type, we can trivially eliminate
6647 // it, and this will remove a cast overall.
6648 if (I->getOperand(0)->getType() == Ty) {
6649 // If the first operand is itself a cast, and is eliminable, do not count
6650 // this as an eliminable cast. We would prefer to eliminate those two
6651 // casts first.
6652 if (!isa<CastInst>(I->getOperand(0)))
6653 ++NumCastsRemoved;
6654 return true;
6655 }
6656 }
6657
6658 // We can't extend or shrink something that has multiple uses: doing so would
6659 // require duplicating the instruction in general, which isn't profitable.
6660 if (!I->hasOneUse()) return false;
6661
Chris Lattner70074e02006-05-13 02:06:03 +00006662 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006663 case Instruction::Add:
6664 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006665 case Instruction::And:
6666 case Instruction::Or:
6667 case Instruction::Xor:
6668 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006669 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6670 NumCastsRemoved) &&
6671 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6672 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006673
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006674 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006675 // A multiply can be truncated by truncating its operands.
6676 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6677 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6678 NumCastsRemoved) &&
6679 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6680 NumCastsRemoved);
6681
Chris Lattner46b96052006-11-29 07:18:39 +00006682 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006683 // If we are truncating the result of this SHL, and if it's a shift of a
6684 // constant amount, we can always perform a SHL in a smaller type.
6685 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006686 uint32_t BitWidth = Ty->getBitWidth();
6687 if (BitWidth < OrigTy->getBitWidth() &&
6688 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006689 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6690 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006691 }
6692 break;
6693 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006694 // If this is a truncate of a logical shr, we can truncate it to a smaller
6695 // lshr iff we know that the bits we would otherwise be shifting in are
6696 // already zeros.
6697 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006698 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6699 uint32_t BitWidth = Ty->getBitWidth();
6700 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006701 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006702 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6703 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006704 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6705 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006706 }
6707 }
Chris Lattner46b96052006-11-29 07:18:39 +00006708 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006709 case Instruction::ZExt:
6710 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006711 case Instruction::Trunc:
6712 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006713 // can safely replace it. Note that replacing it does not reduce the number
6714 // of casts in the input.
6715 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006716 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006717
Reid Spencer3da59db2006-11-27 01:05:10 +00006718 break;
6719 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006720 // TODO: Can handle more cases here.
6721 break;
6722 }
6723
6724 return false;
6725}
6726
6727/// EvaluateInDifferentType - Given an expression that
6728/// CanEvaluateInDifferentType returns true for, actually insert the code to
6729/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006730Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006731 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006732 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006733 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006734
6735 // Otherwise, it must be an instruction.
6736 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006737 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006738 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006739 case Instruction::Add:
6740 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006741 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006742 case Instruction::And:
6743 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006744 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006745 case Instruction::AShr:
6746 case Instruction::LShr:
6747 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006748 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006749 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6750 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6751 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006752 break;
6753 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006754 case Instruction::Trunc:
6755 case Instruction::ZExt:
6756 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006757 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006758 // just return the source. There's no need to insert it because it is not
6759 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006760 if (I->getOperand(0)->getType() == Ty)
6761 return I->getOperand(0);
6762
Chris Lattner951626b2007-08-02 06:11:14 +00006763 // Otherwise, must be the same type of case, so just reinsert a new one.
6764 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6765 Ty, I->getName());
6766 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006767 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006768 // TODO: Can handle more cases here.
6769 assert(0 && "Unreachable!");
6770 break;
6771 }
6772
6773 return InsertNewInstBefore(Res, *I);
6774}
6775
Reid Spencer3da59db2006-11-27 01:05:10 +00006776/// @brief Implement the transforms common to all CastInst visitors.
6777Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006778 Value *Src = CI.getOperand(0);
6779
Dan Gohman23d9d272007-05-11 21:10:54 +00006780 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006781 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006782 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006783 if (Instruction::CastOps opc =
6784 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6785 // The first cast (CSrc) is eliminable so we need to fix up or replace
6786 // the second cast (CI). CSrc will then have a good chance of being dead.
6787 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006788 }
6789 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006790
Reid Spencer3da59db2006-11-27 01:05:10 +00006791 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006792 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6793 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6794 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006795
6796 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006797 if (isa<PHINode>(Src))
6798 if (Instruction *NV = FoldOpIntoPhi(CI))
6799 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006800
Reid Spencer3da59db2006-11-27 01:05:10 +00006801 return 0;
6802}
6803
Chris Lattnerd3e28342007-04-27 17:44:50 +00006804/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6805Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6806 Value *Src = CI.getOperand(0);
6807
Chris Lattnerd3e28342007-04-27 17:44:50 +00006808 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006809 // If casting the result of a getelementptr instruction with no offset, turn
6810 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006811 if (GEP->hasAllZeroIndices()) {
6812 // Changing the cast operand is usually not a good idea but it is safe
6813 // here because the pointer operand is being replaced with another
6814 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006815 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006816 CI.setOperand(0, GEP->getOperand(0));
6817 return &CI;
6818 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006819
6820 // If the GEP has a single use, and the base pointer is a bitcast, and the
6821 // GEP computes a constant offset, see if we can convert these three
6822 // instructions into fewer. This typically happens with unions and other
6823 // non-type-safe code.
6824 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6825 if (GEP->hasAllConstantIndices()) {
6826 // We are guaranteed to get a constant from EmitGEPOffset.
6827 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6828 int64_t Offset = OffsetV->getSExtValue();
6829
6830 // Get the base pointer input of the bitcast, and the type it points to.
6831 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6832 const Type *GEPIdxTy =
6833 cast<PointerType>(OrigBase->getType())->getElementType();
6834 if (GEPIdxTy->isSized()) {
6835 SmallVector<Value*, 8> NewIndices;
6836
Chris Lattnerc42e2262007-05-05 01:59:31 +00006837 // Start with the index over the outer type. Note that the type size
6838 // might be zero (even if the offset isn't zero) if the indexed type
6839 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006840 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006841 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006842 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006843 FirstIdx = Offset/TySize;
6844 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006845
Chris Lattnerc42e2262007-05-05 01:59:31 +00006846 // Handle silly modulus not returning values values [0..TySize).
6847 if (Offset < 0) {
6848 --FirstIdx;
6849 Offset += TySize;
6850 assert(Offset >= 0);
6851 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006852 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006853 }
6854
6855 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006856
6857 // Index into the types. If we fail, set OrigBase to null.
6858 while (Offset) {
6859 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6860 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006861 if (Offset < (int64_t)SL->getSizeInBytes()) {
6862 unsigned Elt = SL->getElementContainingOffset(Offset);
6863 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006864
Chris Lattner6b6aef82007-05-15 00:16:00 +00006865 Offset -= SL->getElementOffset(Elt);
6866 GEPIdxTy = STy->getElementType(Elt);
6867 } else {
6868 // Otherwise, we can't index into this, bail out.
6869 Offset = 0;
6870 OrigBase = 0;
6871 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006872 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6873 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006874 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006875 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6876 Offset %= EltSize;
6877 } else {
6878 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6879 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006880 GEPIdxTy = STy->getElementType();
6881 } else {
6882 // Otherwise, we can't index into this, bail out.
6883 Offset = 0;
6884 OrigBase = 0;
6885 }
6886 }
6887 if (OrigBase) {
6888 // If we were able to index down into an element, create the GEP
6889 // and bitcast the result. This eliminates one bitcast, potentially
6890 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006891 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6892 NewIndices.begin(),
6893 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006894 InsertNewInstBefore(NGEP, CI);
6895 NGEP->takeName(GEP);
6896
Chris Lattner9bc14642007-04-28 00:57:34 +00006897 if (isa<BitCastInst>(CI))
6898 return new BitCastInst(NGEP, CI.getType());
6899 assert(isa<PtrToIntInst>(CI));
6900 return new PtrToIntInst(NGEP, CI.getType());
6901 }
6902 }
6903 }
6904 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006905 }
6906
6907 return commonCastTransforms(CI);
6908}
6909
6910
6911
Chris Lattnerc739cd62007-03-03 05:27:34 +00006912/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6913/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006914/// cases.
6915/// @brief Implement the transforms common to CastInst with integer operands
6916Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6917 if (Instruction *Result = commonCastTransforms(CI))
6918 return Result;
6919
6920 Value *Src = CI.getOperand(0);
6921 const Type *SrcTy = Src->getType();
6922 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006923 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6924 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006925
Reid Spencer3da59db2006-11-27 01:05:10 +00006926 // See if we can simplify any instructions used by the LHS whose sole
6927 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006928 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6929 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006930 KnownZero, KnownOne))
6931 return &CI;
6932
6933 // If the source isn't an instruction or has more than one use then we
6934 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006935 Instruction *SrcI = dyn_cast<Instruction>(Src);
6936 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006937 return 0;
6938
Chris Lattnerc739cd62007-03-03 05:27:34 +00006939 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006940 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006941 if (!isa<BitCastInst>(CI) &&
6942 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006943 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006944 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006945 // eliminates the cast, so it is always a win. If this is a zero-extension,
6946 // we need to do an AND to maintain the clear top-part of the computation,
6947 // so we require that the input have eliminated at least one cast. If this
6948 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006949 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006950 bool DoXForm;
6951 switch (CI.getOpcode()) {
6952 default:
6953 // All the others use floating point so we shouldn't actually
6954 // get here because of the check above.
6955 assert(0 && "Unknown cast type");
6956 case Instruction::Trunc:
6957 DoXForm = true;
6958 break;
6959 case Instruction::ZExt:
6960 DoXForm = NumCastsRemoved >= 1;
6961 break;
6962 case Instruction::SExt:
6963 DoXForm = NumCastsRemoved >= 2;
6964 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006965 }
6966
6967 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006968 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6969 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006970 assert(Res->getType() == DestTy);
6971 switch (CI.getOpcode()) {
6972 default: assert(0 && "Unknown cast type!");
6973 case Instruction::Trunc:
6974 case Instruction::BitCast:
6975 // Just replace this cast with the result.
6976 return ReplaceInstUsesWith(CI, Res);
6977 case Instruction::ZExt: {
6978 // We need to emit an AND to clear the high bits.
6979 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006980 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6981 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006982 return BinaryOperator::createAnd(Res, C);
6983 }
6984 case Instruction::SExt:
6985 // We need to emit a cast to truncate, then a cast to sext.
6986 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006987 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6988 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006989 }
6990 }
6991 }
6992
6993 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6994 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6995
6996 switch (SrcI->getOpcode()) {
6997 case Instruction::Add:
6998 case Instruction::Mul:
6999 case Instruction::And:
7000 case Instruction::Or:
7001 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007002 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007003 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7004 // Don't insert two casts if they cannot be eliminated. We allow
7005 // two casts to be inserted if the sizes are the same. This could
7006 // only be converting signedness, which is a noop.
7007 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007008 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7009 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007010 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007011 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7012 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7013 return BinaryOperator::create(
7014 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007015 }
7016 }
7017
7018 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7019 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7020 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007021 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007022 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007023 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007024 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7025 }
7026 break;
7027 case Instruction::SDiv:
7028 case Instruction::UDiv:
7029 case Instruction::SRem:
7030 case Instruction::URem:
7031 // If we are just changing the sign, rewrite.
7032 if (DestBitSize == SrcBitSize) {
7033 // Don't insert two casts if they cannot be eliminated. We allow
7034 // two casts to be inserted if the sizes are the same. This could
7035 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007036 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7037 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007038 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7039 Op0, DestTy, SrcI);
7040 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7041 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007042 return BinaryOperator::create(
7043 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7044 }
7045 }
7046 break;
7047
7048 case Instruction::Shl:
7049 // Allow changing the sign of the source operand. Do not allow
7050 // changing the size of the shift, UNLESS the shift amount is a
7051 // constant. We must not change variable sized shifts to a smaller
7052 // size, because it is undefined to shift more bits out than exist
7053 // in the value.
7054 if (DestBitSize == SrcBitSize ||
7055 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007056 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7057 Instruction::BitCast : Instruction::Trunc);
7058 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007059 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007060 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007061 }
7062 break;
7063 case Instruction::AShr:
7064 // If this is a signed shr, and if all bits shifted in are about to be
7065 // truncated off, turn it into an unsigned shr to allow greater
7066 // simplifications.
7067 if (DestBitSize < SrcBitSize &&
7068 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007069 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007070 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7071 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007072 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007073 }
7074 }
7075 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007076 }
7077 return 0;
7078}
7079
Chris Lattner8a9f5712007-04-11 06:57:46 +00007080Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007081 if (Instruction *Result = commonIntCastTransforms(CI))
7082 return Result;
7083
7084 Value *Src = CI.getOperand(0);
7085 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007086 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7087 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007088
7089 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7090 switch (SrcI->getOpcode()) {
7091 default: break;
7092 case Instruction::LShr:
7093 // We can shrink lshr to something smaller if we know the bits shifted in
7094 // are already zeros.
7095 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007096 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007097
7098 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007099 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007100 Value* SrcIOp0 = SrcI->getOperand(0);
7101 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007102 if (ShAmt >= DestBitWidth) // All zeros.
7103 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7104
7105 // Okay, we can shrink this. Truncate the input, then return a new
7106 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007107 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7108 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7109 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007110 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007111 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007112 } else { // This is a variable shr.
7113
7114 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7115 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7116 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007117 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007118 Value *One = ConstantInt::get(SrcI->getType(), 1);
7119
Reid Spencer832254e2007-02-02 02:16:23 +00007120 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007121 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007122 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007123 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7124 SrcI->getOperand(0),
7125 "tmp"), CI);
7126 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007127 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007128 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007129 }
7130 break;
7131 }
7132 }
7133
7134 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007135}
7136
Chris Lattner8a9f5712007-04-11 06:57:46 +00007137Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007138 // If one of the common conversion will work ..
7139 if (Instruction *Result = commonIntCastTransforms(CI))
7140 return Result;
7141
7142 Value *Src = CI.getOperand(0);
7143
7144 // If this is a cast of a cast
7145 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007146 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7147 // types and if the sizes are just right we can convert this into a logical
7148 // 'and' which will be much cheaper than the pair of casts.
7149 if (isa<TruncInst>(CSrc)) {
7150 // Get the sizes of the types involved
7151 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007152 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7153 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7154 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007155 // If we're actually extending zero bits and the trunc is a no-op
7156 if (MidSize < DstSize && SrcSize == DstSize) {
7157 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007158 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007159 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007160 Instruction *And =
7161 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7162 // Unfortunately, if the type changed, we need to cast it back.
7163 if (And->getType() != CI.getType()) {
7164 And->setName(CSrc->getName()+".mask");
7165 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007166 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007167 }
7168 return And;
7169 }
7170 }
7171 }
7172
Chris Lattner66bc3252007-04-11 05:45:39 +00007173 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7174 // If we are just checking for a icmp eq of a single bit and zext'ing it
7175 // to an integer, then shift the bit to the appropriate place and then
7176 // cast to integer to avoid the comparison.
7177 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007178 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007179
7180 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7181 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7182 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7183 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7184 Value *In = ICI->getOperand(0);
7185 Value *Sh = ConstantInt::get(In->getType(),
7186 In->getType()->getPrimitiveSizeInBits()-1);
7187 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007188 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007189 CI);
7190 if (In->getType() != CI.getType())
7191 In = CastInst::createIntegerCast(In, CI.getType(),
7192 false/*ZExt*/, "tmp", &CI);
7193
7194 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7195 Constant *One = ConstantInt::get(In->getType(), 1);
7196 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007197 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007198 CI);
7199 }
7200
7201 return ReplaceInstUsesWith(CI, In);
7202 }
7203
7204
7205
Chris Lattnerba417832007-04-11 06:12:58 +00007206 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7207 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7208 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7209 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7210 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7211 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7212 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7213 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007214 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7215 // This only works for EQ and NE
7216 ICI->isEquality()) {
7217 // If Op1C some other power of two, convert:
7218 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7219 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7220 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7221 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7222
7223 APInt KnownZeroMask(~KnownZero);
7224 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7225 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7226 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7227 // (X&4) == 2 --> false
7228 // (X&4) != 2 --> true
7229 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7230 Res = ConstantExpr::getZExt(Res, CI.getType());
7231 return ReplaceInstUsesWith(CI, Res);
7232 }
7233
7234 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7235 Value *In = ICI->getOperand(0);
7236 if (ShiftAmt) {
7237 // Perform a logical shr by shiftamt.
7238 // Insert the shift to put the result in the low bit.
7239 In = InsertNewInstBefore(
7240 BinaryOperator::createLShr(In,
7241 ConstantInt::get(In->getType(), ShiftAmt),
7242 In->getName()+".lobit"), CI);
7243 }
7244
7245 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7246 Constant *One = ConstantInt::get(In->getType(), 1);
7247 In = BinaryOperator::createXor(In, One, "tmp");
7248 InsertNewInstBefore(cast<Instruction>(In), CI);
7249 }
7250
7251 if (CI.getType() == In->getType())
7252 return ReplaceInstUsesWith(CI, In);
7253 else
7254 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7255 }
7256 }
7257 }
7258 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007259 return 0;
7260}
7261
Chris Lattner8a9f5712007-04-11 06:57:46 +00007262Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007263 if (Instruction *I = commonIntCastTransforms(CI))
7264 return I;
7265
Chris Lattner8a9f5712007-04-11 06:57:46 +00007266 Value *Src = CI.getOperand(0);
7267
7268 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7269 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7270 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7271 // If we are just checking for a icmp eq of a single bit and zext'ing it
7272 // to an integer, then shift the bit to the appropriate place and then
7273 // cast to integer to avoid the comparison.
7274 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7275 const APInt &Op1CV = Op1C->getValue();
7276
7277 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7278 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7279 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7280 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7281 Value *In = ICI->getOperand(0);
7282 Value *Sh = ConstantInt::get(In->getType(),
7283 In->getType()->getPrimitiveSizeInBits()-1);
7284 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007285 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007286 CI);
7287 if (In->getType() != CI.getType())
7288 In = CastInst::createIntegerCast(In, CI.getType(),
7289 true/*SExt*/, "tmp", &CI);
7290
7291 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7292 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7293 In->getName()+".not"), CI);
7294
7295 return ReplaceInstUsesWith(CI, In);
7296 }
7297 }
7298 }
7299
Chris Lattnerba417832007-04-11 06:12:58 +00007300 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007301}
7302
Chris Lattnerb7530652008-01-27 05:29:54 +00007303/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7304/// in the specified FP type without changing its value.
7305static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7306 const fltSemantics &Sem) {
7307 APFloat F = CFP->getValueAPF();
7308 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7309 return ConstantFP::get(FPTy, F);
7310 return 0;
7311}
7312
7313/// LookThroughFPExtensions - If this is an fp extension instruction, look
7314/// through it until we get the source value.
7315static Value *LookThroughFPExtensions(Value *V) {
7316 if (Instruction *I = dyn_cast<Instruction>(V))
7317 if (I->getOpcode() == Instruction::FPExt)
7318 return LookThroughFPExtensions(I->getOperand(0));
7319
7320 // If this value is a constant, return the constant in the smallest FP type
7321 // that can accurately represent it. This allows us to turn
7322 // (float)((double)X+2.0) into x+2.0f.
7323 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7324 if (CFP->getType() == Type::PPC_FP128Ty)
7325 return V; // No constant folding of this.
7326 // See if the value can be truncated to float and then reextended.
7327 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7328 return V;
7329 if (CFP->getType() == Type::DoubleTy)
7330 return V; // Won't shrink.
7331 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7332 return V;
7333 // Don't try to shrink to various long double types.
7334 }
7335
7336 return V;
7337}
7338
7339Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7340 if (Instruction *I = commonCastTransforms(CI))
7341 return I;
7342
7343 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7344 // smaller than the destination type, we can eliminate the truncate by doing
7345 // the add as the smaller type. This applies to add/sub/mul/div as well as
7346 // many builtins (sqrt, etc).
7347 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7348 if (OpI && OpI->hasOneUse()) {
7349 switch (OpI->getOpcode()) {
7350 default: break;
7351 case Instruction::Add:
7352 case Instruction::Sub:
7353 case Instruction::Mul:
7354 case Instruction::FDiv:
7355 case Instruction::FRem:
7356 const Type *SrcTy = OpI->getType();
7357 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7358 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7359 if (LHSTrunc->getType() != SrcTy &&
7360 RHSTrunc->getType() != SrcTy) {
7361 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7362 // If the source types were both smaller than the destination type of
7363 // the cast, do this xform.
7364 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7365 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7366 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7367 CI.getType(), CI);
7368 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7369 CI.getType(), CI);
7370 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7371 }
7372 }
7373 break;
7374 }
7375 }
7376 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007377}
7378
7379Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7380 return commonCastTransforms(CI);
7381}
7382
7383Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007384 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007385}
7386
7387Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007388 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007389}
7390
7391Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7392 return commonCastTransforms(CI);
7393}
7394
7395Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7396 return commonCastTransforms(CI);
7397}
7398
7399Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007400 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007401}
7402
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007403Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7404 if (Instruction *I = commonCastTransforms(CI))
7405 return I;
7406
7407 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7408 if (!DestPointee->isSized()) return 0;
7409
7410 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7411 ConstantInt *Cst;
7412 Value *X;
7413 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7414 m_ConstantInt(Cst)))) {
7415 // If the source and destination operands have the same type, see if this
7416 // is a single-index GEP.
7417 if (X->getType() == CI.getType()) {
7418 // Get the size of the pointee type.
7419 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7420
7421 // Convert the constant to intptr type.
7422 APInt Offset = Cst->getValue();
7423 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7424
7425 // If Offset is evenly divisible by Size, we can do this xform.
7426 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7427 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7428 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7429 }
7430 }
7431 // TODO: Could handle other cases, e.g. where add is indexing into field of
7432 // struct etc.
7433 } else if (CI.getOperand(0)->hasOneUse() &&
7434 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7435 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7436 // "inttoptr+GEP" instead of "add+intptr".
7437
7438 // Get the size of the pointee type.
7439 uint64_t Size = TD->getABITypeSize(DestPointee);
7440
7441 // Convert the constant to intptr type.
7442 APInt Offset = Cst->getValue();
7443 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7444
7445 // If Offset is evenly divisible by Size, we can do this xform.
7446 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7447 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7448
7449 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7450 "tmp"), CI);
7451 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7452 }
7453 }
7454 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007455}
7456
Chris Lattnerd3e28342007-04-27 17:44:50 +00007457Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007458 // If the operands are integer typed then apply the integer transforms,
7459 // otherwise just apply the common ones.
7460 Value *Src = CI.getOperand(0);
7461 const Type *SrcTy = Src->getType();
7462 const Type *DestTy = CI.getType();
7463
Chris Lattner42a75512007-01-15 02:27:26 +00007464 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007465 if (Instruction *Result = commonIntCastTransforms(CI))
7466 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007467 } else if (isa<PointerType>(SrcTy)) {
7468 if (Instruction *I = commonPointerCastTransforms(CI))
7469 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007470 } else {
7471 if (Instruction *Result = commonCastTransforms(CI))
7472 return Result;
7473 }
7474
7475
7476 // Get rid of casts from one type to the same type. These are useless and can
7477 // be replaced by the operand.
7478 if (DestTy == Src->getType())
7479 return ReplaceInstUsesWith(CI, Src);
7480
Reid Spencer3da59db2006-11-27 01:05:10 +00007481 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007482 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7483 const Type *DstElTy = DstPTy->getElementType();
7484 const Type *SrcElTy = SrcPTy->getElementType();
7485
7486 // If we are casting a malloc or alloca to a pointer to a type of the same
7487 // size, rewrite the allocation instruction to allocate the "right" type.
7488 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7489 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7490 return V;
7491
Chris Lattnerd717c182007-05-05 22:32:24 +00007492 // If the source and destination are pointers, and this cast is equivalent
7493 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007494 // This can enhance SROA and other transforms that want type-safe pointers.
7495 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7496 unsigned NumZeros = 0;
7497 while (SrcElTy != DstElTy &&
7498 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7499 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7500 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7501 ++NumZeros;
7502 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007503
Chris Lattnerd3e28342007-04-27 17:44:50 +00007504 // If we found a path from the src to dest, create the getelementptr now.
7505 if (SrcElTy == DstElTy) {
7506 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007507 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7508 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007509 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007510 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007511
Reid Spencer3da59db2006-11-27 01:05:10 +00007512 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7513 if (SVI->hasOneUse()) {
7514 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7515 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007516 if (isa<VectorType>(DestTy) &&
7517 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007518 SVI->getType()->getNumElements()) {
7519 CastInst *Tmp;
7520 // If either of the operands is a cast from CI.getType(), then
7521 // evaluating the shuffle in the casted destination's type will allow
7522 // us to eliminate at least one cast.
7523 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7524 Tmp->getOperand(0)->getType() == DestTy) ||
7525 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7526 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007527 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7528 SVI->getOperand(0), DestTy, &CI);
7529 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7530 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007531 // Return a new shuffle vector. Use the same element ID's, as we
7532 // know the vector types match #elts.
7533 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007534 }
7535 }
7536 }
7537 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007538 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007539}
7540
Chris Lattnere576b912004-04-09 23:46:01 +00007541/// GetSelectFoldableOperands - We want to turn code that looks like this:
7542/// %C = or %A, %B
7543/// %D = select %cond, %C, %A
7544/// into:
7545/// %C = select %cond, %B, 0
7546/// %D = or %A, %C
7547///
7548/// Assuming that the specified instruction is an operand to the select, return
7549/// a bitmask indicating which operands of this instruction are foldable if they
7550/// equal the other incoming value of the select.
7551///
7552static unsigned GetSelectFoldableOperands(Instruction *I) {
7553 switch (I->getOpcode()) {
7554 case Instruction::Add:
7555 case Instruction::Mul:
7556 case Instruction::And:
7557 case Instruction::Or:
7558 case Instruction::Xor:
7559 return 3; // Can fold through either operand.
7560 case Instruction::Sub: // Can only fold on the amount subtracted.
7561 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007562 case Instruction::LShr:
7563 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007564 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007565 default:
7566 return 0; // Cannot fold
7567 }
7568}
7569
7570/// GetSelectFoldableConstant - For the same transformation as the previous
7571/// function, return the identity constant that goes into the select.
7572static Constant *GetSelectFoldableConstant(Instruction *I) {
7573 switch (I->getOpcode()) {
7574 default: assert(0 && "This cannot happen!"); abort();
7575 case Instruction::Add:
7576 case Instruction::Sub:
7577 case Instruction::Or:
7578 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007579 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007580 case Instruction::LShr:
7581 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007582 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007583 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007584 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007585 case Instruction::Mul:
7586 return ConstantInt::get(I->getType(), 1);
7587 }
7588}
7589
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007590/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7591/// have the same opcode and only one use each. Try to simplify this.
7592Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7593 Instruction *FI) {
7594 if (TI->getNumOperands() == 1) {
7595 // If this is a non-volatile load or a cast from the same type,
7596 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007597 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007598 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7599 return 0;
7600 } else {
7601 return 0; // unknown unary op.
7602 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007603
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007604 // Fold this by inserting a select from the input values.
7605 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7606 FI->getOperand(0), SI.getName()+".v");
7607 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007608 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7609 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007610 }
7611
Reid Spencer832254e2007-02-02 02:16:23 +00007612 // Only handle binary operators here.
7613 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007614 return 0;
7615
7616 // Figure out if the operations have any operands in common.
7617 Value *MatchOp, *OtherOpT, *OtherOpF;
7618 bool MatchIsOpZero;
7619 if (TI->getOperand(0) == FI->getOperand(0)) {
7620 MatchOp = TI->getOperand(0);
7621 OtherOpT = TI->getOperand(1);
7622 OtherOpF = FI->getOperand(1);
7623 MatchIsOpZero = true;
7624 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7625 MatchOp = TI->getOperand(1);
7626 OtherOpT = TI->getOperand(0);
7627 OtherOpF = FI->getOperand(0);
7628 MatchIsOpZero = false;
7629 } else if (!TI->isCommutative()) {
7630 return 0;
7631 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7632 MatchOp = TI->getOperand(0);
7633 OtherOpT = TI->getOperand(1);
7634 OtherOpF = FI->getOperand(0);
7635 MatchIsOpZero = true;
7636 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7637 MatchOp = TI->getOperand(1);
7638 OtherOpT = TI->getOperand(0);
7639 OtherOpF = FI->getOperand(1);
7640 MatchIsOpZero = true;
7641 } else {
7642 return 0;
7643 }
7644
7645 // If we reach here, they do have operations in common.
7646 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7647 OtherOpF, SI.getName()+".v");
7648 InsertNewInstBefore(NewSI, SI);
7649
7650 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7651 if (MatchIsOpZero)
7652 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7653 else
7654 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007655 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007656 assert(0 && "Shouldn't get here");
7657 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007658}
7659
Chris Lattner3d69f462004-03-12 05:52:32 +00007660Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007661 Value *CondVal = SI.getCondition();
7662 Value *TrueVal = SI.getTrueValue();
7663 Value *FalseVal = SI.getFalseValue();
7664
7665 // select true, X, Y -> X
7666 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007667 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007668 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007669
7670 // select C, X, X -> X
7671 if (TrueVal == FalseVal)
7672 return ReplaceInstUsesWith(SI, TrueVal);
7673
Chris Lattnere87597f2004-10-16 18:11:37 +00007674 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7675 return ReplaceInstUsesWith(SI, FalseVal);
7676 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7677 return ReplaceInstUsesWith(SI, TrueVal);
7678 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7679 if (isa<Constant>(TrueVal))
7680 return ReplaceInstUsesWith(SI, TrueVal);
7681 else
7682 return ReplaceInstUsesWith(SI, FalseVal);
7683 }
7684
Reid Spencer4fe16d62007-01-11 18:21:29 +00007685 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007686 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007687 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007688 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007689 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007690 } else {
7691 // Change: A = select B, false, C --> A = and !B, C
7692 Value *NotCond =
7693 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7694 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007695 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007696 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007697 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007698 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007699 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007700 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007701 } else {
7702 // Change: A = select B, C, true --> A = or !B, C
7703 Value *NotCond =
7704 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7705 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007706 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007707 }
7708 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007709
7710 // select a, b, a -> a&b
7711 // select a, a, b -> a|b
7712 if (CondVal == TrueVal)
7713 return BinaryOperator::createOr(CondVal, FalseVal);
7714 else if (CondVal == FalseVal)
7715 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007716 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007717
Chris Lattner2eefe512004-04-09 19:05:30 +00007718 // Selecting between two integer constants?
7719 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7720 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007721 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007722 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007723 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007724 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007725 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007726 Value *NotCond =
7727 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007728 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007729 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007730 }
Chris Lattnerba417832007-04-11 06:12:58 +00007731
7732 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007733
Reid Spencere4d87aa2006-12-23 06:05:41 +00007734 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007735
Reid Spencere4d87aa2006-12-23 06:05:41 +00007736 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007737 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007738 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007739 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007740 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007741 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007742 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007743 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007744 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7745 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7746 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007747 InsertNewInstBefore(SRA, SI);
7748
Reid Spencer3da59db2006-11-27 01:05:10 +00007749 // Finally, convert to the type of the select RHS. We figure out
7750 // if this requires a SExt, Trunc or BitCast based on the sizes.
7751 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007752 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7753 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007754 if (SRASize < SISize)
7755 opc = Instruction::SExt;
7756 else if (SRASize > SISize)
7757 opc = Instruction::Trunc;
7758 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007759 }
7760 }
7761
7762
7763 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007764 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007765 // non-constant value, eliminate this whole mess. This corresponds to
7766 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007767 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007768 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007769 cast<Constant>(IC->getOperand(1))->isNullValue())
7770 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7771 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007772 isa<ConstantInt>(ICA->getOperand(1)) &&
7773 (ICA->getOperand(1) == TrueValC ||
7774 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007775 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7776 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007777 // know whether we have a icmp_ne or icmp_eq and whether the
7778 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007779 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007780 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007781 Value *V = ICA;
7782 if (ShouldNotVal)
7783 V = InsertNewInstBefore(BinaryOperator::create(
7784 Instruction::Xor, V, ICA->getOperand(1)), SI);
7785 return ReplaceInstUsesWith(SI, V);
7786 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007787 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007788 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007789
7790 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007791 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7792 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007793 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007794 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7795 // This is not safe in general for floating point:
7796 // consider X== -0, Y== +0.
7797 // It becomes safe if either operand is a nonzero constant.
7798 ConstantFP *CFPt, *CFPf;
7799 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7800 !CFPt->getValueAPF().isZero()) ||
7801 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7802 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007803 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007804 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007805 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007806 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007807 return ReplaceInstUsesWith(SI, TrueVal);
7808 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7809
Reid Spencere4d87aa2006-12-23 06:05:41 +00007810 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007811 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007812 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7813 // This is not safe in general for floating point:
7814 // consider X== -0, Y== +0.
7815 // It becomes safe if either operand is a nonzero constant.
7816 ConstantFP *CFPt, *CFPf;
7817 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7818 !CFPt->getValueAPF().isZero()) ||
7819 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7820 !CFPf->getValueAPF().isZero()))
7821 return ReplaceInstUsesWith(SI, FalseVal);
7822 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007823 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007824 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7825 return ReplaceInstUsesWith(SI, TrueVal);
7826 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7827 }
7828 }
7829
7830 // See if we are selecting two values based on a comparison of the two values.
7831 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7832 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7833 // Transform (X == Y) ? X : Y -> Y
7834 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7835 return ReplaceInstUsesWith(SI, FalseVal);
7836 // Transform (X != Y) ? X : Y -> X
7837 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7838 return ReplaceInstUsesWith(SI, TrueVal);
7839 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7840
7841 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7842 // Transform (X == Y) ? Y : X -> X
7843 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7844 return ReplaceInstUsesWith(SI, FalseVal);
7845 // Transform (X != Y) ? Y : X -> Y
7846 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007847 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007848 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7849 }
7850 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007851
Chris Lattner87875da2005-01-13 22:52:24 +00007852 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7853 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7854 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007855 Instruction *AddOp = 0, *SubOp = 0;
7856
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007857 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7858 if (TI->getOpcode() == FI->getOpcode())
7859 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7860 return IV;
7861
7862 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7863 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007864 if (TI->getOpcode() == Instruction::Sub &&
7865 FI->getOpcode() == Instruction::Add) {
7866 AddOp = FI; SubOp = TI;
7867 } else if (FI->getOpcode() == Instruction::Sub &&
7868 TI->getOpcode() == Instruction::Add) {
7869 AddOp = TI; SubOp = FI;
7870 }
7871
7872 if (AddOp) {
7873 Value *OtherAddOp = 0;
7874 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7875 OtherAddOp = AddOp->getOperand(1);
7876 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7877 OtherAddOp = AddOp->getOperand(0);
7878 }
7879
7880 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007881 // So at this point we know we have (Y -> OtherAddOp):
7882 // select C, (add X, Y), (sub X, Z)
7883 Value *NegVal; // Compute -Z
7884 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7885 NegVal = ConstantExpr::getNeg(C);
7886 } else {
7887 NegVal = InsertNewInstBefore(
7888 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007889 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007890
7891 Value *NewTrueOp = OtherAddOp;
7892 Value *NewFalseOp = NegVal;
7893 if (AddOp != TI)
7894 std::swap(NewTrueOp, NewFalseOp);
7895 Instruction *NewSel =
7896 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7897
7898 NewSel = InsertNewInstBefore(NewSel, SI);
7899 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007900 }
7901 }
7902 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007903
Chris Lattnere576b912004-04-09 23:46:01 +00007904 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007905 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007906 // See the comment above GetSelectFoldableOperands for a description of the
7907 // transformation we are doing here.
7908 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7909 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7910 !isa<Constant>(FalseVal))
7911 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7912 unsigned OpToFold = 0;
7913 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7914 OpToFold = 1;
7915 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7916 OpToFold = 2;
7917 }
7918
7919 if (OpToFold) {
7920 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007921 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007922 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007923 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007924 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007925 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7926 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007927 else {
7928 assert(0 && "Unknown instruction!!");
7929 }
7930 }
7931 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007932
Chris Lattnere576b912004-04-09 23:46:01 +00007933 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7934 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7935 !isa<Constant>(TrueVal))
7936 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7937 unsigned OpToFold = 0;
7938 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7939 OpToFold = 1;
7940 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7941 OpToFold = 2;
7942 }
7943
7944 if (OpToFold) {
7945 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007946 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007947 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007948 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007949 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007950 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7951 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007952 else
Chris Lattnere576b912004-04-09 23:46:01 +00007953 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007954 }
7955 }
7956 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007957
7958 if (BinaryOperator::isNot(CondVal)) {
7959 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7960 SI.setOperand(1, FalseVal);
7961 SI.setOperand(2, TrueVal);
7962 return &SI;
7963 }
7964
Chris Lattner3d69f462004-03-12 05:52:32 +00007965 return 0;
7966}
7967
Chris Lattnerf2369f22007-08-09 19:05:49 +00007968/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7969/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7970/// and it is more than the alignment of the ultimate object, see if we can
7971/// increase the alignment of the ultimate object, making this check succeed.
7972static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7973 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007974 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7975 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007976 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007977 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007978
7979 // If there is a large requested alignment and we can, bump up the alignment
7980 // of the global.
7981 if (PrefAlign > Align && GV->hasInitializer()) {
7982 GV->setAlignment(PrefAlign);
7983 Align = PrefAlign;
7984 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007985 return Align;
7986 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7987 unsigned Align = AI->getAlignment();
7988 if (Align == 0 && TD) {
7989 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007990 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007991 else if (isa<MallocInst>(AI)) {
7992 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007993 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007994 Align =
7995 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007996 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007997 Align =
7998 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007999 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00008000 }
8001 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008002
8003 // If there is a requested alignment and if this is an alloca, round up. We
8004 // don't do this for malloc, because some systems can't respect the request.
8005 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8006 AI->setAlignment(PrefAlign);
8007 Align = PrefAlign;
8008 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008009 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00008010 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00008011 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008013 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8014 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00008015 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008016 // If all indexes are zero, it is just the alignment of the base pointer.
8017 bool AllZeroOperands = true;
8018 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8019 if (!isa<Constant>(GEPI->getOperand(i)) ||
8020 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8021 AllZeroOperands = false;
8022 break;
8023 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008024
8025 if (AllZeroOperands) {
8026 // Treat this like a bitcast.
8027 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8028 }
8029
8030 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8031 if (BaseAlignment == 0) return 0;
8032
Chris Lattner95a959d2006-03-06 20:18:44 +00008033 // Otherwise, if the base alignment is >= the alignment we expect for the
8034 // base pointer type, then we know that the resultant pointer is aligned at
8035 // least as much as its type requires.
8036 if (!TD) return 0;
8037
8038 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008039 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008040 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8041 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00008042 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008043 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008044 Align = std::min(Align, (unsigned)
8045 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8046 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00008047 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008048 return 0;
8049 }
8050 return 0;
8051}
8052
Chris Lattnerf497b022008-01-13 23:50:23 +00008053Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8054 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8055 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8056 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8057 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8058
8059 if (CopyAlign < MinAlign) {
8060 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8061 return MI;
8062 }
8063
8064 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8065 // load/store.
8066 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8067 if (MemOpLength == 0) return 0;
8068
Chris Lattner37ac6082008-01-14 00:28:35 +00008069 // Source and destination pointer types are always "i8*" for intrinsic. See
8070 // if the size is something we can handle with a single primitive load/store.
8071 // A single load+store correctly handles overlapping memory in the memmove
8072 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008073 unsigned Size = MemOpLength->getZExtValue();
8074 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008075 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008076
Chris Lattner37ac6082008-01-14 00:28:35 +00008077 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008078 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008079
8080 // Memcpy forces the use of i8* for the source and destination. That means
8081 // that if you're using memcpy to move one double around, you'll get a cast
8082 // from double* to i8*. We'd much rather use a double load+store rather than
8083 // an i64 load+store, here because this improves the odds that the source or
8084 // dest address will be promotable. See if we can find a better type than the
8085 // integer datatype.
8086 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8087 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8088 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8089 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8090 // down through these levels if so.
8091 while (!SrcETy->isFirstClassType()) {
8092 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8093 if (STy->getNumElements() == 1)
8094 SrcETy = STy->getElementType(0);
8095 else
8096 break;
8097 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8098 if (ATy->getNumElements() == 1)
8099 SrcETy = ATy->getElementType();
8100 else
8101 break;
8102 } else
8103 break;
8104 }
8105
8106 if (SrcETy->isFirstClassType())
8107 NewPtrTy = PointerType::getUnqual(SrcETy);
8108 }
8109 }
8110
8111
Chris Lattnerf497b022008-01-13 23:50:23 +00008112 // If the memcpy/memmove provides better alignment info than we can
8113 // infer, use it.
8114 SrcAlign = std::max(SrcAlign, CopyAlign);
8115 DstAlign = std::max(DstAlign, CopyAlign);
8116
8117 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8118 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008119 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8120 InsertNewInstBefore(L, *MI);
8121 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8122
8123 // Set the size of the copy to 0, it will be deleted on the next iteration.
8124 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8125 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008126}
Chris Lattner3d69f462004-03-12 05:52:32 +00008127
Chris Lattner8b0ea312006-01-13 20:11:04 +00008128/// visitCallInst - CallInst simplification. This mostly only handles folding
8129/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8130/// the heavy lifting.
8131///
Chris Lattner9fe38862003-06-19 17:00:31 +00008132Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008133 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8134 if (!II) return visitCallSite(&CI);
8135
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008136 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8137 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008138 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008139 bool Changed = false;
8140
8141 // memmove/cpy/set of zero bytes is a noop.
8142 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8143 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8144
Chris Lattner35b9e482004-10-12 04:52:52 +00008145 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008146 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008147 // Replace the instruction with just byte operations. We would
8148 // transform other cases to loads/stores, but we don't know if
8149 // alignment is sufficient.
8150 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008151 }
8152
Chris Lattner35b9e482004-10-12 04:52:52 +00008153 // If we have a memmove and the source operation is a constant global,
8154 // then the source and dest pointers can't alias, so we can change this
8155 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008156 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008157 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8158 if (GVSrc->isConstant()) {
8159 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008160 Intrinsic::ID MemCpyID;
8161 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8162 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008163 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008164 MemCpyID = Intrinsic::memcpy_i64;
8165 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008166 Changed = true;
8167 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008168 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008169
Chris Lattner95a959d2006-03-06 20:18:44 +00008170 // If we can determine a pointer alignment that is bigger than currently
8171 // set, update the alignment.
8172 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008173 if (Instruction *I = SimplifyMemTransfer(MI))
8174 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008175 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008176 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008177 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008178 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008179 Changed = true;
8180 }
8181 }
8182
Chris Lattner8b0ea312006-01-13 20:11:04 +00008183 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008184 } else {
8185 switch (II->getIntrinsicID()) {
8186 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008187 case Intrinsic::ppc_altivec_lvx:
8188 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008189 case Intrinsic::x86_sse_loadu_ps:
8190 case Intrinsic::x86_sse2_loadu_pd:
8191 case Intrinsic::x86_sse2_loadu_dq:
8192 // Turn PPC lvx -> load if the pointer is known aligned.
8193 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008194 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008195 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8196 PointerType::getUnqual(II->getType()),
8197 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008198 return new LoadInst(Ptr);
8199 }
8200 break;
8201 case Intrinsic::ppc_altivec_stvx:
8202 case Intrinsic::ppc_altivec_stvxl:
8203 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008204 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008205 const Type *OpPtrTy =
8206 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008207 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008208 return new StoreInst(II->getOperand(1), Ptr);
8209 }
8210 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008211 case Intrinsic::x86_sse_storeu_ps:
8212 case Intrinsic::x86_sse2_storeu_pd:
8213 case Intrinsic::x86_sse2_storeu_dq:
8214 case Intrinsic::x86_sse2_storel_dq:
8215 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008216 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008217 const Type *OpPtrTy =
8218 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008219 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008220 return new StoreInst(II->getOperand(2), Ptr);
8221 }
8222 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008223
8224 case Intrinsic::x86_sse_cvttss2si: {
8225 // These intrinsics only demands the 0th element of its input vector. If
8226 // we can simplify the input based on that, do so now.
8227 uint64_t UndefElts;
8228 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8229 UndefElts)) {
8230 II->setOperand(1, V);
8231 return II;
8232 }
8233 break;
8234 }
8235
Chris Lattnere2ed0572006-04-06 19:19:17 +00008236 case Intrinsic::ppc_altivec_vperm:
8237 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008238 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008239 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8240
8241 // Check that all of the elements are integer constants or undefs.
8242 bool AllEltsOk = true;
8243 for (unsigned i = 0; i != 16; ++i) {
8244 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8245 !isa<UndefValue>(Mask->getOperand(i))) {
8246 AllEltsOk = false;
8247 break;
8248 }
8249 }
8250
8251 if (AllEltsOk) {
8252 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008253 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8254 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008255 Value *Result = UndefValue::get(Op0->getType());
8256
8257 // Only extract each element once.
8258 Value *ExtractedElts[32];
8259 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8260
8261 for (unsigned i = 0; i != 16; ++i) {
8262 if (isa<UndefValue>(Mask->getOperand(i)))
8263 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008264 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008265 Idx &= 31; // Match the hardware behavior.
8266
8267 if (ExtractedElts[Idx] == 0) {
8268 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008269 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008270 InsertNewInstBefore(Elt, CI);
8271 ExtractedElts[Idx] = Elt;
8272 }
8273
8274 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008275 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008276 InsertNewInstBefore(cast<Instruction>(Result), CI);
8277 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008278 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008279 }
8280 }
8281 break;
8282
Chris Lattnera728ddc2006-01-13 21:28:09 +00008283 case Intrinsic::stackrestore: {
8284 // If the save is right next to the restore, remove the restore. This can
8285 // happen when variable allocas are DCE'd.
8286 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8287 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8288 BasicBlock::iterator BI = SS;
8289 if (&*++BI == II)
8290 return EraseInstFromFunction(CI);
8291 }
8292 }
8293
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008294 // Scan down this block to see if there is another stack restore in the
8295 // same block without an intervening call/alloca.
8296 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008297 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008298 bool CannotRemove = false;
8299 for (++BI; &*BI != TI; ++BI) {
8300 if (isa<AllocaInst>(BI)) {
8301 CannotRemove = true;
8302 break;
8303 }
8304 if (isa<CallInst>(BI)) {
8305 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008306 CannotRemove = true;
8307 break;
8308 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008309 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008310 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008311 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008312 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008313
8314 // If the stack restore is in a return/unwind block and if there are no
8315 // allocas or calls between the restore and the return, nuke the restore.
8316 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8317 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008318 break;
8319 }
8320 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008321 }
8322
Chris Lattner8b0ea312006-01-13 20:11:04 +00008323 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008324}
8325
8326// InvokeInst simplification
8327//
8328Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008329 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008330}
8331
Chris Lattnera44d8a22003-10-07 22:32:43 +00008332// visitCallSite - Improvements for call and invoke instructions.
8333//
8334Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008335 bool Changed = false;
8336
8337 // If the callee is a constexpr cast of a function, attempt to move the cast
8338 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008339 if (transformConstExprCastCall(CS)) return 0;
8340
Chris Lattner6c266db2003-10-07 22:54:13 +00008341 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008342
Chris Lattner08b22ec2005-05-13 07:09:09 +00008343 if (Function *CalleeF = dyn_cast<Function>(Callee))
8344 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8345 Instruction *OldCall = CS.getInstruction();
8346 // If the call and callee calling conventions don't match, this call must
8347 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008348 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008349 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8350 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008351 if (!OldCall->use_empty())
8352 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8353 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8354 return EraseInstFromFunction(*OldCall);
8355 return 0;
8356 }
8357
Chris Lattner17be6352004-10-18 02:59:09 +00008358 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8359 // This instruction is not reachable, just remove it. We insert a store to
8360 // undef so that we know that this code is not reachable, despite the fact
8361 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008362 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008363 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008364 CS.getInstruction());
8365
8366 if (!CS.getInstruction()->use_empty())
8367 CS.getInstruction()->
8368 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8369
8370 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8371 // Don't break the CFG, insert a dummy cond branch.
8372 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008373 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008374 }
Chris Lattner17be6352004-10-18 02:59:09 +00008375 return EraseInstFromFunction(*CS.getInstruction());
8376 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008377
Duncan Sandscdb6d922007-09-17 10:26:40 +00008378 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8379 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8380 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8381 return transformCallThroughTrampoline(CS);
8382
Chris Lattner6c266db2003-10-07 22:54:13 +00008383 const PointerType *PTy = cast<PointerType>(Callee->getType());
8384 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8385 if (FTy->isVarArg()) {
8386 // See if we can optimize any arguments passed through the varargs area of
8387 // the call.
8388 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8389 E = CS.arg_end(); I != E; ++I)
8390 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8391 // If this cast does not effect the value passed through the varargs
8392 // area, we can eliminate the use of the cast.
8393 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008394 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008395 *I = Op;
8396 Changed = true;
8397 }
8398 }
8399 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008400
Duncan Sandsf0c33542007-12-19 21:13:37 +00008401 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008402 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008403 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008404 Changed = true;
8405 }
8406
Chris Lattner6c266db2003-10-07 22:54:13 +00008407 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008408}
8409
Chris Lattner9fe38862003-06-19 17:00:31 +00008410// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8411// attempt to move the cast to the arguments of the call/invoke.
8412//
8413bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8414 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8415 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008416 if (CE->getOpcode() != Instruction::BitCast ||
8417 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008418 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008419 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008420 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008421 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008422
8423 // Okay, this is a cast from a function to a different type. Unless doing so
8424 // would cause a type conversion of one of our arguments, change this call to
8425 // be a direct call with arguments casted to the appropriate types.
8426 //
8427 const FunctionType *FT = Callee->getFunctionType();
8428 const Type *OldRetTy = Caller->getType();
8429
Devang Patel75e6f022008-03-11 18:04:06 +00008430 if (isa<StructType>(FT->getReturnType()))
8431 return false; // TODO: Handle multiple return values.
8432
Chris Lattnerf78616b2004-01-14 06:06:08 +00008433 // Check to see if we are changing the return type...
8434 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008435 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008436 // Conversion is ok if changing from pointer to int of same size.
8437 !(isa<PointerType>(FT->getReturnType()) &&
8438 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008439 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008440
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008441 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008442 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008443 FT->getReturnType() != Type::VoidTy &&
8444 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008445 return false; // Cannot transform this return value.
8446
Chris Lattner58d74912008-03-12 17:45:29 +00008447 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8448 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008449 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8450 return false; // Attribute not compatible with transformed value.
8451 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008452
Chris Lattnerf78616b2004-01-14 06:06:08 +00008453 // If the callsite is an invoke instruction, and the return value is used by
8454 // a PHI node in a successor, we cannot change the return type of the call
8455 // because there is no place to put the cast instruction (without breaking
8456 // the critical edge). Bail out in this case.
8457 if (!Caller->use_empty())
8458 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8459 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8460 UI != E; ++UI)
8461 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8462 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008463 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008464 return false;
8465 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008466
8467 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8468 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008469
Chris Lattner9fe38862003-06-19 17:00:31 +00008470 CallSite::arg_iterator AI = CS.arg_begin();
8471 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8472 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008473 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008474
8475 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008476 return false; // Cannot transform this parameter value.
8477
Chris Lattner58d74912008-03-12 17:45:29 +00008478 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8479 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008480
Reid Spencer3da59db2006-11-27 01:05:10 +00008481 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008482 // Some conversions are safe even if we do not have a body.
8483 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008484 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008485 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008486 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008487 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8488 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008489 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008490 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008491 }
8492
8493 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008494 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008495 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008496
Chris Lattner58d74912008-03-12 17:45:29 +00008497 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8498 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008499 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008500 // won't be dropping them. Check that these extra arguments have attributes
8501 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008502 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8503 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008504 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008505 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008506 if (PAttrs & ParamAttr::VarArgsIncompatible)
8507 return false;
8508 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008509
Chris Lattner9fe38862003-06-19 17:00:31 +00008510 // Okay, we decided that this is a safe thing to do: go ahead and start
8511 // inserting cast instructions as necessary...
8512 std::vector<Value*> Args;
8513 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008514 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008515 attrVec.reserve(NumCommonArgs);
8516
8517 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008518 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008519
8520 // If the return value is not being used, the type may not be compatible
8521 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008522 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008523
8524 // Add the new return attributes.
8525 if (RAttrs)
8526 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008527
8528 AI = CS.arg_begin();
8529 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8530 const Type *ParamTy = FT->getParamType(i);
8531 if ((*AI)->getType() == ParamTy) {
8532 Args.push_back(*AI);
8533 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008534 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008535 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008536 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008537 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008538 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008539
8540 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008541 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008542 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008543 }
8544
8545 // If the function takes more arguments than the call was taking, add them
8546 // now...
8547 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8548 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8549
8550 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008551 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008552 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008553 cerr << "WARNING: While resolving call to function '"
8554 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008555 } else {
8556 // Add all of the arguments in their promoted form to the arg list...
8557 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8558 const Type *PTy = getPromotedType((*AI)->getType());
8559 if (PTy != (*AI)->getType()) {
8560 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008561 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8562 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008563 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008564 InsertNewInstBefore(Cast, *Caller);
8565 Args.push_back(Cast);
8566 } else {
8567 Args.push_back(*AI);
8568 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008569
Duncan Sandse1e520f2008-01-13 08:02:44 +00008570 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008571 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008572 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8573 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008574 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008575 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008576
8577 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008578 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008579
Chris Lattner58d74912008-03-12 17:45:29 +00008580 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008581
Chris Lattner9fe38862003-06-19 17:00:31 +00008582 Instruction *NC;
8583 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008584 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008585 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008586 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008587 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008588 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008589 NC = new CallInst(Callee, Args.begin(), Args.end(),
8590 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008591 CallInst *CI = cast<CallInst>(Caller);
8592 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008593 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008594 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008595 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008596 }
8597
Chris Lattner6934a042007-02-11 01:23:03 +00008598 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008599 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008600 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008601 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008602 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008603 OldRetTy, false);
8604 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008605
8606 // If this is an invoke instruction, we should insert it after the first
8607 // non-phi, instruction in the normal successor block.
8608 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8609 BasicBlock::iterator I = II->getNormalDest()->begin();
8610 while (isa<PHINode>(I)) ++I;
8611 InsertNewInstBefore(NC, *I);
8612 } else {
8613 // Otherwise, it's a call, just insert cast right after the call instr
8614 InsertNewInstBefore(NC, *Caller);
8615 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008616 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008617 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008618 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008619 }
8620 }
8621
8622 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8623 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008624 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008625 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008626 return true;
8627}
8628
Duncan Sandscdb6d922007-09-17 10:26:40 +00008629// transformCallThroughTrampoline - Turn a call to a function created by the
8630// init_trampoline intrinsic into a direct call to the underlying function.
8631//
8632Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8633 Value *Callee = CS.getCalledValue();
8634 const PointerType *PTy = cast<PointerType>(Callee->getType());
8635 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008636 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008637
8638 // If the call already has the 'nest' attribute somewhere then give up -
8639 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008640 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008641 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008642
8643 IntrinsicInst *Tramp =
8644 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8645
8646 Function *NestF =
8647 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8648 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8649 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8650
Chris Lattner58d74912008-03-12 17:45:29 +00008651 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8652 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008653 unsigned NestIdx = 1;
8654 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008655 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008656
8657 // Look for a parameter marked with the 'nest' attribute.
8658 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8659 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008660 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008661 // Record the parameter type and any other attributes.
8662 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008663 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008664 break;
8665 }
8666
8667 if (NestTy) {
8668 Instruction *Caller = CS.getInstruction();
8669 std::vector<Value*> NewArgs;
8670 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8671
Chris Lattner58d74912008-03-12 17:45:29 +00008672 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8673 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008674
Duncan Sandscdb6d922007-09-17 10:26:40 +00008675 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008676 // mean appending it. Likewise for attributes.
8677
8678 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008679 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8680 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008681
Duncan Sandscdb6d922007-09-17 10:26:40 +00008682 {
8683 unsigned Idx = 1;
8684 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8685 do {
8686 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008687 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008688 Value *NestVal = Tramp->getOperand(3);
8689 if (NestVal->getType() != NestTy)
8690 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8691 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008692 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008693 }
8694
8695 if (I == E)
8696 break;
8697
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008698 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008699 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008700 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008701 NewAttrs.push_back
8702 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008703
8704 ++Idx, ++I;
8705 } while (1);
8706 }
8707
8708 // The trampoline may have been bitcast to a bogus type (FTy).
8709 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008710 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008711
Duncan Sandscdb6d922007-09-17 10:26:40 +00008712 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008713 NewTypes.reserve(FTy->getNumParams()+1);
8714
Duncan Sandscdb6d922007-09-17 10:26:40 +00008715 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008716 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008717 {
8718 unsigned Idx = 1;
8719 FunctionType::param_iterator I = FTy->param_begin(),
8720 E = FTy->param_end();
8721
8722 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008723 if (Idx == NestIdx)
8724 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008725 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008726
8727 if (I == E)
8728 break;
8729
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008730 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008731 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008732
8733 ++Idx, ++I;
8734 } while (1);
8735 }
8736
8737 // Replace the trampoline call with a direct call. Let the generic
8738 // code sort out any function type mismatches.
8739 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008740 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008741 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8742 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008743 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008744
8745 Instruction *NewCaller;
8746 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8747 NewCaller = new InvokeInst(NewCallee,
8748 II->getNormalDest(), II->getUnwindDest(),
8749 NewArgs.begin(), NewArgs.end(),
8750 Caller->getName(), Caller);
8751 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008752 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008753 } else {
8754 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8755 Caller->getName(), Caller);
8756 if (cast<CallInst>(Caller)->isTailCall())
8757 cast<CallInst>(NewCaller)->setTailCall();
8758 cast<CallInst>(NewCaller)->
8759 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008760 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008761 }
8762 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8763 Caller->replaceAllUsesWith(NewCaller);
8764 Caller->eraseFromParent();
8765 RemoveFromWorkList(Caller);
8766 return 0;
8767 }
8768 }
8769
8770 // Replace the trampoline call with a direct call. Since there is no 'nest'
8771 // parameter, there is no need to adjust the argument list. Let the generic
8772 // code sort out any function type mismatches.
8773 Constant *NewCallee =
8774 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8775 CS.setCalledFunction(NewCallee);
8776 return CS.getInstruction();
8777}
8778
Chris Lattner7da52b22006-11-01 04:51:18 +00008779/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8780/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8781/// and a single binop.
8782Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8783 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008784 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8785 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008786 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008787 Value *LHSVal = FirstInst->getOperand(0);
8788 Value *RHSVal = FirstInst->getOperand(1);
8789
8790 const Type *LHSType = LHSVal->getType();
8791 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008792
8793 // Scan to see if all operands are the same opcode, all have one use, and all
8794 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008795 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008796 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008797 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008798 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008799 // types or GEP's with different index types.
8800 I->getOperand(0)->getType() != LHSType ||
8801 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008802 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008803
8804 // If they are CmpInst instructions, check their predicates
8805 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8806 if (cast<CmpInst>(I)->getPredicate() !=
8807 cast<CmpInst>(FirstInst)->getPredicate())
8808 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008809
8810 // Keep track of which operand needs a phi node.
8811 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8812 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008813 }
8814
Chris Lattner53738a42006-11-08 19:42:28 +00008815 // Otherwise, this is safe to transform, determine if it is profitable.
8816
8817 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8818 // Indexes are often folded into load/store instructions, so we don't want to
8819 // hide them behind a phi.
8820 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8821 return 0;
8822
Chris Lattner7da52b22006-11-01 04:51:18 +00008823 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008824 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008825 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008826 if (LHSVal == 0) {
8827 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8828 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8829 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008830 InsertNewInstBefore(NewLHS, PN);
8831 LHSVal = NewLHS;
8832 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008833
8834 if (RHSVal == 0) {
8835 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8836 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8837 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008838 InsertNewInstBefore(NewRHS, PN);
8839 RHSVal = NewRHS;
8840 }
8841
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008842 // Add all operands to the new PHIs.
8843 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8844 if (NewLHS) {
8845 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8846 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8847 }
8848 if (NewRHS) {
8849 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8850 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8851 }
8852 }
8853
Chris Lattner7da52b22006-11-01 04:51:18 +00008854 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008855 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008856 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8857 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8858 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008859 else {
8860 assert(isa<GetElementPtrInst>(FirstInst));
8861 return new GetElementPtrInst(LHSVal, RHSVal);
8862 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008863}
8864
Chris Lattner76c73142006-11-01 07:13:54 +00008865/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8866/// of the block that defines it. This means that it must be obvious the value
8867/// of the load is not changed from the point of the load to the end of the
8868/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008869///
8870/// Finally, it is safe, but not profitable, to sink a load targetting a
8871/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8872/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008873static bool isSafeToSinkLoad(LoadInst *L) {
8874 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8875
8876 for (++BBI; BBI != E; ++BBI)
8877 if (BBI->mayWriteToMemory())
8878 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008879
8880 // Check for non-address taken alloca. If not address-taken already, it isn't
8881 // profitable to do this xform.
8882 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8883 bool isAddressTaken = false;
8884 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8885 UI != E; ++UI) {
8886 if (isa<LoadInst>(UI)) continue;
8887 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8888 // If storing TO the alloca, then the address isn't taken.
8889 if (SI->getOperand(1) == AI) continue;
8890 }
8891 isAddressTaken = true;
8892 break;
8893 }
8894
8895 if (!isAddressTaken)
8896 return false;
8897 }
8898
Chris Lattner76c73142006-11-01 07:13:54 +00008899 return true;
8900}
8901
Chris Lattner9fe38862003-06-19 17:00:31 +00008902
Chris Lattnerbac32862004-11-14 19:13:23 +00008903// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8904// operator and they all are only used by the PHI, PHI together their
8905// inputs, and do the operation once, to the result of the PHI.
8906Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8907 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8908
8909 // Scan the instruction, looking for input operations that can be folded away.
8910 // If all input operands to the phi are the same instruction (e.g. a cast from
8911 // the same type or "+42") we can pull the operation through the PHI, reducing
8912 // code size and simplifying code.
8913 Constant *ConstantOp = 0;
8914 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008915 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008916 if (isa<CastInst>(FirstInst)) {
8917 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008918 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008919 // Can fold binop, compare or shift here if the RHS is a constant,
8920 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008921 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008922 if (ConstantOp == 0)
8923 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008924 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8925 isVolatile = LI->isVolatile();
8926 // We can't sink the load if the loaded value could be modified between the
8927 // load and the PHI.
8928 if (LI->getParent() != PN.getIncomingBlock(0) ||
8929 !isSafeToSinkLoad(LI))
8930 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008931 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008932 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008933 return FoldPHIArgBinOpIntoPHI(PN);
8934 // Can't handle general GEPs yet.
8935 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008936 } else {
8937 return 0; // Cannot fold this operation.
8938 }
8939
8940 // Check to see if all arguments are the same operation.
8941 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8942 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8943 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008944 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008945 return 0;
8946 if (CastSrcTy) {
8947 if (I->getOperand(0)->getType() != CastSrcTy)
8948 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008949 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008950 // We can't sink the load if the loaded value could be modified between
8951 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008952 if (LI->isVolatile() != isVolatile ||
8953 LI->getParent() != PN.getIncomingBlock(i) ||
8954 !isSafeToSinkLoad(LI))
8955 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008956 } else if (I->getOperand(1) != ConstantOp) {
8957 return 0;
8958 }
8959 }
8960
8961 // Okay, they are all the same operation. Create a new PHI node of the
8962 // correct type, and PHI together all of the LHS's of the instructions.
8963 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8964 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008965 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008966
8967 Value *InVal = FirstInst->getOperand(0);
8968 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008969
8970 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008971 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8972 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8973 if (NewInVal != InVal)
8974 InVal = 0;
8975 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8976 }
8977
8978 Value *PhiVal;
8979 if (InVal) {
8980 // The new PHI unions all of the same values together. This is really
8981 // common, so we handle it intelligently here for compile-time speed.
8982 PhiVal = InVal;
8983 delete NewPN;
8984 } else {
8985 InsertNewInstBefore(NewPN, PN);
8986 PhiVal = NewPN;
8987 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008988
Chris Lattnerbac32862004-11-14 19:13:23 +00008989 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008990 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8991 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008992 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008993 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008994 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008995 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008996 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8997 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8998 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008999 else
Reid Spencer832254e2007-02-02 02:16:23 +00009000 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009001 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009002}
Chris Lattnera1be5662002-05-02 17:06:02 +00009003
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009004/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9005/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009006static bool DeadPHICycle(PHINode *PN,
9007 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009008 if (PN->use_empty()) return true;
9009 if (!PN->hasOneUse()) return false;
9010
9011 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009012 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009013 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009014
9015 // Don't scan crazily complex things.
9016 if (PotentiallyDeadPHIs.size() == 16)
9017 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009018
9019 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9020 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009021
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009022 return false;
9023}
9024
Chris Lattnercf5008a2007-11-06 21:52:06 +00009025/// PHIsEqualValue - Return true if this phi node is always equal to
9026/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9027/// z = some value; x = phi (y, z); y = phi (x, z)
9028static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9029 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9030 // See if we already saw this PHI node.
9031 if (!ValueEqualPHIs.insert(PN))
9032 return true;
9033
9034 // Don't scan crazily complex things.
9035 if (ValueEqualPHIs.size() == 16)
9036 return false;
9037
9038 // Scan the operands to see if they are either phi nodes or are equal to
9039 // the value.
9040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9041 Value *Op = PN->getIncomingValue(i);
9042 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9043 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9044 return false;
9045 } else if (Op != NonPhiInVal)
9046 return false;
9047 }
9048
9049 return true;
9050}
9051
9052
Chris Lattner473945d2002-05-06 18:06:38 +00009053// PHINode simplification
9054//
Chris Lattner7e708292002-06-25 16:13:24 +00009055Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009056 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009057 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009058
Owen Anderson7e057142006-07-10 22:03:18 +00009059 if (Value *V = PN.hasConstantValue())
9060 return ReplaceInstUsesWith(PN, V);
9061
Owen Anderson7e057142006-07-10 22:03:18 +00009062 // If all PHI operands are the same operation, pull them through the PHI,
9063 // reducing code size.
9064 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9065 PN.getIncomingValue(0)->hasOneUse())
9066 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9067 return Result;
9068
9069 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9070 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9071 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009072 if (PN.hasOneUse()) {
9073 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9074 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009075 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009076 PotentiallyDeadPHIs.insert(&PN);
9077 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9078 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9079 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009080
9081 // If this phi has a single use, and if that use just computes a value for
9082 // the next iteration of a loop, delete the phi. This occurs with unused
9083 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9084 // common case here is good because the only other things that catch this
9085 // are induction variable analysis (sometimes) and ADCE, which is only run
9086 // late.
9087 if (PHIUser->hasOneUse() &&
9088 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9089 PHIUser->use_back() == &PN) {
9090 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9091 }
9092 }
Owen Anderson7e057142006-07-10 22:03:18 +00009093
Chris Lattnercf5008a2007-11-06 21:52:06 +00009094 // We sometimes end up with phi cycles that non-obviously end up being the
9095 // same value, for example:
9096 // z = some value; x = phi (y, z); y = phi (x, z)
9097 // where the phi nodes don't necessarily need to be in the same block. Do a
9098 // quick check to see if the PHI node only contains a single non-phi value, if
9099 // so, scan to see if the phi cycle is actually equal to that value.
9100 {
9101 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9102 // Scan for the first non-phi operand.
9103 while (InValNo != NumOperandVals &&
9104 isa<PHINode>(PN.getIncomingValue(InValNo)))
9105 ++InValNo;
9106
9107 if (InValNo != NumOperandVals) {
9108 Value *NonPhiInVal = PN.getOperand(InValNo);
9109
9110 // Scan the rest of the operands to see if there are any conflicts, if so
9111 // there is no need to recursively scan other phis.
9112 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9113 Value *OpVal = PN.getIncomingValue(InValNo);
9114 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9115 break;
9116 }
9117
9118 // If we scanned over all operands, then we have one unique value plus
9119 // phi values. Scan PHI nodes to see if they all merge in each other or
9120 // the value.
9121 if (InValNo == NumOperandVals) {
9122 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9123 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9124 return ReplaceInstUsesWith(PN, NonPhiInVal);
9125 }
9126 }
9127 }
Chris Lattner60921c92003-12-19 05:58:40 +00009128 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009129}
9130
Reid Spencer17212df2006-12-12 09:18:51 +00009131static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9132 Instruction *InsertPoint,
9133 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009134 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9135 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009136 // We must cast correctly to the pointer type. Ensure that we
9137 // sign extend the integer value if it is smaller as this is
9138 // used for address computation.
9139 Instruction::CastOps opcode =
9140 (VTySize < PtrSize ? Instruction::SExt :
9141 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9142 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009143}
9144
Chris Lattnera1be5662002-05-02 17:06:02 +00009145
Chris Lattner7e708292002-06-25 16:13:24 +00009146Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009147 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009148 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009149 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009150 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009151 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009152
Chris Lattnere87597f2004-10-16 18:11:37 +00009153 if (isa<UndefValue>(GEP.getOperand(0)))
9154 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9155
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009156 bool HasZeroPointerIndex = false;
9157 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9158 HasZeroPointerIndex = C->isNullValue();
9159
9160 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009161 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009162
Chris Lattner28977af2004-04-05 01:30:19 +00009163 // Eliminate unneeded casts for indices.
9164 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009165
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009166 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009167 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009168 if (isa<SequentialType>(*GTI)) {
9169 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009170 if (CI->getOpcode() == Instruction::ZExt ||
9171 CI->getOpcode() == Instruction::SExt) {
9172 const Type *SrcTy = CI->getOperand(0)->getType();
9173 // We can eliminate a cast from i32 to i64 iff the target
9174 // is a 32-bit pointer target.
9175 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9176 MadeChange = true;
9177 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009178 }
9179 }
9180 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009181 // If we are using a wider index than needed for this platform, shrink it
9182 // to what we need. If the incoming value needs a cast instruction,
9183 // insert it. This explicit cast can make subsequent optimizations more
9184 // obvious.
9185 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009186 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009187 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009188 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009189 MadeChange = true;
9190 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009191 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9192 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009193 GEP.setOperand(i, Op);
9194 MadeChange = true;
9195 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009196 }
Chris Lattner28977af2004-04-05 01:30:19 +00009197 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009198 }
Chris Lattner28977af2004-04-05 01:30:19 +00009199 if (MadeChange) return &GEP;
9200
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009201 // If this GEP instruction doesn't move the pointer, and if the input operand
9202 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9203 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009204 if (GEP.hasAllZeroIndices()) {
9205 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9206 // If the bitcast is of an allocation, and the allocation will be
9207 // converted to match the type of the cast, don't touch this.
9208 if (isa<AllocationInst>(BCI->getOperand(0))) {
9209 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009210 if (Instruction *I = visitBitCast(*BCI)) {
9211 if (I != BCI) {
9212 I->takeName(BCI);
9213 BCI->getParent()->getInstList().insert(BCI, I);
9214 ReplaceInstUsesWith(*BCI, I);
9215 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009216 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009217 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009218 }
9219 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9220 }
9221 }
9222
Chris Lattner90ac28c2002-08-02 19:29:35 +00009223 // Combine Indices - If the source pointer to this getelementptr instruction
9224 // is a getelementptr instruction, combine the indices of the two
9225 // getelementptr instructions into a single instruction.
9226 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009227 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009228 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009229 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009230
9231 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009232 // Note that if our source is a gep chain itself that we wait for that
9233 // chain to be resolved before we perform this transformation. This
9234 // avoids us creating a TON of code in some cases.
9235 //
9236 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9237 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9238 return 0; // Wait until our source is folded to completion.
9239
Chris Lattner72588fc2007-02-15 22:48:32 +00009240 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009241
9242 // Find out whether the last index in the source GEP is a sequential idx.
9243 bool EndsWithSequential = false;
9244 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9245 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009246 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009247
Chris Lattner90ac28c2002-08-02 19:29:35 +00009248 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009249 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009250 // Replace: gep (gep %P, long B), long A, ...
9251 // With: T = long A+B; gep %P, T, ...
9252 //
Chris Lattner620ce142004-05-07 22:09:22 +00009253 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009254 if (SO1 == Constant::getNullValue(SO1->getType())) {
9255 Sum = GO1;
9256 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9257 Sum = SO1;
9258 } else {
9259 // If they aren't the same type, convert both to an integer of the
9260 // target's pointer size.
9261 if (SO1->getType() != GO1->getType()) {
9262 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009263 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009264 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009265 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009266 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009267 unsigned PS = TD->getPointerSizeInBits();
9268 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009269 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009270 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009271
Duncan Sands514ab342007-11-01 20:53:16 +00009272 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009273 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009274 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009275 } else {
9276 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009277 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9278 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009279 }
9280 }
9281 }
Chris Lattner620ce142004-05-07 22:09:22 +00009282 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9283 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9284 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009285 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9286 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009287 }
Chris Lattner28977af2004-04-05 01:30:19 +00009288 }
Chris Lattner620ce142004-05-07 22:09:22 +00009289
9290 // Recycle the GEP we already have if possible.
9291 if (SrcGEPOperands.size() == 2) {
9292 GEP.setOperand(0, SrcGEPOperands[0]);
9293 GEP.setOperand(1, Sum);
9294 return &GEP;
9295 } else {
9296 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9297 SrcGEPOperands.end()-1);
9298 Indices.push_back(Sum);
9299 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9300 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009301 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009302 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009303 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009304 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009305 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9306 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009307 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9308 }
9309
9310 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009311 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9312 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009313
Chris Lattner620ce142004-05-07 22:09:22 +00009314 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009315 // GEP of global variable. If all of the indices for this GEP are
9316 // constants, we can promote this to a constexpr instead of an instruction.
9317
9318 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009319 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009320 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9321 for (; I != E && isa<Constant>(*I); ++I)
9322 Indices.push_back(cast<Constant>(*I));
9323
9324 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009325 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9326 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009327
9328 // Replace all uses of the GEP with the new constexpr...
9329 return ReplaceInstUsesWith(GEP, CE);
9330 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009331 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009332 if (!isa<PointerType>(X->getType())) {
9333 // Not interesting. Source pointer must be a cast from pointer.
9334 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009335 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9336 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009337 //
9338 // This occurs when the program declares an array extern like "int X[];"
9339 //
9340 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9341 const PointerType *XTy = cast<PointerType>(X->getType());
9342 if (const ArrayType *XATy =
9343 dyn_cast<ArrayType>(XTy->getElementType()))
9344 if (const ArrayType *CATy =
9345 dyn_cast<ArrayType>(CPTy->getElementType()))
9346 if (CATy->getElementType() == XATy->getElementType()) {
9347 // At this point, we know that the cast source type is a pointer
9348 // to an array of the same type as the destination pointer
9349 // array. Because the array type is never stepped over (there
9350 // is a leading zero) we can fold the cast into this GEP.
9351 GEP.setOperand(0, X);
9352 return &GEP;
9353 }
9354 } else if (GEP.getNumOperands() == 2) {
9355 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009356 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9357 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009358 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9359 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9360 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009361 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9362 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009363 Value *Idx[2];
9364 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9365 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009366 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009367 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009368 // V and GEP are both pointer types --> BitCast
9369 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009370 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009371
9372 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009373 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009374 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009375 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009376
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009377 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009378 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009379 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009380
9381 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9382 // allow either a mul, shift, or constant here.
9383 Value *NewIdx = 0;
9384 ConstantInt *Scale = 0;
9385 if (ArrayEltSize == 1) {
9386 NewIdx = GEP.getOperand(1);
9387 Scale = ConstantInt::get(NewIdx->getType(), 1);
9388 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009389 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009390 Scale = CI;
9391 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9392 if (Inst->getOpcode() == Instruction::Shl &&
9393 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009394 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9395 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9396 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009397 NewIdx = Inst->getOperand(0);
9398 } else if (Inst->getOpcode() == Instruction::Mul &&
9399 isa<ConstantInt>(Inst->getOperand(1))) {
9400 Scale = cast<ConstantInt>(Inst->getOperand(1));
9401 NewIdx = Inst->getOperand(0);
9402 }
9403 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009404
Chris Lattner7835cdd2005-09-13 18:36:04 +00009405 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009406 // out, perform the transformation. Note, we don't know whether Scale is
9407 // signed or not. We'll use unsigned version of division/modulo
9408 // operation after making sure Scale doesn't have the sign bit set.
9409 if (Scale && Scale->getSExtValue() >= 0LL &&
9410 Scale->getZExtValue() % ArrayEltSize == 0) {
9411 Scale = ConstantInt::get(Scale->getType(),
9412 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009413 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009414 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009415 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009416 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9417 NewIdx = InsertNewInstBefore(Sc, GEP);
9418 }
9419
9420 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009421 Value *Idx[2];
9422 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9423 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009424 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009425 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009426 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9427 // The NewGEP must be pointer typed, so must the old one -> BitCast
9428 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009429 }
9430 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009431 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009432 }
9433
Chris Lattner8a2a3112001-12-14 16:52:21 +00009434 return 0;
9435}
9436
Chris Lattner0864acf2002-11-04 16:18:53 +00009437Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9438 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009439 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009440 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9441 const Type *NewTy =
9442 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009443 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009444
9445 // Create and insert the replacement instruction...
9446 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009447 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009448 else {
9449 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009450 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009451 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009452
9453 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009454
Chris Lattner0864acf2002-11-04 16:18:53 +00009455 // Scan to the end of the allocation instructions, to skip over a block of
9456 // allocas if possible...
9457 //
9458 BasicBlock::iterator It = New;
9459 while (isa<AllocationInst>(*It)) ++It;
9460
9461 // Now that I is pointing to the first non-allocation-inst in the block,
9462 // insert our getelementptr instruction...
9463 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009464 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009465 Value *Idx[2];
9466 Idx[0] = NullIdx;
9467 Idx[1] = NullIdx;
9468 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009469 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009470
9471 // Now make everything use the getelementptr instead of the original
9472 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009473 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009474 } else if (isa<UndefValue>(AI.getArraySize())) {
9475 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009476 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009477 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009478
9479 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9480 // Note that we only do this for alloca's, because malloc should allocate and
9481 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009482 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009483 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009484 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9485
Chris Lattner0864acf2002-11-04 16:18:53 +00009486 return 0;
9487}
9488
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009489Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9490 Value *Op = FI.getOperand(0);
9491
Chris Lattner17be6352004-10-18 02:59:09 +00009492 // free undef -> unreachable.
9493 if (isa<UndefValue>(Op)) {
9494 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009495 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009496 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009497 return EraseInstFromFunction(FI);
9498 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009499
Chris Lattner6160e852004-02-28 04:57:37 +00009500 // If we have 'free null' delete the instruction. This can happen in stl code
9501 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009502 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009503 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009504
9505 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9506 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9507 FI.setOperand(0, CI->getOperand(0));
9508 return &FI;
9509 }
9510
9511 // Change free (gep X, 0,0,0,0) into free(X)
9512 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9513 if (GEPI->hasAllZeroIndices()) {
9514 AddToWorkList(GEPI);
9515 FI.setOperand(0, GEPI->getOperand(0));
9516 return &FI;
9517 }
9518 }
9519
9520 // Change free(malloc) into nothing, if the malloc has a single use.
9521 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9522 if (MI->hasOneUse()) {
9523 EraseInstFromFunction(FI);
9524 return EraseInstFromFunction(*MI);
9525 }
Chris Lattner6160e852004-02-28 04:57:37 +00009526
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009527 return 0;
9528}
9529
9530
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009531/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009532static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009533 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009534 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009535 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009536
Devang Patel99db6ad2007-10-18 19:52:32 +00009537 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9538 // Instead of loading constant c string, use corresponding integer value
9539 // directly if string length is small enough.
9540 const std::string &Str = CE->getOperand(0)->getStringValue();
9541 if (!Str.empty()) {
9542 unsigned len = Str.length();
9543 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9544 unsigned numBits = Ty->getPrimitiveSizeInBits();
9545 // Replace LI with immediate integer store.
9546 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009547 APInt StrVal(numBits, 0);
9548 APInt SingleChar(numBits, 0);
9549 if (TD->isLittleEndian()) {
9550 for (signed i = len-1; i >= 0; i--) {
9551 SingleChar = (uint64_t) Str[i];
9552 StrVal = (StrVal << 8) | SingleChar;
9553 }
9554 } else {
9555 for (unsigned i = 0; i < len; i++) {
9556 SingleChar = (uint64_t) Str[i];
9557 StrVal = (StrVal << 8) | SingleChar;
9558 }
9559 // Append NULL at the end.
9560 SingleChar = 0;
9561 StrVal = (StrVal << 8) | SingleChar;
9562 }
9563 Value *NL = ConstantInt::get(StrVal);
9564 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009565 }
9566 }
9567 }
9568
Chris Lattnerb89e0712004-07-13 01:49:43 +00009569 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009570 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009571 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009572
Reid Spencer42230162007-01-22 05:51:25 +00009573 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009574 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009575 // If the source is an array, the code below will not succeed. Check to
9576 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9577 // constants.
9578 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9579 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9580 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009581 Value *Idxs[2];
9582 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9583 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009584 SrcTy = cast<PointerType>(CastOp->getType());
9585 SrcPTy = SrcTy->getElementType();
9586 }
9587
Reid Spencer42230162007-01-22 05:51:25 +00009588 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009589 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009590 // Do not allow turning this into a load of an integer, which is then
9591 // casted to a pointer, this pessimizes pointer analysis a lot.
9592 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009593 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9594 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009595
Chris Lattnerf9527852005-01-31 04:50:46 +00009596 // Okay, we are casting from one integer or pointer type to another of
9597 // the same size. Instead of casting the pointer before the load, cast
9598 // the result of the loaded value.
9599 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9600 CI->getName(),
9601 LI.isVolatile()),LI);
9602 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009603 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009604 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009605 }
9606 }
9607 return 0;
9608}
9609
Chris Lattnerc10aced2004-09-19 18:43:46 +00009610/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009611/// from this value cannot trap. If it is not obviously safe to load from the
9612/// specified pointer, we do a quick local scan of the basic block containing
9613/// ScanFrom, to determine if the address is already accessed.
9614static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009615 // If it is an alloca it is always safe to load from.
9616 if (isa<AllocaInst>(V)) return true;
9617
Duncan Sands46318cd2007-09-19 10:25:38 +00009618 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009619 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009620 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009621 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009622
9623 // Otherwise, be a little bit agressive by scanning the local block where we
9624 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009625 // from/to. If so, the previous load or store would have already trapped,
9626 // so there is no harm doing an extra load (also, CSE will later eliminate
9627 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009628 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9629
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009630 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009631 --BBI;
9632
9633 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9634 if (LI->getOperand(0) == V) return true;
9635 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9636 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009637
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009638 }
Chris Lattner8a375202004-09-19 19:18:10 +00009639 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009640}
9641
Chris Lattner8d2e8882007-08-11 18:48:48 +00009642/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9643/// until we find the underlying object a pointer is referring to or something
9644/// we don't understand. Note that the returned pointer may be offset from the
9645/// input, because we ignore GEP indices.
9646static Value *GetUnderlyingObject(Value *Ptr) {
9647 while (1) {
9648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9649 if (CE->getOpcode() == Instruction::BitCast ||
9650 CE->getOpcode() == Instruction::GetElementPtr)
9651 Ptr = CE->getOperand(0);
9652 else
9653 return Ptr;
9654 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9655 Ptr = BCI->getOperand(0);
9656 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9657 Ptr = GEP->getOperand(0);
9658 } else {
9659 return Ptr;
9660 }
9661 }
9662}
9663
Chris Lattner833b8a42003-06-26 05:06:25 +00009664Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9665 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009666
Dan Gohman9941f742007-07-20 16:34:21 +00009667 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009668 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009669 if (KnownAlign > LI.getAlignment())
9670 LI.setAlignment(KnownAlign);
9671
Chris Lattner37366c12005-05-01 04:24:53 +00009672 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009673 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009674 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009675 return Res;
9676
9677 // None of the following transforms are legal for volatile loads.
9678 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009679
Chris Lattner62f254d2005-09-12 22:00:15 +00009680 if (&LI.getParent()->front() != &LI) {
9681 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009682 // If the instruction immediately before this is a store to the same
9683 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009684 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9685 if (SI->getOperand(1) == LI.getOperand(0))
9686 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009687 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9688 if (LIB->getOperand(0) == LI.getOperand(0))
9689 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009690 }
Chris Lattner37366c12005-05-01 04:24:53 +00009691
Christopher Lambb15147e2007-12-29 07:56:53 +00009692 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9693 const Value *GEPI0 = GEPI->getOperand(0);
9694 // TODO: Consider a target hook for valid address spaces for this xform.
9695 if (isa<ConstantPointerNull>(GEPI0) &&
9696 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009697 // Insert a new store to null instruction before the load to indicate
9698 // that this code is not reachable. We do this instead of inserting
9699 // an unreachable instruction directly because we cannot modify the
9700 // CFG.
9701 new StoreInst(UndefValue::get(LI.getType()),
9702 Constant::getNullValue(Op->getType()), &LI);
9703 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9704 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009705 }
Chris Lattner37366c12005-05-01 04:24:53 +00009706
Chris Lattnere87597f2004-10-16 18:11:37 +00009707 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009708 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009709 // TODO: Consider a target hook for valid address spaces for this xform.
9710 if (isa<UndefValue>(C) || (C->isNullValue() &&
9711 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009712 // Insert a new store to null instruction before the load to indicate that
9713 // this code is not reachable. We do this instead of inserting an
9714 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009715 new StoreInst(UndefValue::get(LI.getType()),
9716 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009717 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009718 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009719
Chris Lattnere87597f2004-10-16 18:11:37 +00009720 // Instcombine load (constant global) into the value loaded.
9721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009722 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009723 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009724
Chris Lattnere87597f2004-10-16 18:11:37 +00009725 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009726 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009727 if (CE->getOpcode() == Instruction::GetElementPtr) {
9728 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009729 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009730 if (Constant *V =
9731 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009732 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009733 if (CE->getOperand(0)->isNullValue()) {
9734 // Insert a new store to null instruction before the load to indicate
9735 // that this code is not reachable. We do this instead of inserting
9736 // an unreachable instruction directly because we cannot modify the
9737 // CFG.
9738 new StoreInst(UndefValue::get(LI.getType()),
9739 Constant::getNullValue(Op->getType()), &LI);
9740 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9741 }
9742
Reid Spencer3da59db2006-11-27 01:05:10 +00009743 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009744 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009745 return Res;
9746 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009747 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009748 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009749
9750 // If this load comes from anywhere in a constant global, and if the global
9751 // is all undef or zero, we know what it loads.
9752 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9753 if (GV->isConstant() && GV->hasInitializer()) {
9754 if (GV->getInitializer()->isNullValue())
9755 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9756 else if (isa<UndefValue>(GV->getInitializer()))
9757 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9758 }
9759 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009760
Chris Lattner37366c12005-05-01 04:24:53 +00009761 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009762 // Change select and PHI nodes to select values instead of addresses: this
9763 // helps alias analysis out a lot, allows many others simplifications, and
9764 // exposes redundancy in the code.
9765 //
9766 // Note that we cannot do the transformation unless we know that the
9767 // introduced loads cannot trap! Something like this is valid as long as
9768 // the condition is always false: load (select bool %C, int* null, int* %G),
9769 // but it would not be valid if we transformed it to load from null
9770 // unconditionally.
9771 //
9772 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9773 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009774 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9775 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009776 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009777 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009778 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009779 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009780 return new SelectInst(SI->getCondition(), V1, V2);
9781 }
9782
Chris Lattner684fe212004-09-23 15:46:00 +00009783 // load (select (cond, null, P)) -> load P
9784 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9785 if (C->isNullValue()) {
9786 LI.setOperand(0, SI->getOperand(2));
9787 return &LI;
9788 }
9789
9790 // load (select (cond, P, null)) -> load P
9791 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9792 if (C->isNullValue()) {
9793 LI.setOperand(0, SI->getOperand(1));
9794 return &LI;
9795 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009796 }
9797 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009798 return 0;
9799}
9800
Reid Spencer55af2b52007-01-19 21:20:31 +00009801/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009802/// when possible.
9803static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9804 User *CI = cast<User>(SI.getOperand(1));
9805 Value *CastOp = CI->getOperand(0);
9806
9807 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9808 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9809 const Type *SrcPTy = SrcTy->getElementType();
9810
Reid Spencer42230162007-01-22 05:51:25 +00009811 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009812 // If the source is an array, the code below will not succeed. Check to
9813 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9814 // constants.
9815 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9816 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9817 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009818 Value* Idxs[2];
9819 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9820 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009821 SrcTy = cast<PointerType>(CastOp->getType());
9822 SrcPTy = SrcTy->getElementType();
9823 }
9824
Reid Spencer67f827c2007-01-20 23:35:48 +00009825 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9826 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9827 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009828
9829 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009830 // the same size. Instead of casting the pointer before
9831 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009832 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009833 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009834 Instruction::CastOps opcode = Instruction::BitCast;
9835 const Type* CastSrcTy = SIOp0->getType();
9836 const Type* CastDstTy = SrcPTy;
9837 if (isa<PointerType>(CastDstTy)) {
9838 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009839 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009840 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009841 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009842 opcode = Instruction::PtrToInt;
9843 }
9844 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009845 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009846 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009847 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009848 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9849 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009850 return new StoreInst(NewCast, CastOp);
9851 }
9852 }
9853 }
9854 return 0;
9855}
9856
Chris Lattner2f503e62005-01-31 05:36:43 +00009857Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9858 Value *Val = SI.getOperand(0);
9859 Value *Ptr = SI.getOperand(1);
9860
9861 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009862 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009863 ++NumCombined;
9864 return 0;
9865 }
Chris Lattner836692d2007-01-15 06:51:56 +00009866
9867 // If the RHS is an alloca with a single use, zapify the store, making the
9868 // alloca dead.
9869 if (Ptr->hasOneUse()) {
9870 if (isa<AllocaInst>(Ptr)) {
9871 EraseInstFromFunction(SI);
9872 ++NumCombined;
9873 return 0;
9874 }
9875
9876 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9877 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9878 GEP->getOperand(0)->hasOneUse()) {
9879 EraseInstFromFunction(SI);
9880 ++NumCombined;
9881 return 0;
9882 }
9883 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009884
Dan Gohman9941f742007-07-20 16:34:21 +00009885 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009886 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009887 if (KnownAlign > SI.getAlignment())
9888 SI.setAlignment(KnownAlign);
9889
Chris Lattner9ca96412006-02-08 03:25:32 +00009890 // Do really simple DSE, to catch cases where there are several consequtive
9891 // stores to the same location, separated by a few arithmetic operations. This
9892 // situation often occurs with bitfield accesses.
9893 BasicBlock::iterator BBI = &SI;
9894 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9895 --ScanInsts) {
9896 --BBI;
9897
9898 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9899 // Prev store isn't volatile, and stores to the same location?
9900 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9901 ++NumDeadStore;
9902 ++BBI;
9903 EraseInstFromFunction(*PrevSI);
9904 continue;
9905 }
9906 break;
9907 }
9908
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009909 // If this is a load, we have to stop. However, if the loaded value is from
9910 // the pointer we're loading and is producing the pointer we're storing,
9911 // then *this* store is dead (X = load P; store X -> P).
9912 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009913 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009914 EraseInstFromFunction(SI);
9915 ++NumCombined;
9916 return 0;
9917 }
9918 // Otherwise, this is a load from some other location. Stores before it
9919 // may not be dead.
9920 break;
9921 }
9922
Chris Lattner9ca96412006-02-08 03:25:32 +00009923 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009924 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009925 break;
9926 }
9927
9928
9929 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009930
9931 // store X, null -> turns into 'unreachable' in SimplifyCFG
9932 if (isa<ConstantPointerNull>(Ptr)) {
9933 if (!isa<UndefValue>(Val)) {
9934 SI.setOperand(0, UndefValue::get(Val->getType()));
9935 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009936 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009937 ++NumCombined;
9938 }
9939 return 0; // Do not modify these!
9940 }
9941
9942 // store undef, Ptr -> noop
9943 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009944 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009945 ++NumCombined;
9946 return 0;
9947 }
9948
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009949 // If the pointer destination is a cast, see if we can fold the cast into the
9950 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009951 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009952 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9953 return Res;
9954 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009955 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009956 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9957 return Res;
9958
Chris Lattner408902b2005-09-12 23:23:25 +00009959
9960 // If this store is the last instruction in the basic block, and if the block
9961 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009962 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009963 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009964 if (BI->isUnconditional())
9965 if (SimplifyStoreAtEndOfBlock(SI))
9966 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009967
Chris Lattner2f503e62005-01-31 05:36:43 +00009968 return 0;
9969}
9970
Chris Lattner3284d1f2007-04-15 00:07:55 +00009971/// SimplifyStoreAtEndOfBlock - Turn things like:
9972/// if () { *P = v1; } else { *P = v2 }
9973/// into a phi node with a store in the successor.
9974///
Chris Lattner31755a02007-04-15 01:02:18 +00009975/// Simplify things like:
9976/// *P = v1; if () { *P = v2; }
9977/// into a phi node with a store in the successor.
9978///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009979bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9980 BasicBlock *StoreBB = SI.getParent();
9981
9982 // Check to see if the successor block has exactly two incoming edges. If
9983 // so, see if the other predecessor contains a store to the same location.
9984 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009985 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009986
9987 // Determine whether Dest has exactly two predecessors and, if so, compute
9988 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009989 pred_iterator PI = pred_begin(DestBB);
9990 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009991 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009992 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009993 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009994 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009995 return false;
9996
9997 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009998 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009999 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010000 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010001 }
Chris Lattner31755a02007-04-15 01:02:18 +000010002 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010003 return false;
10004
10005
Chris Lattner31755a02007-04-15 01:02:18 +000010006 // Verify that the other block ends in a branch and is not otherwise empty.
10007 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010008 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010009 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010010 return false;
10011
Chris Lattner31755a02007-04-15 01:02:18 +000010012 // If the other block ends in an unconditional branch, check for the 'if then
10013 // else' case. there is an instruction before the branch.
10014 StoreInst *OtherStore = 0;
10015 if (OtherBr->isUnconditional()) {
10016 // If this isn't a store, or isn't a store to the same location, bail out.
10017 --BBI;
10018 OtherStore = dyn_cast<StoreInst>(BBI);
10019 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10020 return false;
10021 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010022 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010023 // destinations is StoreBB, then we have the if/then case.
10024 if (OtherBr->getSuccessor(0) != StoreBB &&
10025 OtherBr->getSuccessor(1) != StoreBB)
10026 return false;
10027
10028 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010029 // if/then triangle. See if there is a store to the same ptr as SI that
10030 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010031 for (;; --BBI) {
10032 // Check to see if we find the matching store.
10033 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10034 if (OtherStore->getOperand(1) != SI.getOperand(1))
10035 return false;
10036 break;
10037 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010038 // If we find something that may be using the stored value, or if we run
10039 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010040 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10041 BBI == OtherBB->begin())
10042 return false;
10043 }
10044
10045 // In order to eliminate the store in OtherBr, we have to
10046 // make sure nothing reads the stored value in StoreBB.
10047 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10048 // FIXME: This should really be AA driven.
10049 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10050 return false;
10051 }
10052 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010053
Chris Lattner31755a02007-04-15 01:02:18 +000010054 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010055 Value *MergedVal = OtherStore->getOperand(0);
10056 if (MergedVal != SI.getOperand(0)) {
10057 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10058 PN->reserveOperandSpace(2);
10059 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010060 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10061 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010062 }
10063
10064 // Advance to a place where it is safe to insert the new store and
10065 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010066 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010067 while (isa<PHINode>(BBI)) ++BBI;
10068 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10069 OtherStore->isVolatile()), *BBI);
10070
10071 // Nuke the old stores.
10072 EraseInstFromFunction(SI);
10073 EraseInstFromFunction(*OtherStore);
10074 ++NumCombined;
10075 return true;
10076}
10077
Chris Lattner2f503e62005-01-31 05:36:43 +000010078
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010079Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10080 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010081 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010082 BasicBlock *TrueDest;
10083 BasicBlock *FalseDest;
10084 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10085 !isa<Constant>(X)) {
10086 // Swap Destinations and condition...
10087 BI.setCondition(X);
10088 BI.setSuccessor(0, FalseDest);
10089 BI.setSuccessor(1, TrueDest);
10090 return &BI;
10091 }
10092
Reid Spencere4d87aa2006-12-23 06:05:41 +000010093 // Cannonicalize fcmp_one -> fcmp_oeq
10094 FCmpInst::Predicate FPred; Value *Y;
10095 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10096 TrueDest, FalseDest)))
10097 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10098 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10099 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010100 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010101 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10102 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010103 // Swap Destinations and condition...
10104 BI.setCondition(NewSCC);
10105 BI.setSuccessor(0, FalseDest);
10106 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010107 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010108 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010109 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010110 return &BI;
10111 }
10112
10113 // Cannonicalize icmp_ne -> icmp_eq
10114 ICmpInst::Predicate IPred;
10115 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10116 TrueDest, FalseDest)))
10117 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10118 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10119 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10120 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010121 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010122 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10123 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010124 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010125 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010126 BI.setSuccessor(0, FalseDest);
10127 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010128 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010129 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010130 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010131 return &BI;
10132 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010133
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010134 return 0;
10135}
Chris Lattner0864acf2002-11-04 16:18:53 +000010136
Chris Lattner46238a62004-07-03 00:26:11 +000010137Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10138 Value *Cond = SI.getCondition();
10139 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10140 if (I->getOpcode() == Instruction::Add)
10141 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10142 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10143 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010144 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010145 AddRHS));
10146 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010147 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010148 return &SI;
10149 }
10150 }
10151 return 0;
10152}
10153
Chris Lattner220b0cf2006-03-05 00:22:33 +000010154/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10155/// is to leave as a vector operation.
10156static bool CheapToScalarize(Value *V, bool isConstant) {
10157 if (isa<ConstantAggregateZero>(V))
10158 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010159 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010160 if (isConstant) return true;
10161 // If all elts are the same, we can extract.
10162 Constant *Op0 = C->getOperand(0);
10163 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10164 if (C->getOperand(i) != Op0)
10165 return false;
10166 return true;
10167 }
10168 Instruction *I = dyn_cast<Instruction>(V);
10169 if (!I) return false;
10170
10171 // Insert element gets simplified to the inserted element or is deleted if
10172 // this is constant idx extract element and its a constant idx insertelt.
10173 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10174 isa<ConstantInt>(I->getOperand(2)))
10175 return true;
10176 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10177 return true;
10178 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10179 if (BO->hasOneUse() &&
10180 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10181 CheapToScalarize(BO->getOperand(1), isConstant)))
10182 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010183 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10184 if (CI->hasOneUse() &&
10185 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10186 CheapToScalarize(CI->getOperand(1), isConstant)))
10187 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010188
10189 return false;
10190}
10191
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010192/// Read and decode a shufflevector mask.
10193///
10194/// It turns undef elements into values that are larger than the number of
10195/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010196static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10197 unsigned NElts = SVI->getType()->getNumElements();
10198 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10199 return std::vector<unsigned>(NElts, 0);
10200 if (isa<UndefValue>(SVI->getOperand(2)))
10201 return std::vector<unsigned>(NElts, 2*NElts);
10202
10203 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010204 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010205 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10206 if (isa<UndefValue>(CP->getOperand(i)))
10207 Result.push_back(NElts*2); // undef -> 8
10208 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010209 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010210 return Result;
10211}
10212
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010213/// FindScalarElement - Given a vector and an element number, see if the scalar
10214/// value is already around as a register, for example if it were inserted then
10215/// extracted from the vector.
10216static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010217 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10218 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010219 unsigned Width = PTy->getNumElements();
10220 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010221 return UndefValue::get(PTy->getElementType());
10222
10223 if (isa<UndefValue>(V))
10224 return UndefValue::get(PTy->getElementType());
10225 else if (isa<ConstantAggregateZero>(V))
10226 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010227 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010228 return CP->getOperand(EltNo);
10229 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10230 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010231 if (!isa<ConstantInt>(III->getOperand(2)))
10232 return 0;
10233 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010234
10235 // If this is an insert to the element we are looking for, return the
10236 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010237 if (EltNo == IIElt)
10238 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010239
10240 // Otherwise, the insertelement doesn't modify the value, recurse on its
10241 // vector input.
10242 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010243 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010244 unsigned InEl = getShuffleMask(SVI)[EltNo];
10245 if (InEl < Width)
10246 return FindScalarElement(SVI->getOperand(0), InEl);
10247 else if (InEl < Width*2)
10248 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10249 else
10250 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010251 }
10252
10253 // Otherwise, we don't know.
10254 return 0;
10255}
10256
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010257Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010258
Dan Gohman07a96762007-07-16 14:29:03 +000010259 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010260 if (isa<UndefValue>(EI.getOperand(0)))
10261 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10262
Dan Gohman07a96762007-07-16 14:29:03 +000010263 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010264 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10265 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10266
Reid Spencer9d6565a2007-02-15 02:26:10 +000010267 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010268 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010269 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010270 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010271 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010272 if (C->getOperand(i) != op0) {
10273 op0 = 0;
10274 break;
10275 }
10276 if (op0)
10277 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010278 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010279
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010280 // If extracting a specified index from the vector, see if we can recursively
10281 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010282 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010283 unsigned IndexVal = IdxC->getZExtValue();
10284 unsigned VectorWidth =
10285 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10286
10287 // If this is extracting an invalid index, turn this into undef, to avoid
10288 // crashing the code below.
10289 if (IndexVal >= VectorWidth)
10290 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10291
Chris Lattner867b99f2006-10-05 06:55:50 +000010292 // This instruction only demands the single element from the input vector.
10293 // If the input vector has a single use, simplify it based on this use
10294 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010295 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010296 uint64_t UndefElts;
10297 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010298 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010299 UndefElts)) {
10300 EI.setOperand(0, V);
10301 return &EI;
10302 }
10303 }
10304
Reid Spencerb83eb642006-10-20 07:07:24 +000010305 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010306 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010307
10308 // If the this extractelement is directly using a bitcast from a vector of
10309 // the same number of elements, see if we can find the source element from
10310 // it. In this case, we will end up needing to bitcast the scalars.
10311 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10312 if (const VectorType *VT =
10313 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10314 if (VT->getNumElements() == VectorWidth)
10315 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10316 return new BitCastInst(Elt, EI.getType());
10317 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010318 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010319
Chris Lattner73fa49d2006-05-25 22:53:38 +000010320 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010321 if (I->hasOneUse()) {
10322 // Push extractelement into predecessor operation if legal and
10323 // profitable to do so
10324 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010325 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10326 if (CheapToScalarize(BO, isConstantElt)) {
10327 ExtractElementInst *newEI0 =
10328 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10329 EI.getName()+".lhs");
10330 ExtractElementInst *newEI1 =
10331 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10332 EI.getName()+".rhs");
10333 InsertNewInstBefore(newEI0, EI);
10334 InsertNewInstBefore(newEI1, EI);
10335 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10336 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010337 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010338 unsigned AS =
10339 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010340 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10341 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010342 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010343 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010344 InsertNewInstBefore(GEP, EI);
10345 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010346 }
10347 }
10348 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10349 // Extracting the inserted element?
10350 if (IE->getOperand(2) == EI.getOperand(1))
10351 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10352 // If the inserted and extracted elements are constants, they must not
10353 // be the same value, extract from the pre-inserted value instead.
10354 if (isa<Constant>(IE->getOperand(2)) &&
10355 isa<Constant>(EI.getOperand(1))) {
10356 AddUsesToWorkList(EI);
10357 EI.setOperand(0, IE->getOperand(0));
10358 return &EI;
10359 }
10360 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10361 // If this is extracting an element from a shufflevector, figure out where
10362 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010363 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10364 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010365 Value *Src;
10366 if (SrcIdx < SVI->getType()->getNumElements())
10367 Src = SVI->getOperand(0);
10368 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10369 SrcIdx -= SVI->getType()->getNumElements();
10370 Src = SVI->getOperand(1);
10371 } else {
10372 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010373 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010374 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010375 }
10376 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010377 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010378 return 0;
10379}
10380
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010381/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10382/// elements from either LHS or RHS, return the shuffle mask and true.
10383/// Otherwise, return false.
10384static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10385 std::vector<Constant*> &Mask) {
10386 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10387 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010388 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010389
10390 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010391 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010392 return true;
10393 } else if (V == LHS) {
10394 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010395 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010396 return true;
10397 } else if (V == RHS) {
10398 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010399 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010400 return true;
10401 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10402 // If this is an insert of an extract from some other vector, include it.
10403 Value *VecOp = IEI->getOperand(0);
10404 Value *ScalarOp = IEI->getOperand(1);
10405 Value *IdxOp = IEI->getOperand(2);
10406
Chris Lattnerd929f062006-04-27 21:14:21 +000010407 if (!isa<ConstantInt>(IdxOp))
10408 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010409 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010410
10411 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10412 // Okay, we can handle this if the vector we are insertinting into is
10413 // transitively ok.
10414 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10415 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010416 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010417 return true;
10418 }
10419 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10420 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010421 EI->getOperand(0)->getType() == V->getType()) {
10422 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010423 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010424
10425 // This must be extracting from either LHS or RHS.
10426 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10427 // Okay, we can handle this if the vector we are insertinting into is
10428 // transitively ok.
10429 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10430 // If so, update the mask to reflect the inserted value.
10431 if (EI->getOperand(0) == LHS) {
10432 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010433 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010434 } else {
10435 assert(EI->getOperand(0) == RHS);
10436 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010437 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010438
10439 }
10440 return true;
10441 }
10442 }
10443 }
10444 }
10445 }
10446 // TODO: Handle shufflevector here!
10447
10448 return false;
10449}
10450
10451/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10452/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10453/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010454static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010455 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010456 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010457 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010458 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010459 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010460
10461 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010462 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010463 return V;
10464 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010465 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010466 return V;
10467 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10468 // If this is an insert of an extract from some other vector, include it.
10469 Value *VecOp = IEI->getOperand(0);
10470 Value *ScalarOp = IEI->getOperand(1);
10471 Value *IdxOp = IEI->getOperand(2);
10472
10473 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10474 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10475 EI->getOperand(0)->getType() == V->getType()) {
10476 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010477 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10478 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010479
10480 // Either the extracted from or inserted into vector must be RHSVec,
10481 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010482 if (EI->getOperand(0) == RHS || RHS == 0) {
10483 RHS = EI->getOperand(0);
10484 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010485 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010486 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010487 return V;
10488 }
10489
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010490 if (VecOp == RHS) {
10491 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010492 // Everything but the extracted element is replaced with the RHS.
10493 for (unsigned i = 0; i != NumElts; ++i) {
10494 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010495 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010496 }
10497 return V;
10498 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010499
10500 // If this insertelement is a chain that comes from exactly these two
10501 // vectors, return the vector and the effective shuffle.
10502 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10503 return EI->getOperand(0);
10504
Chris Lattnerefb47352006-04-15 01:39:45 +000010505 }
10506 }
10507 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010508 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010509
10510 // Otherwise, can't do anything fancy. Return an identity vector.
10511 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010512 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010513 return V;
10514}
10515
10516Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10517 Value *VecOp = IE.getOperand(0);
10518 Value *ScalarOp = IE.getOperand(1);
10519 Value *IdxOp = IE.getOperand(2);
10520
Chris Lattner599ded12007-04-09 01:11:16 +000010521 // Inserting an undef or into an undefined place, remove this.
10522 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10523 ReplaceInstUsesWith(IE, VecOp);
10524
Chris Lattnerefb47352006-04-15 01:39:45 +000010525 // If the inserted element was extracted from some other vector, and if the
10526 // indexes are constant, try to turn this into a shufflevector operation.
10527 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10528 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10529 EI->getOperand(0)->getType() == IE.getType()) {
10530 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010531 unsigned ExtractedIdx =
10532 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010533 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010534
10535 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10536 return ReplaceInstUsesWith(IE, VecOp);
10537
10538 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10539 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10540
10541 // If we are extracting a value from a vector, then inserting it right
10542 // back into the same place, just use the input vector.
10543 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10544 return ReplaceInstUsesWith(IE, VecOp);
10545
10546 // We could theoretically do this for ANY input. However, doing so could
10547 // turn chains of insertelement instructions into a chain of shufflevector
10548 // instructions, and right now we do not merge shufflevectors. As such,
10549 // only do this in a situation where it is clear that there is benefit.
10550 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10551 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10552 // the values of VecOp, except then one read from EIOp0.
10553 // Build a new shuffle mask.
10554 std::vector<Constant*> Mask;
10555 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010556 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010557 else {
10558 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010559 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010560 NumVectorElts));
10561 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010562 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010563 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010564 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010565 }
10566
10567 // If this insertelement isn't used by some other insertelement, turn it
10568 // (and any insertelements it points to), into one big shuffle.
10569 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10570 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010571 Value *RHS = 0;
10572 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10573 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10574 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010575 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010576 }
10577 }
10578 }
10579
10580 return 0;
10581}
10582
10583
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010584Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10585 Value *LHS = SVI.getOperand(0);
10586 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010587 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010588
10589 bool MadeChange = false;
10590
Chris Lattner867b99f2006-10-05 06:55:50 +000010591 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010592 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010593 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10594
Chris Lattnere4929dd2007-01-05 07:36:08 +000010595 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010596 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010597 if (isa<UndefValue>(SVI.getOperand(1))) {
10598 // Scan to see if there are any references to the RHS. If so, replace them
10599 // with undef element refs and set MadeChange to true.
10600 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10601 if (Mask[i] >= e && Mask[i] != 2*e) {
10602 Mask[i] = 2*e;
10603 MadeChange = true;
10604 }
10605 }
10606
10607 if (MadeChange) {
10608 // Remap any references to RHS to use LHS.
10609 std::vector<Constant*> Elts;
10610 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10611 if (Mask[i] == 2*e)
10612 Elts.push_back(UndefValue::get(Type::Int32Ty));
10613 else
10614 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10615 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010616 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010617 }
10618 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010619
Chris Lattner863bcff2006-05-25 23:48:38 +000010620 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10621 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10622 if (LHS == RHS || isa<UndefValue>(LHS)) {
10623 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010624 // shuffle(undef,undef,mask) -> undef.
10625 return ReplaceInstUsesWith(SVI, LHS);
10626 }
10627
Chris Lattner863bcff2006-05-25 23:48:38 +000010628 // Remap any references to RHS to use LHS.
10629 std::vector<Constant*> Elts;
10630 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010631 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010632 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010633 else {
10634 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10635 (Mask[i] < e && isa<UndefValue>(LHS)))
10636 Mask[i] = 2*e; // Turn into undef.
10637 else
10638 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010639 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010640 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010641 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010642 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010643 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010644 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010645 LHS = SVI.getOperand(0);
10646 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010647 MadeChange = true;
10648 }
10649
Chris Lattner7b2e27922006-05-26 00:29:06 +000010650 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010651 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010652
Chris Lattner863bcff2006-05-25 23:48:38 +000010653 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10654 if (Mask[i] >= e*2) continue; // Ignore undef values.
10655 // Is this an identity shuffle of the LHS value?
10656 isLHSID &= (Mask[i] == i);
10657
10658 // Is this an identity shuffle of the RHS value?
10659 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010660 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010661
Chris Lattner863bcff2006-05-25 23:48:38 +000010662 // Eliminate identity shuffles.
10663 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10664 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010665
Chris Lattner7b2e27922006-05-26 00:29:06 +000010666 // If the LHS is a shufflevector itself, see if we can combine it with this
10667 // one without producing an unusual shuffle. Here we are really conservative:
10668 // we are absolutely afraid of producing a shuffle mask not in the input
10669 // program, because the code gen may not be smart enough to turn a merged
10670 // shuffle into two specific shuffles: it may produce worse code. As such,
10671 // we only merge two shuffles if the result is one of the two input shuffle
10672 // masks. In this case, merging the shuffles just removes one instruction,
10673 // which we know is safe. This is good for things like turning:
10674 // (splat(splat)) -> splat.
10675 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10676 if (isa<UndefValue>(RHS)) {
10677 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10678
10679 std::vector<unsigned> NewMask;
10680 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10681 if (Mask[i] >= 2*e)
10682 NewMask.push_back(2*e);
10683 else
10684 NewMask.push_back(LHSMask[Mask[i]]);
10685
10686 // If the result mask is equal to the src shuffle or this shuffle mask, do
10687 // the replacement.
10688 if (NewMask == LHSMask || NewMask == Mask) {
10689 std::vector<Constant*> Elts;
10690 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10691 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010692 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010693 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010694 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010695 }
10696 }
10697 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10698 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010699 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010700 }
10701 }
10702 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010703
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010704 return MadeChange ? &SVI : 0;
10705}
10706
10707
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010708
Chris Lattnerea1c4542004-12-08 23:43:58 +000010709
10710/// TryToSinkInstruction - Try to move the specified instruction from its
10711/// current block into the beginning of DestBlock, which can only happen if it's
10712/// safe to move the instruction past all of the instructions between it and the
10713/// end of its block.
10714static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10715 assert(I->hasOneUse() && "Invariants didn't hold!");
10716
Chris Lattner108e9022005-10-27 17:13:11 +000010717 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10718 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010719
Chris Lattnerea1c4542004-12-08 23:43:58 +000010720 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010721 if (isa<AllocaInst>(I) && I->getParent() ==
10722 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010723 return false;
10724
Chris Lattner96a52a62004-12-09 07:14:34 +000010725 // We can only sink load instructions if there is nothing between the load and
10726 // the end of block that could change the value.
10727 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010728 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10729 Scan != E; ++Scan)
10730 if (Scan->mayWriteToMemory())
10731 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010732 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010733
10734 BasicBlock::iterator InsertPos = DestBlock->begin();
10735 while (isa<PHINode>(InsertPos)) ++InsertPos;
10736
Chris Lattner4bc5f802005-08-08 19:11:57 +000010737 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010738 ++NumSunkInst;
10739 return true;
10740}
10741
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010742
10743/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10744/// all reachable code to the worklist.
10745///
10746/// This has a couple of tricks to make the code faster and more powerful. In
10747/// particular, we constant fold and DCE instructions as we go, to avoid adding
10748/// them to the worklist (this significantly speeds up instcombine on code where
10749/// many instructions are dead or constant). Additionally, if we find a branch
10750/// whose condition is a known constant, we only visit the reachable successors.
10751///
10752static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010753 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010754 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010755 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010756 std::vector<BasicBlock*> Worklist;
10757 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010758
Chris Lattner2c7718a2007-03-23 19:17:18 +000010759 while (!Worklist.empty()) {
10760 BB = Worklist.back();
10761 Worklist.pop_back();
10762
10763 // We have now visited this block! If we've already been here, ignore it.
10764 if (!Visited.insert(BB)) continue;
10765
10766 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10767 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010768
Chris Lattner2c7718a2007-03-23 19:17:18 +000010769 // DCE instruction if trivially dead.
10770 if (isInstructionTriviallyDead(Inst)) {
10771 ++NumDeadInst;
10772 DOUT << "IC: DCE: " << *Inst;
10773 Inst->eraseFromParent();
10774 continue;
10775 }
10776
10777 // ConstantProp instruction if trivially constant.
10778 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10779 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10780 Inst->replaceAllUsesWith(C);
10781 ++NumConstProp;
10782 Inst->eraseFromParent();
10783 continue;
10784 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010785
Chris Lattner2c7718a2007-03-23 19:17:18 +000010786 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010787 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010788
10789 // Recursively visit successors. If this is a branch or switch on a
10790 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000010791 if (BB->getUnwindDest())
10792 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000010793 TerminatorInst *TI = BB->getTerminator();
10794 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10795 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10796 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000010797 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10798 if (ReachableBB != BB->getUnwindDest())
10799 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010800 continue;
10801 }
10802 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10803 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10804 // See if this is an explicit destination.
10805 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10806 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000010807 BasicBlock *ReachableBB = SI->getSuccessor(i);
10808 if (ReachableBB != BB->getUnwindDest())
10809 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010810 continue;
10811 }
10812
10813 // Otherwise it is the default destination.
10814 Worklist.push_back(SI->getSuccessor(0));
10815 continue;
10816 }
10817 }
10818
10819 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10820 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010821 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010822}
10823
Chris Lattnerec9c3582007-03-03 02:04:50 +000010824bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010825 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010826 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010827
10828 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10829 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010830
Chris Lattnerb3d59702005-07-07 20:40:38 +000010831 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010832 // Do a depth-first traversal of the function, populate the worklist with
10833 // the reachable instructions. Ignore blocks that are not reachable. Keep
10834 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010835 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010836 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010837
Chris Lattnerb3d59702005-07-07 20:40:38 +000010838 // Do a quick scan over the function. If we find any blocks that are
10839 // unreachable, remove any instructions inside of them. This prevents
10840 // the instcombine code from having to deal with some bad special cases.
10841 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10842 if (!Visited.count(BB)) {
10843 Instruction *Term = BB->getTerminator();
10844 while (Term != BB->begin()) { // Remove instrs bottom-up
10845 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010846
Bill Wendlingb7427032006-11-26 09:46:52 +000010847 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010848 ++NumDeadInst;
10849
10850 if (!I->use_empty())
10851 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10852 I->eraseFromParent();
10853 }
10854 }
10855 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010856
Chris Lattnerdbab3862007-03-02 21:28:56 +000010857 while (!Worklist.empty()) {
10858 Instruction *I = RemoveOneFromWorkList();
10859 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010860
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010861 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010862 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010863 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010864 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010865 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010866 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010867
Bill Wendlingb7427032006-11-26 09:46:52 +000010868 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010869
10870 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010871 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010872 continue;
10873 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010874
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010875 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010876 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010877 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010878
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010879 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010880 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010881 ReplaceInstUsesWith(*I, C);
10882
Chris Lattner62b14df2002-09-02 04:59:56 +000010883 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010884 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010885 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010886 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010887 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010888
Chris Lattnerea1c4542004-12-08 23:43:58 +000010889 // See if we can trivially sink this instruction to a successor basic block.
10890 if (I->hasOneUse()) {
10891 BasicBlock *BB = I->getParent();
10892 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10893 if (UserParent != BB) {
10894 bool UserIsSuccessor = false;
10895 // See if the user is one of our successors.
10896 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10897 if (*SI == UserParent) {
10898 UserIsSuccessor = true;
10899 break;
10900 }
10901
10902 // If the user is one of our immediate successors, and if that successor
10903 // only has us as a predecessors (we'd have to split the critical edge
10904 // otherwise), we can keep going.
10905 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10906 next(pred_begin(UserParent)) == pred_end(UserParent))
10907 // Okay, the CFG is simple enough, try to sink this instruction.
10908 Changed |= TryToSinkInstruction(I, UserParent);
10909 }
10910 }
10911
Chris Lattner8a2a3112001-12-14 16:52:21 +000010912 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010913#ifndef NDEBUG
10914 std::string OrigI;
10915#endif
10916 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010917 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010918 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010919 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010920 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010921 DOUT << "IC: Old = " << *I
10922 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010923
Chris Lattnerf523d062004-06-09 05:08:07 +000010924 // Everything uses the new instruction now.
10925 I->replaceAllUsesWith(Result);
10926
10927 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010928 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010929 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010930
Chris Lattner6934a042007-02-11 01:23:03 +000010931 // Move the name to the new instruction first.
10932 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010933
10934 // Insert the new instruction into the basic block...
10935 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010936 BasicBlock::iterator InsertPos = I;
10937
10938 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10939 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10940 ++InsertPos;
10941
10942 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010943
Chris Lattner00d51312004-05-01 23:27:23 +000010944 // Make sure that we reprocess all operands now that we reduced their
10945 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010946 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010947
Chris Lattnerf523d062004-06-09 05:08:07 +000010948 // Instructions can end up on the worklist more than once. Make sure
10949 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010950 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010951
10952 // Erase the old instruction.
10953 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010954 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010955#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010956 DOUT << "IC: Mod = " << OrigI
10957 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010958#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010959
Chris Lattner90ac28c2002-08-02 19:29:35 +000010960 // If the instruction was modified, it's possible that it is now dead.
10961 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010962 if (isInstructionTriviallyDead(I)) {
10963 // Make sure we process all operands now that we are reducing their
10964 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010965 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010966
Chris Lattner00d51312004-05-01 23:27:23 +000010967 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010968 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010969 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010970 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010971 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010972 AddToWorkList(I);
10973 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010974 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010975 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010976 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010977 }
10978 }
10979
Chris Lattnerec9c3582007-03-03 02:04:50 +000010980 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010981
10982 // Do an explicit clear, this shrinks the map if needed.
10983 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010984 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010985}
10986
Chris Lattnerec9c3582007-03-03 02:04:50 +000010987
10988bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010989 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10990
Chris Lattnerec9c3582007-03-03 02:04:50 +000010991 bool EverMadeChange = false;
10992
10993 // Iterate while there is work to do.
10994 unsigned Iteration = 0;
10995 while (DoOneIteration(F, Iteration++))
10996 EverMadeChange = true;
10997 return EverMadeChange;
10998}
10999
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011000FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011001 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011002}
Brian Gaeked0fde302003-11-11 22:41:34 +000011003