blob: 6af0afd55e18e40de3ab3a5ea0476c1ee41fcd61 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
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 Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000204
Reid Spencere4d87aa2006-12-23 06:05:41 +0000205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000208 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000223 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000232 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000233 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000234 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000235 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000236 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000237 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000238 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000245
Chris Lattner9fe38862003-06-19 17:00:31 +0000246 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000247 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000253 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
254
Chris Lattner9fe38862003-06-19 17:00:31 +0000255
Chris Lattner28977af2004-04-05 01:30:19 +0000256 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000257 // InsertNewInstBefore - insert an instruction New before instruction Old
258 // in the program. Add the new instruction to the worklist.
259 //
Chris Lattner955f3312004-09-28 21:48:02 +0000260 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000261 assert(New && New->getParent() == 0 &&
262 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000263 BasicBlock *BB = Old.getParent();
264 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000265 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000266 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000267 }
268
Chris Lattner0c967662004-09-24 15:21:34 +0000269 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
270 /// This also adds the cast to the worklist. Finally, this returns the
271 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000272 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
273 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000274 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000275
Chris Lattnere2ed0572006-04-06 19:19:17 +0000276 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000277 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000278
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000279 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000280 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000281 return C;
282 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000283
284 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
285 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
286 }
287
Chris Lattner0c967662004-09-24 15:21:34 +0000288
Chris Lattner8b170942002-08-09 23:47:40 +0000289 // ReplaceInstUsesWith - This method is to be used when an instruction is
290 // found to be dead, replacable with another preexisting expression. Here
291 // we add all uses of I to the worklist, replace all uses of I with the new
292 // value, then return I, so that the inst combiner will know that I was
293 // modified.
294 //
295 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000296 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000297 if (&I != V) {
298 I.replaceAllUsesWith(V);
299 return &I;
300 } else {
301 // If we are replacing the instruction with itself, this must be in a
302 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000303 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000304 return &I;
305 }
Chris Lattner8b170942002-08-09 23:47:40 +0000306 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000307
308 // EraseInstFromFunction - When dealing with an instruction that has side
309 // effects or produces a void value, we can't rely on DCE to delete the
310 // instruction. Instead, visit methods should return the value returned by
311 // this function.
312 Instruction *EraseInstFromFunction(Instruction &I) {
313 assert(I.use_empty() && "Cannot erase instruction that is used!");
314 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000315 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000316 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000317 return 0; // Don't do anything with FI
318 }
Chris Lattner173234a2008-06-02 01:18:21 +0000319
320 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
321 APInt &KnownOne, unsigned Depth = 0) const {
322 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
323 }
324
325 bool MaskedValueIsZero(Value *V, const APInt &Mask,
326 unsigned Depth = 0) const {
327 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
328 }
329 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
330 return llvm::ComputeNumSignBits(Op, TD, Depth);
331 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000332
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000333 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000334
Reid Spencere4d87aa2006-12-23 06:05:41 +0000335 /// SimplifyCommutative - This performs a few simplifications for
336 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000337 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000338
Reid Spencere4d87aa2006-12-23 06:05:41 +0000339 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
340 /// most-complex to least-complex order.
341 bool SimplifyCompare(CmpInst &I);
342
Chris Lattner886ab6c2009-01-31 08:15:18 +0000343 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
344 /// based on the demanded bits.
345 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
346 APInt& KnownZero, APInt& KnownOne,
347 unsigned Depth);
348 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000349 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000350 unsigned Depth=0);
351
352 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
353 /// SimplifyDemandedBits knows about. See if the instruction has any
354 /// properties that allow us to simplify its operands.
355 bool SimplifyDemandedInstructionBits(Instruction &Inst);
356
Evan Cheng388df622009-02-03 10:05:09 +0000357 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
358 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000359
Chris Lattner4e998b22004-09-29 05:07:12 +0000360 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
361 // PHI node as operand #0, see if we can fold the instruction into the PHI
362 // (which is only possible if all operands to the PHI are constants).
363 Instruction *FoldOpIntoPhi(Instruction &I);
364
Chris Lattnerbac32862004-11-14 19:13:23 +0000365 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
366 // operator and they all are only used by the PHI, PHI together their
367 // inputs, and do the operation once, to the result of the PHI.
368 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000369 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000370 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
371
Chris Lattner7da52b22006-11-01 04:51:18 +0000372
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000373 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
374 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000375
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000376 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000377 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000378 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000379 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000380 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000381 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000382 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000383 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000384 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000385
Chris Lattnerafe91a52006-06-15 19:07:26 +0000386
Reid Spencerc55b2432006-12-13 18:21:21 +0000387 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000388
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000390 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000391 unsigned GetOrEnforceKnownAlignment(Value *V,
392 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000393
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000394 };
395}
396
Dan Gohman844731a2008-05-13 00:00:25 +0000397char InstCombiner::ID = 0;
398static RegisterPass<InstCombiner>
399X("instcombine", "Combine redundant instructions");
400
Chris Lattner4f98c562003-03-10 21:43:22 +0000401// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000402// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000403static unsigned getComplexity(Value *V) {
404 if (isa<Instruction>(V)) {
405 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000406 return 3;
407 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000408 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000409 if (isa<Argument>(V)) return 3;
410 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000411}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000412
Chris Lattnerc8802d22003-03-11 00:12:48 +0000413// isOnlyUse - Return true if this instruction will be deleted if we stop using
414// it.
415static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000416 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000417}
418
Chris Lattner4cb170c2004-02-23 06:38:22 +0000419// getPromotedType - Return the specified type promoted as it would be to pass
420// though a va_arg area...
421static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000422 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
423 if (ITy->getBitWidth() < 32)
424 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000425 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000426 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000427}
428
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000429/// getBitCastOperand - If the specified operand is a CastInst, a constant
430/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
431/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000432static Value *getBitCastOperand(Value *V) {
433 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000435 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000436 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
437 // GetElementPtrInst?
438 if (GEP->hasAllZeroIndices())
439 return GEP->getOperand(0);
440 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000441 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000443 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000444 else if (CE->getOpcode() == Instruction::GetElementPtr) {
445 // GetElementPtr ConstantExp?
446 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
447 I != E; ++I) {
448 ConstantInt *CI = dyn_cast<ConstantInt>(I);
449 if (!CI || !CI->isZero())
450 // Any non-zero indices? Not cast-like.
451 return 0;
452 }
453 // All-zero indices? This is just like casting.
454 return CE->getOperand(0);
455 }
456 }
Chris Lattnereed48272005-09-13 00:40:14 +0000457 return 0;
458}
459
Reid Spencer3da59db2006-11-27 01:05:10 +0000460/// This function is a wrapper around CastInst::isEliminableCastPair. It
461/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000462static Instruction::CastOps
463isEliminableCastPair(
464 const CastInst *CI, ///< The first cast instruction
465 unsigned opcode, ///< The opcode of the second cast instruction
466 const Type *DstTy, ///< The target type for the second cast instruction
467 TargetData *TD ///< The target data for pointer size
468) {
469
470 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
471 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000472
Reid Spencer3da59db2006-11-27 01:05:10 +0000473 // Get the opcodes of the two Cast instructions
474 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
475 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000476
Reid Spencer3da59db2006-11-27 01:05:10 +0000477 return Instruction::CastOps(
478 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
479 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000480}
481
482/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
483/// in any code being generated. It does not require codegen if V is simple
484/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000485static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
486 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000487 if (V->getType() == Ty || isa<Constant>(V)) return false;
488
Chris Lattner01575b72006-05-25 23:24:33 +0000489 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000490 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000491 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000492 return false;
493 return true;
494}
495
Chris Lattner4f98c562003-03-10 21:43:22 +0000496// SimplifyCommutative - This performs a few simplifications for commutative
497// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000498//
Chris Lattner4f98c562003-03-10 21:43:22 +0000499// 1. Order operands such that they are listed from right (least complex) to
500// left (most complex). This puts constants before unary operators before
501// binary operators.
502//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000505//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000507 bool Changed = false;
508 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000510
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 if (!I.isAssociative()) return Changed;
512 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000516 Constant *Folded = ConstantExpr::get(I.getOpcode(),
517 cast<Constant>(I.getOperand(1)),
518 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 I.setOperand(0, Op->getOperand(0));
520 I.setOperand(1, Folded);
521 return true;
522 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524 isOnlyUse(Op) && isOnlyUse(Op1)) {
525 Constant *C1 = cast<Constant>(Op->getOperand(1));
526 Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000529 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000530 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 Op1->getOperand(0),
532 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000533 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 I.setOperand(0, New);
535 I.setOperand(1, Folded);
536 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000537 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000538 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000539 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000540}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000541
Reid Spencere4d87aa2006-12-23 06:05:41 +0000542/// SimplifyCompare - For a CmpInst this function just orders the operands
543/// so that theyare listed from right (least complex) to left (most complex).
544/// This puts constants before unary operators before binary operators.
545bool InstCombiner::SimplifyCompare(CmpInst &I) {
546 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547 return false;
548 I.swapOperands();
549 // Compare instructions are not associative so there's nothing else we can do.
550 return true;
551}
552
Chris Lattner8d969642003-03-10 23:06:50 +0000553// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000555//
Chris Lattner8d969642003-03-10 23:06:50 +0000556static inline Value *dyn_castNegVal(Value *V) {
557 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000558 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000559
Chris Lattner0ce85802004-12-14 20:08:06 +0000560 // Constants can be considered to be negated values if they can be folded.
561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000563
564 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
565 if (C->getType()->getElementType()->isInteger())
566 return ConstantExpr::getNeg(C);
567
Chris Lattner8d969642003-03-10 23:06:50 +0000568 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000569}
570
Chris Lattner8d969642003-03-10 23:06:50 +0000571static inline Value *dyn_castNotVal(Value *V) {
572 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000573 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000574
575 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000576 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000577 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000578 return 0;
579}
580
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581// dyn_castFoldableMul - If this value is a multiply that can be folded into
582// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000583// non-constant operand of the multiply, and set CST to point to the multiplier.
584// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000585//
Chris Lattner50af16a2004-11-13 19:50:12 +0000586static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000587 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000588 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000590 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000594 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000595 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000596 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000597 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000598 return I->getOperand(0);
599 }
600 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000601 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000602}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000603
Chris Lattner574da9b2005-01-13 20:14:25 +0000604/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
605/// expression, return it.
606static User *dyn_castGetElementPtr(Value *V) {
607 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
609 if (CE->getOpcode() == Instruction::GetElementPtr)
610 return cast<User>(V);
611 return false;
612}
613
Dan Gohmaneee962e2008-04-10 18:43:06 +0000614/// getOpcode - If this is an Instruction or a ConstantExpr, return the
615/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000616static unsigned getOpcode(const Value *V) {
617 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000619 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000620 return CE->getOpcode();
621 // Use UserOp1 to mean there's no opcode.
622 return Instruction::UserOp1;
623}
624
Reid Spencer7177c3a2007-03-25 05:33:51 +0000625/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000626static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000627 APInt Val(C->getValue());
628 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000629}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000630/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000631static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000632 APInt Val(C->getValue());
633 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000634}
635/// Add - Add two ConstantInts together
636static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
637 return ConstantInt::get(C1->getValue() + C2->getValue());
638}
639/// And - Bitwise AND two ConstantInts together
640static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
641 return ConstantInt::get(C1->getValue() & C2->getValue());
642}
643/// Subtract - Subtract one ConstantInt from another
644static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() - C2->getValue());
646}
647/// Multiply - Multiply two ConstantInts together
648static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000650}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000651/// MultiplyOverflows - True if the multiply can not be expressed in an int
652/// this size.
653static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
654 uint32_t W = C1->getBitWidth();
655 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656 if (sign) {
657 LHSExt.sext(W * 2);
658 RHSExt.sext(W * 2);
659 } else {
660 LHSExt.zext(W * 2);
661 RHSExt.zext(W * 2);
662 }
663
664 APInt MulExt = LHSExt * RHSExt;
665
666 if (sign) {
667 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
668 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
669 return MulExt.slt(Min) || MulExt.sgt(Max);
670 } else
671 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
672}
Chris Lattner955f3312004-09-28 21:48:02 +0000673
Reid Spencere7816b52007-03-08 01:52:58 +0000674
Chris Lattner255d8912006-02-11 09:31:47 +0000675/// ShrinkDemandedConstant - Check to see if the specified operand of the
676/// specified instruction is a constant integer. If so, check to see if there
677/// are any bits set in the constant that are not demanded. If so, shrink the
678/// constant and return true.
679static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000680 APInt Demanded) {
681 assert(I && "No instruction?");
682 assert(OpNo < I->getNumOperands() && "Operand index too large");
683
684 // If the operand is not a constant integer, nothing to do.
685 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
686 if (!OpC) return false;
687
688 // If there are no bits set that aren't demanded, nothing to do.
689 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
690 if ((~Demanded & OpC->getValue()) == 0)
691 return false;
692
693 // This instruction is producing bits that are not demanded. Shrink the RHS.
694 Demanded &= OpC->getValue();
695 I->setOperand(OpNo, ConstantInt::get(Demanded));
696 return true;
697}
698
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000699// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
700// set of known zero and one bits, compute the maximum and minimum values that
701// could have the specified known zero and known one bits, returning them in
702// min/max.
703static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000704 const APInt& KnownZero,
705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
707 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
708 assert(KnownZero.getBitWidth() == BitWidth &&
709 KnownOne.getBitWidth() == BitWidth &&
710 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
711 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000712 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000714 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
715 // bit if it is unknown.
716 Min = KnownOne;
717 Max = KnownOne|UnknownBits;
718
Zhou Sheng4acf1552007-03-28 05:15:57 +0000719 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000720 Min.set(BitWidth-1);
721 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000723}
724
725// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
726// a set of known zero and one bits, compute the maximum and minimum values that
727// could have the specified known zero and known one bits, returning them in
728// min/max.
729static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000730 const APInt &KnownZero,
731 const APInt &KnownOne,
732 APInt &Min, APInt &Max) {
733 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000734 assert(KnownZero.getBitWidth() == BitWidth &&
735 KnownOne.getBitWidth() == BitWidth &&
736 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
737 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000738 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000739
740 // The minimum value is when the unknown bits are all zeros.
741 Min = KnownOne;
742 // The maximum value is when the unknown bits are all ones.
743 Max = KnownOne|UnknownBits;
744}
Chris Lattner255d8912006-02-11 09:31:47 +0000745
Chris Lattner886ab6c2009-01-31 08:15:18 +0000746/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
747/// SimplifyDemandedBits knows about. See if the instruction has any
748/// properties that allow us to simplify its operands.
749bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
750 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
751 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
752 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
753
754 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
755 KnownZero, KnownOne, 0);
756 if (V == 0) return false;
757 if (V == &Inst) return true;
758 ReplaceInstUsesWith(Inst, V);
759 return true;
760}
761
762/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
763/// specified instruction operand if possible, updating it in place. It returns
764/// true if it made any change and false otherwise.
765bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
766 APInt &KnownZero, APInt &KnownOne,
767 unsigned Depth) {
768 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
769 KnownZero, KnownOne, Depth);
770 if (NewVal == 0) return false;
771 U.set(NewVal);
772 return true;
773}
774
775
776/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
777/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000778/// that only the bits set in DemandedMask of the result of V are ever used
779/// downstream. Consequently, depending on the mask and V, it may be possible
780/// to replace V with a constant or one of its operands. In such cases, this
781/// function does the replacement and returns true. In all other cases, it
782/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000783/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000784/// to be zero in the expression. These are provided to potentially allow the
785/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
786/// the expression. KnownOne and KnownZero always follow the invariant that
787/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
788/// the bits in KnownOne and KnownZero may only be accurate for those bits set
789/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
790/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000791///
792/// This returns null if it did not change anything and it permits no
793/// simplification. This returns V itself if it did some simplification of V's
794/// operands based on the information about what bits are demanded. This returns
795/// some other non-null value if it found out that V is equal to another value
796/// in the context where the specified bits are demanded, but not for all users.
797Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
798 APInt &KnownZero, APInt &KnownOne,
799 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000800 assert(V != 0 && "Null pointer of Value???");
801 assert(Depth <= 6 && "Limit Search Depth");
802 uint32_t BitWidth = DemandedMask.getBitWidth();
803 const IntegerType *VTy = cast<IntegerType>(V->getType());
804 assert(VTy->getBitWidth() == BitWidth &&
805 KnownZero.getBitWidth() == BitWidth &&
806 KnownOne.getBitWidth() == BitWidth &&
807 "Value *V, DemandedMask, KnownZero and KnownOne \
808 must have same BitWidth");
809 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
810 // We know all of the bits for a constant!
811 KnownOne = CI->getValue() & DemandedMask;
812 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000813 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000814 }
815
Chris Lattner08d2cc72009-01-31 07:26:06 +0000816 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000817 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000818 if (DemandedMask == 0) { // Not demanding any bits from V.
819 if (isa<UndefValue>(V))
820 return 0;
821 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 }
823
Chris Lattner4598c942009-01-31 08:24:16 +0000824 if (Depth == 6) // Limit search depth.
825 return 0;
826
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000828 if (!I) return 0; // Only analyze instructions.
Chris Lattner4598c942009-01-31 08:24:16 +0000829
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000830 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
831 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
832
Chris Lattner4598c942009-01-31 08:24:16 +0000833 // If there are multiple uses of this value and we aren't at the root, then
834 // we can't do any simplifications of the operands, because DemandedMask
835 // only reflects the bits demanded by *one* of the users.
836 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000837 // Despite the fact that we can't simplify this instruction in all User's
838 // context, we can at least compute the knownzero/knownone bits, and we can
839 // do simplifications that apply to *just* the one user if we know that
840 // this instruction has a simpler value in that context.
841 if (I->getOpcode() == Instruction::And) {
842 // If either the LHS or the RHS are Zero, the result is zero.
843 ComputeMaskedBits(I->getOperand(1), DemandedMask,
844 RHSKnownZero, RHSKnownOne, Depth+1);
845 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
846 LHSKnownZero, LHSKnownOne, Depth+1);
847
848 // If all of the demanded bits are known 1 on one side, return the other.
849 // These bits cannot contribute to the result of the 'and' in this
850 // context.
851 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
852 (DemandedMask & ~LHSKnownZero))
853 return I->getOperand(0);
854 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
855 (DemandedMask & ~RHSKnownZero))
856 return I->getOperand(1);
857
858 // If all of the demanded bits in the inputs are known zeros, return zero.
859 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
860 return Constant::getNullValue(VTy);
861
862 } else if (I->getOpcode() == Instruction::Or) {
863 // We can simplify (X|Y) -> X or Y in the user's context if we know that
864 // only bits from X or Y are demanded.
865
866 // If either the LHS or the RHS are One, the result is One.
867 ComputeMaskedBits(I->getOperand(1), DemandedMask,
868 RHSKnownZero, RHSKnownOne, Depth+1);
869 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
870 LHSKnownZero, LHSKnownOne, Depth+1);
871
872 // If all of the demanded bits are known zero on one side, return the
873 // other. These bits cannot contribute to the result of the 'or' in this
874 // context.
875 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
876 (DemandedMask & ~LHSKnownOne))
877 return I->getOperand(0);
878 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
879 (DemandedMask & ~RHSKnownOne))
880 return I->getOperand(1);
881
882 // If all of the potentially set bits on one side are known to be set on
883 // the other side, just use the 'other' side.
884 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
885 (DemandedMask & (~RHSKnownZero)))
886 return I->getOperand(0);
887 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
888 (DemandedMask & (~LHSKnownZero)))
889 return I->getOperand(1);
890 }
891
Chris Lattner4598c942009-01-31 08:24:16 +0000892 // Compute the KnownZero/KnownOne bits to simplify things downstream.
893 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
894 return 0;
895 }
896
897 // If this is the root being simplified, allow it to have multiple uses,
898 // just set the DemandedMask to all bits so that we can try to simplify the
899 // operands. This allows visitTruncInst (for example) to simplify the
900 // operand of a trunc without duplicating all the logic below.
901 if (Depth == 0 && !V->hasOneUse())
902 DemandedMask = APInt::getAllOnesValue(BitWidth);
903
Reid Spencer8cb68342007-03-12 17:25:59 +0000904 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000905 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000906 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000907 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000908 case Instruction::And:
909 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000910 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
911 RHSKnownZero, RHSKnownOne, Depth+1) ||
912 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000913 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000914 return I;
915 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
916 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000917
918 // If all of the demanded bits are known 1 on one side, return the other.
919 // These bits cannot contribute to the result of the 'and'.
920 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
921 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
924 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000925 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000926
927 // If all of the demanded bits in the inputs are known zeros, return zero.
928 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000930
931 // If the RHS is a constant, see if we can simplify it.
932 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // Output known-1 bits are only known if set in both the LHS & RHS.
936 RHSKnownOne &= LHSKnownOne;
937 // Output known-0 are known to be clear if zero in either the LHS | RHS.
938 RHSKnownZero |= LHSKnownZero;
939 break;
940 case Instruction::Or:
941 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000942 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
943 RHSKnownZero, RHSKnownOne, Depth+1) ||
944 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000945 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 return I;
947 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
948 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // If all of the demanded bits are known zero on one side, return the other.
951 // These bits cannot contribute to the result of the 'or'.
952 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
953 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
956 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000958
959 // If all of the potentially set bits on one side are known to be set on
960 // the other side, just use the 'other' side.
961 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
962 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
965 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // If the RHS is a constant, see if we can simplify it.
969 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000970 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000971
972 // Output known-0 bits are only known if clear in both the LHS & RHS.
973 RHSKnownZero &= LHSKnownZero;
974 // Output known-1 are known to be set if set in either the LHS | RHS.
975 RHSKnownOne |= LHSKnownOne;
976 break;
977 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979 RHSKnownZero, RHSKnownOne, Depth+1) ||
980 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 return I;
983 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
984 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000985
986 // If all of the demanded bits are known zero on one side, return the other.
987 // These bits cannot contribute to the result of the 'xor'.
988 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // Output known-0 bits are known if clear or set in both the LHS & RHS.
994 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
995 (RHSKnownOne & LHSKnownOne);
996 // Output known-1 are known to be set if set in only one of the LHS, RHS.
997 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
998 (RHSKnownOne & LHSKnownZero);
999
1000 // If all of the demanded bits are known to be zero on one side or the
1001 // other, turn this into an *inclusive* or.
1002 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1003 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1004 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001005 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001008 }
1009
1010 // If all of the demanded bits on one side are known, and all of the set
1011 // bits on that side are also known to be set on the other side, turn this
1012 // into an AND, as we know the bits will be cleared.
1013 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1014 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1015 // all known
1016 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1017 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1018 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001019 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001021 }
1022 }
1023
1024 // If the RHS is a constant, see if we can simplify it.
1025 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 RHSKnownZero = KnownZeroOut;
1030 RHSKnownOne = KnownOneOut;
1031 break;
1032 }
1033 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035 RHSKnownZero, RHSKnownOne, Depth+1) ||
1036 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 return I;
1039 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1040 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001041
1042 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044 ShrinkDemandedConstant(I, 2, DemandedMask))
1045 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
1047 // Only known if known in both the LHS and RHS.
1048 RHSKnownOne &= LHSKnownOne;
1049 RHSKnownZero &= LHSKnownZero;
1050 break;
1051 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001052 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001053 DemandedMask.zext(truncBf);
1054 RHSKnownZero.zext(truncBf);
1055 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001057 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001058 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 DemandedMask.trunc(BitWidth);
1060 RHSKnownZero.trunc(BitWidth);
1061 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 break;
1064 }
1065 case Instruction::BitCast:
1066 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return false; // vector->int or fp->int?
1068 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001070 return I;
1071 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 break;
1073 case Instruction::ZExt: {
1074 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001076
Zhou Shengd48653a2007-03-29 04:45:55 +00001077 DemandedMask.trunc(SrcBitWidth);
1078 RHSKnownZero.trunc(SrcBitWidth);
1079 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001081 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 DemandedMask.zext(BitWidth);
1084 RHSKnownZero.zext(BitWidth);
1085 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001086 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001088 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 break;
1090 }
1091 case Instruction::SExt: {
1092 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001094
Reid Spencer8cb68342007-03-12 17:25:59 +00001095 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001096 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001097
Zhou Sheng01542f32007-03-29 02:26:30 +00001098 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 // If any of the sign extended bits are demanded, we know that the sign
1100 // bit is demanded.
1101 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001102 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001103
Zhou Shengd48653a2007-03-29 04:45:55 +00001104 InputDemandedBits.trunc(SrcBitWidth);
1105 RHSKnownZero.trunc(SrcBitWidth);
1106 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001108 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001109 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 InputDemandedBits.zext(BitWidth);
1111 RHSKnownZero.zext(BitWidth);
1112 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001113 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001114
1115 // If the sign bit of the input is known set or clear, then we know the
1116 // top bits of the result.
1117
1118 // If the input sign bit is known zero, or if the NewBits are not demanded
1119 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1123 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001124 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 }
1127 break;
1128 }
1129 case Instruction::Add: {
1130 // Figure out what the input bits are. If the top bits of the and result
1131 // are not demanded, then the add doesn't demand them from its input
1132 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
1135 // If there is a constant on the RHS, there are a variety of xformations
1136 // we can do.
1137 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138 // If null, this should be simplified elsewhere. Some of the xforms here
1139 // won't work if the RHS is zero.
1140 if (RHS->isZero())
1141 break;
1142
1143 // If the top bit of the output is demanded, demand everything from the
1144 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001146
1147 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
1152 // If the RHS of the add has bits set that can't affect the input, reduce
1153 // the constant.
1154 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001155 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001156
1157 // Avoid excess work.
1158 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1159 break;
1160
1161 // Turn it into OR if input bits are zero.
1162 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1163 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001164 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001166 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 }
1168
1169 // We can say something about the output known-zero and known-one bits,
1170 // depending on potential carries from the input constant and the
1171 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1172 // bits set and the RHS constant is 0x01001, then we know we have a known
1173 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1174
1175 // To compute this, we first compute the potential carry bits. These are
1176 // the bits which may be modified. I'm not aware of a better way to do
1177 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001178 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001179 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
1181 // Now that we know which bits have carries, compute the known-1/0 sets.
1182
1183 // Bits are known one if they are known zero in one operand and one in the
1184 // other, and there is no input carry.
1185 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1186 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1187
1188 // Bits are known zero if they are known zero in both operands and there
1189 // is no input carry.
1190 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1191 } else {
1192 // If the high-bits of this ADD are not demanded, then it does not demand
1193 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001194 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 // Right fill the mask of bits for this ADD to demand the most
1196 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001197 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001198 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1199 LHSKnownZero, LHSKnownOne, Depth+1) ||
1200 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 }
1204 }
1205 break;
1206 }
1207 case Instruction::Sub:
1208 // If the high-bits of this SUB are not demanded, then it does not demand
1209 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001210 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001211 // Right fill the mask of bits for this SUB to demand the most
1212 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001213 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1216 LHSKnownZero, LHSKnownOne, Depth+1) ||
1217 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001220 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001221 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1222 // the known zeros and ones.
1223 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 break;
1225 case Instruction::Shl:
1226 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001227 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001231 return I;
1232 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 RHSKnownZero <<= ShiftAmt;
1234 RHSKnownOne <<= ShiftAmt;
1235 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001236 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001237 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 }
1239 break;
1240 case Instruction::LShr:
1241 // For a logical shift right
1242 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001243 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001244
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001246 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 return I;
1250 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1252 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001253 if (ShiftAmt) {
1254 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001255 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001256 RHSKnownZero |= HighBits; // high bits known zero.
1257 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 }
1259 break;
1260 case Instruction::AShr:
1261 // If this is an arithmetic shift right and only the low-bit is set, we can
1262 // always convert this into a logical shr, even if the shift amount is
1263 // variable. The low bit of the shift cannot be an input sign bit unless
1264 // the shift amount is >= the size of the datatype, which is undefined.
1265 if (DemandedMask == 1) {
1266 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001271
1272 // If the sign bit is the only bit demanded by this ashr, then there is no
1273 // need to do it, the shift doesn't change the high bit.
1274 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001275 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001276
1277 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001278 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001279
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001281 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001282 // If any of the "high bits" are demanded, we should set the sign bit as
1283 // demanded.
1284 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1285 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001288 return I;
1289 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001291 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1293 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1294
1295 // Handle the sign bits.
1296 APInt SignBit(APInt::getSignBit(BitWidth));
1297 // Adjust to where it is now in the mask.
1298 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1299
1300 // If the input sign bit is known to be zero, or if none of the top bits
1301 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001302 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 (HighBits & ~DemandedMask) == HighBits) {
1304 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1309 RHSKnownOne |= HighBits;
1310 }
1311 }
1312 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001313 case Instruction::SRem:
1314 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001315 APInt RA = Rem->getValue().abs();
1316 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001317 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001319
Nick Lewycky8e394322008-11-02 02:41:50 +00001320 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001321 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001323 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001324 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001325
1326 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1327 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001328
1329 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001330
Chris Lattner886ab6c2009-01-31 08:15:18 +00001331 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001332 }
1333 }
1334 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001335 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001336 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1337 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001338 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1339 KnownZero2, KnownOne2, Depth+1) ||
1340 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001341 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001343
Chris Lattner455e9ab2009-01-21 18:09:24 +00001344 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001345 Leaders = std::max(Leaders,
1346 KnownZero2.countLeadingOnes());
1347 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001350 case Instruction::Call:
1351 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1352 switch (II->getIntrinsicID()) {
1353 default: break;
1354 case Intrinsic::bswap: {
1355 // If the only bits demanded come from one byte of the bswap result,
1356 // just shift the input byte into position to eliminate the bswap.
1357 unsigned NLZ = DemandedMask.countLeadingZeros();
1358 unsigned NTZ = DemandedMask.countTrailingZeros();
1359
1360 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1361 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1362 // have 14 leading zeros, round to 8.
1363 NLZ &= ~7;
1364 NTZ &= ~7;
1365 // If we need exactly one byte, we can do this transformation.
1366 if (BitWidth-NLZ-NTZ == 8) {
1367 unsigned ResultBit = NTZ;
1368 unsigned InputBit = BitWidth-NTZ-8;
1369
1370 // Replace this with either a left or right shift to get the byte into
1371 // the right place.
1372 Instruction *NewVal;
1373 if (InputBit > ResultBit)
1374 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1375 ConstantInt::get(I->getType(), InputBit-ResultBit));
1376 else
1377 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1378 ConstantInt::get(I->getType(), ResultBit-InputBit));
1379 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001380 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001381 }
1382
1383 // TODO: Could compute known zero/one bits based on the input.
1384 break;
1385 }
1386 }
1387 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001388 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001389 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001390 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001391
1392 // If the client is only demanding bits that we know, return the known
1393 // constant.
1394 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001395 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001396 return false;
1397}
1398
Chris Lattner867b99f2006-10-05 06:55:50 +00001399
Mon P Wangaeb06d22008-11-10 04:46:22 +00001400/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001401/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001402/// actually used by the caller. This method analyzes which elements of the
1403/// operand are undef and returns that information in UndefElts.
1404///
1405/// If the information about demanded elements can be used to simplify the
1406/// operation, the operation is simplified, then the resultant value is
1407/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001408Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1409 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001410 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001411 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001412 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001413 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001414
1415 if (isa<UndefValue>(V)) {
1416 // If the entire vector is undefined, just return this info.
1417 UndefElts = EltMask;
1418 return 0;
1419 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1420 UndefElts = EltMask;
1421 return UndefValue::get(V->getType());
1422 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001423
Chris Lattner867b99f2006-10-05 06:55:50 +00001424 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001425 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1426 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001427 Constant *Undef = UndefValue::get(EltTy);
1428
1429 std::vector<Constant*> Elts;
1430 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001431 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001432 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001433 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001434 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1435 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001436 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001437 } else { // Otherwise, defined.
1438 Elts.push_back(CP->getOperand(i));
1439 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001440
Chris Lattner867b99f2006-10-05 06:55:50 +00001441 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001442 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001443 return NewCP != CP ? NewCP : 0;
1444 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001445 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001447
1448 // Check if this is identity. If so, return 0 since we are not simplifying
1449 // anything.
1450 if (DemandedElts == ((1ULL << VWidth) -1))
1451 return 0;
1452
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 Constant *Zero = Constant::getNullValue(EltTy);
1455 Constant *Undef = UndefValue::get(EltTy);
1456 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001457 for (unsigned i = 0; i != VWidth; ++i) {
1458 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1459 Elts.push_back(Elt);
1460 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001462 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 }
1464
Dan Gohman488fbfc2008-09-09 18:11:14 +00001465 // Limit search depth.
1466 if (Depth == 10)
1467 return false;
1468
1469 // If multiple users are using the root value, procede with
1470 // simplification conservatively assuming that all elements
1471 // are needed.
1472 if (!V->hasOneUse()) {
1473 // Quit if we find multiple users of a non-root value though.
1474 // They'll be handled when it's their turn to be visited by
1475 // the main instcombine process.
1476 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 // TODO: Just compute the UndefElts information recursively.
1478 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001479
1480 // Conservatively assume that all elements are needed.
1481 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 }
1483
1484 Instruction *I = dyn_cast<Instruction>(V);
1485 if (!I) return false; // Only analyze instructions.
1486
1487 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001488 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001489 Value *TmpV;
1490 switch (I->getOpcode()) {
1491 default: break;
1492
1493 case Instruction::InsertElement: {
1494 // If this is a variable index, we don't know which element it overwrites.
1495 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001496 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 if (Idx == 0) {
1498 // Note that we can't propagate undef elt info, because we don't know
1499 // which elt is getting updated.
1500 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1501 UndefElts2, Depth+1);
1502 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1503 break;
1504 }
1505
1506 // If this is inserting an element that isn't demanded, remove this
1507 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001508 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001509 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 return AddSoonDeadInstToWorklist(*I, 0);
1511
1512 // Otherwise, the element inserted overwrites whatever was there, so the
1513 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001514 APInt DemandedElts2 = DemandedElts;
1515 DemandedElts2.clear(IdxNo);
1516 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 UndefElts, Depth+1);
1518 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519
1520 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001521 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001522 break;
1523 }
1524 case Instruction::ShuffleVector: {
1525 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001526 uint64_t LHSVWidth =
1527 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001528 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001529 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001530 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001531 unsigned MaskVal = Shuffle->getMaskValue(i);
1532 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001533 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001534 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001535 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001536 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001537 else
Evan Cheng388df622009-02-03 10:05:09 +00001538 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001539 }
1540 }
1541 }
1542
Nate Begeman7b254672009-02-11 22:36:25 +00001543 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001544 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001545 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001546 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547
Nate Begeman7b254672009-02-11 22:36:25 +00001548 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001549 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1550 UndefElts3, Depth+1);
1551 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1552
1553 bool NewUndefElts = false;
1554 for (unsigned i = 0; i < VWidth; i++) {
1555 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001556 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001557 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001558 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001559 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001560 NewUndefElts = true;
1561 UndefElts.set(i);
1562 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001564 if (UndefElts3[MaskVal - LHSVWidth]) {
1565 NewUndefElts = true;
1566 UndefElts.set(i);
1567 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 }
1569 }
1570
1571 if (NewUndefElts) {
1572 // Add additional discovered undefs.
1573 std::vector<Constant*> Elts;
1574 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001575 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 Elts.push_back(UndefValue::get(Type::Int32Ty));
1577 else
1578 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1579 Shuffle->getMaskValue(i)));
1580 }
1581 I->setOperand(2, ConstantVector::get(Elts));
1582 MadeChange = true;
1583 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001584 break;
1585 }
Chris Lattner69878332007-04-14 22:29:23 +00001586 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001587 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001588 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1589 if (!VTy) break;
1590 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001591 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001592 unsigned Ratio;
1593
1594 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001595 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001596 // elements as are demanded of us.
1597 Ratio = 1;
1598 InputDemandedElts = DemandedElts;
1599 } else if (VWidth > InVWidth) {
1600 // Untested so far.
1601 break;
1602
1603 // If there are more elements in the result than there are in the source,
1604 // then an input element is live if any of the corresponding output
1605 // elements are live.
1606 Ratio = VWidth/InVWidth;
1607 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001608 if (DemandedElts[OutIdx])
1609 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001610 }
1611 } else {
1612 // Untested so far.
1613 break;
1614
1615 // If there are more elements in the source than there are in the result,
1616 // then an input element is live if the corresponding output element is
1617 // live.
1618 Ratio = InVWidth/VWidth;
1619 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001620 if (DemandedElts[InIdx/Ratio])
1621 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001622 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001623
Chris Lattner69878332007-04-14 22:29:23 +00001624 // div/rem demand all inputs, because they don't want divide by zero.
1625 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1626 UndefElts2, Depth+1);
1627 if (TmpV) {
1628 I->setOperand(0, TmpV);
1629 MadeChange = true;
1630 }
1631
1632 UndefElts = UndefElts2;
1633 if (VWidth > InVWidth) {
1634 assert(0 && "Unimp");
1635 // If there are more elements in the result than there are in the source,
1636 // then an output element is undef if the corresponding input element is
1637 // undef.
1638 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001639 if (UndefElts2[OutIdx/Ratio])
1640 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001641 } else if (VWidth < InVWidth) {
1642 assert(0 && "Unimp");
1643 // If there are more elements in the source than there are in the result,
1644 // then a result element is undef if all of the corresponding input
1645 // elements are undef.
1646 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1647 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001648 if (!UndefElts2[InIdx]) // Not undef?
1649 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001650 }
1651 break;
1652 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001653 case Instruction::And:
1654 case Instruction::Or:
1655 case Instruction::Xor:
1656 case Instruction::Add:
1657 case Instruction::Sub:
1658 case Instruction::Mul:
1659 // div/rem demand all inputs, because they don't want divide by zero.
1660 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1661 UndefElts, Depth+1);
1662 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1663 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1664 UndefElts2, Depth+1);
1665 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1666
1667 // Output elements are undefined if both are undefined. Consider things
1668 // like undef&0. The result is known zero, not undef.
1669 UndefElts &= UndefElts2;
1670 break;
1671
1672 case Instruction::Call: {
1673 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1674 if (!II) break;
1675 switch (II->getIntrinsicID()) {
1676 default: break;
1677
1678 // Binary vector operations that work column-wise. A dest element is a
1679 // function of the corresponding input elements from the two inputs.
1680 case Intrinsic::x86_sse_sub_ss:
1681 case Intrinsic::x86_sse_mul_ss:
1682 case Intrinsic::x86_sse_min_ss:
1683 case Intrinsic::x86_sse_max_ss:
1684 case Intrinsic::x86_sse2_sub_sd:
1685 case Intrinsic::x86_sse2_mul_sd:
1686 case Intrinsic::x86_sse2_min_sd:
1687 case Intrinsic::x86_sse2_max_sd:
1688 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1689 UndefElts, Depth+1);
1690 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1691 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1692 UndefElts2, Depth+1);
1693 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1694
1695 // If only the low elt is demanded and this is a scalarizable intrinsic,
1696 // scalarize it now.
1697 if (DemandedElts == 1) {
1698 switch (II->getIntrinsicID()) {
1699 default: break;
1700 case Intrinsic::x86_sse_sub_ss:
1701 case Intrinsic::x86_sse_mul_ss:
1702 case Intrinsic::x86_sse2_sub_sd:
1703 case Intrinsic::x86_sse2_mul_sd:
1704 // TODO: Lower MIN/MAX/ABS/etc
1705 Value *LHS = II->getOperand(1);
1706 Value *RHS = II->getOperand(2);
1707 // Extract the element as scalars.
1708 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1709 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1710
1711 switch (II->getIntrinsicID()) {
1712 default: assert(0 && "Case stmts out of sync!");
1713 case Intrinsic::x86_sse_sub_ss:
1714 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001715 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001716 II->getName()), *II);
1717 break;
1718 case Intrinsic::x86_sse_mul_ss:
1719 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001720 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001721 II->getName()), *II);
1722 break;
1723 }
1724
1725 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001726 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1727 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001728 InsertNewInstBefore(New, *II);
1729 AddSoonDeadInstToWorklist(*II, 0);
1730 return New;
1731 }
1732 }
1733
1734 // Output elements are undefined if both are undefined. Consider things
1735 // like undef&0. The result is known zero, not undef.
1736 UndefElts &= UndefElts2;
1737 break;
1738 }
1739 break;
1740 }
1741 }
1742 return MadeChange ? I : 0;
1743}
1744
Dan Gohman45b4e482008-05-19 22:14:15 +00001745
Chris Lattner564a7272003-08-13 19:01:45 +00001746/// AssociativeOpt - Perform an optimization on an associative operator. This
1747/// function is designed to check a chain of associative operators for a
1748/// potential to apply a certain optimization. Since the optimization may be
1749/// applicable if the expression was reassociated, this checks the chain, then
1750/// reassociates the expression as necessary to expose the optimization
1751/// opportunity. This makes use of a special Functor, which must define
1752/// 'shouldApply' and 'apply' methods.
1753///
1754template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001755static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001756 unsigned Opcode = Root.getOpcode();
1757 Value *LHS = Root.getOperand(0);
1758
1759 // Quick check, see if the immediate LHS matches...
1760 if (F.shouldApply(LHS))
1761 return F.apply(Root);
1762
1763 // Otherwise, if the LHS is not of the same opcode as the root, return.
1764 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001765 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001766 // Should we apply this transform to the RHS?
1767 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1768
1769 // If not to the RHS, check to see if we should apply to the LHS...
1770 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1771 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1772 ShouldApply = true;
1773 }
1774
1775 // If the functor wants to apply the optimization to the RHS of LHSI,
1776 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1777 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001778 // Now all of the instructions are in the current basic block, go ahead
1779 // and perform the reassociation.
1780 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1781
1782 // First move the selected RHS to the LHS of the root...
1783 Root.setOperand(0, LHSI->getOperand(1));
1784
1785 // Make what used to be the LHS of the root be the user of the root...
1786 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001787 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001788 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1789 return 0;
1790 }
Chris Lattner65725312004-04-16 18:08:07 +00001791 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001792 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001793 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001794 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001795 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001796
1797 // Now propagate the ExtraOperand down the chain of instructions until we
1798 // get to LHSI.
1799 while (TmpLHSI != LHSI) {
1800 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001801 // Move the instruction to immediately before the chain we are
1802 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001803 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001804 ARI = NextLHSI;
1805
Chris Lattner564a7272003-08-13 19:01:45 +00001806 Value *NextOp = NextLHSI->getOperand(1);
1807 NextLHSI->setOperand(1, ExtraOperand);
1808 TmpLHSI = NextLHSI;
1809 ExtraOperand = NextOp;
1810 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001811
Chris Lattner564a7272003-08-13 19:01:45 +00001812 // Now that the instructions are reassociated, have the functor perform
1813 // the transformation...
1814 return F.apply(Root);
1815 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001816
Chris Lattner564a7272003-08-13 19:01:45 +00001817 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1818 }
1819 return 0;
1820}
1821
Dan Gohman844731a2008-05-13 00:00:25 +00001822namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001823
Nick Lewycky02d639f2008-05-23 04:34:58 +00001824// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001825struct AddRHS {
1826 Value *RHS;
1827 AddRHS(Value *rhs) : RHS(rhs) {}
1828 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1829 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001830 return BinaryOperator::CreateShl(Add.getOperand(0),
1831 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001832 }
1833};
1834
1835// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1836// iff C1&C2 == 0
1837struct AddMaskingAnd {
1838 Constant *C2;
1839 AddMaskingAnd(Constant *c) : C2(c) {}
1840 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001841 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001842 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001843 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001844 }
1845 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001846 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001847 }
1848};
1849
Dan Gohman844731a2008-05-13 00:00:25 +00001850}
1851
Chris Lattner6e7ba452005-01-01 16:22:27 +00001852static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001853 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001854 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001855 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001856 }
1857
Chris Lattner2eefe512004-04-09 19:05:30 +00001858 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001859 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1860 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001861
Chris Lattner2eefe512004-04-09 19:05:30 +00001862 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1863 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001864 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1865 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001866 }
1867
1868 Value *Op0 = SO, *Op1 = ConstOperand;
1869 if (!ConstIsRHS)
1870 std::swap(Op0, Op1);
1871 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001872 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001873 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001874 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001875 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001876 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001877 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001878 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001879 abort();
1880 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001881 return IC->InsertNewInstBefore(New, I);
1882}
1883
1884// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1885// constant as the other operand, try to fold the binary operator into the
1886// select arguments. This also works for Cast instructions, which obviously do
1887// not have a second operand.
1888static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1889 InstCombiner *IC) {
1890 // Don't modify shared select instructions
1891 if (!SI->hasOneUse()) return 0;
1892 Value *TV = SI->getOperand(1);
1893 Value *FV = SI->getOperand(2);
1894
1895 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001896 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001897 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001898
Chris Lattner6e7ba452005-01-01 16:22:27 +00001899 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1900 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1901
Gabor Greif051a9502008-04-06 20:25:17 +00001902 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1903 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 }
1905 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001906}
1907
Chris Lattner4e998b22004-09-29 05:07:12 +00001908
1909/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1910/// node as operand #0, see if we can fold the instruction into the PHI (which
1911/// is only possible if all operands to the PHI are constants).
1912Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1913 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001914 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001915 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001916
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001917 // Check to see if all of the operands of the PHI are constants. If there is
1918 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001919 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001920 BasicBlock *NonConstBB = 0;
1921 for (unsigned i = 0; i != NumPHIValues; ++i)
1922 if (!isa<Constant>(PN->getIncomingValue(i))) {
1923 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001924 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001925 NonConstBB = PN->getIncomingBlock(i);
1926
1927 // If the incoming non-constant value is in I's block, we have an infinite
1928 // loop.
1929 if (NonConstBB == I.getParent())
1930 return 0;
1931 }
1932
1933 // If there is exactly one non-constant value, we can insert a copy of the
1934 // operation in that block. However, if this is a critical edge, we would be
1935 // inserting the computation one some other paths (e.g. inside a loop). Only
1936 // do this if the pred block is unconditionally branching into the phi block.
1937 if (NonConstBB) {
1938 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1939 if (!BI || !BI->isUnconditional()) return 0;
1940 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001941
1942 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001943 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001944 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001945 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001946 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001947
1948 // Next, add all of the operands to the PHI.
1949 if (I.getNumOperands() == 2) {
1950 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001951 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001952 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001953 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001954 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1955 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1956 else
1957 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001958 } else {
1959 assert(PN->getIncomingBlock(i) == NonConstBB);
1960 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001961 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001962 PN->getIncomingValue(i), C, "phitmp",
1963 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001964 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001965 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001966 CI->getPredicate(),
1967 PN->getIncomingValue(i), C, "phitmp",
1968 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001969 else
1970 assert(0 && "Unknown binop!");
1971
Chris Lattnerdbab3862007-03-02 21:28:56 +00001972 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001973 }
1974 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001975 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001976 } else {
1977 CastInst *CI = cast<CastInst>(&I);
1978 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001979 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001980 Value *InV;
1981 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001982 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001983 } else {
1984 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001985 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001986 I.getType(), "phitmp",
1987 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001988 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 }
1990 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001991 }
1992 }
1993 return ReplaceInstUsesWith(I, NewPN);
1994}
1995
Chris Lattner2454a2e2008-01-29 06:52:45 +00001996
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001997/// WillNotOverflowSignedAdd - Return true if we can prove that:
1998/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1999/// This basically requires proving that the add in the original type would not
2000/// overflow to change the sign bit or have a carry out.
2001bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2002 // There are different heuristics we can use for this. Here are some simple
2003 // ones.
2004
2005 // Add has the property that adding any two 2's complement numbers can only
2006 // have one carry bit which can change a sign. As such, if LHS and RHS each
2007 // have at least two sign bits, we know that the addition of the two values will
2008 // sign extend fine.
2009 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2010 return true;
2011
2012
2013 // If one of the operands only has one non-zero bit, and if the other operand
2014 // has a known-zero bit in a more significant place than it (not including the
2015 // sign bit) the ripple may go up to and fill the zero, but won't change the
2016 // sign. For example, (X & ~4) + 1.
2017
2018 // TODO: Implement.
2019
2020 return false;
2021}
2022
Chris Lattner2454a2e2008-01-29 06:52:45 +00002023
Chris Lattner7e708292002-06-25 16:13:24 +00002024Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002025 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002026 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002027
Chris Lattner66331a42004-04-10 22:01:55 +00002028 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002029 // X + undef -> undef
2030 if (isa<UndefValue>(RHS))
2031 return ReplaceInstUsesWith(I, RHS);
2032
Chris Lattner66331a42004-04-10 22:01:55 +00002033 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002034 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002035 if (RHSC->isNullValue())
2036 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002037 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002038 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2039 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002040 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002041 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002042
Chris Lattner66331a42004-04-10 22:01:55 +00002043 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002044 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002045 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002046 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002047 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002048 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002049
2050 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2051 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002052 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2053 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002054
2055 // zext(i1) - 1 -> select i1, 0, -1
2056 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2057 if (CI->isAllOnesValue() &&
2058 ZI->getOperand(0)->getType() == Type::Int1Ty)
2059 return SelectInst::Create(ZI->getOperand(0),
2060 Constant::getNullValue(I.getType()),
2061 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002062 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002063
2064 if (isa<PHINode>(LHS))
2065 if (Instruction *NV = FoldOpIntoPhi(I))
2066 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002067
Chris Lattner4f637d42006-01-06 17:59:59 +00002068 ConstantInt *XorRHS = 0;
2069 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002070 if (isa<ConstantInt>(RHSC) &&
2071 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002072 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002073 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002074
Zhou Sheng4351c642007-04-02 08:20:41 +00002075 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002076 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2077 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002078 do {
2079 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002080 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2081 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002082 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2083 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002084 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002085 if (!MaskedValueIsZero(XorLHS,
2086 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002087 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002088 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002089 }
2090 }
2091 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002092 C0080Val = APIntOps::lshr(C0080Val, Size);
2093 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2094 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002095
Reid Spencer35c38852007-03-28 01:36:16 +00002096 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002097 // with funny bit widths then this switch statement should be removed. It
2098 // is just here to get the size of the "middle" type back up to something
2099 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002100 const Type *MiddleType = 0;
2101 switch (Size) {
2102 default: break;
2103 case 32: MiddleType = Type::Int32Ty; break;
2104 case 16: MiddleType = Type::Int16Ty; break;
2105 case 8: MiddleType = Type::Int8Ty; break;
2106 }
2107 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002108 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002109 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002110 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002111 }
2112 }
Chris Lattner66331a42004-04-10 22:01:55 +00002113 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002114
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002115 if (I.getType() == Type::Int1Ty)
2116 return BinaryOperator::CreateXor(LHS, RHS);
2117
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002118 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002119 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002120 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002121
2122 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2123 if (RHSI->getOpcode() == Instruction::Sub)
2124 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2125 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2126 }
2127 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2128 if (LHSI->getOpcode() == Instruction::Sub)
2129 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2130 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2131 }
Robert Bocchino71698282004-07-27 21:02:21 +00002132 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002133
Chris Lattner5c4afb92002-05-08 22:46:53 +00002134 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002135 // -A + -B --> -(A + B)
2136 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002137 if (LHS->getType()->isIntOrIntVector()) {
2138 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002139 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002140 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002141 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002142 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002143 }
2144
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002145 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002146 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002147
2148 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002149 if (!isa<Constant>(RHS))
2150 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002151 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002152
Misha Brukmanfd939082005-04-21 23:48:37 +00002153
Chris Lattner50af16a2004-11-13 19:50:12 +00002154 ConstantInt *C2;
2155 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2156 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002157 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002158
2159 // X*C1 + X*C2 --> X * (C1+C2)
2160 ConstantInt *C1;
2161 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002162 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002163 }
2164
2165 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002166 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002167 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002168
Chris Lattnere617c9e2007-01-05 02:17:46 +00002169 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002170 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2171 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002172
Chris Lattnerad3448c2003-02-18 19:57:07 +00002173
Chris Lattner564a7272003-08-13 19:01:45 +00002174 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002175 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002176 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2177 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002178
2179 // A+B --> A|B iff A and B have no bits set in common.
2180 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2181 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2182 APInt LHSKnownOne(IT->getBitWidth(), 0);
2183 APInt LHSKnownZero(IT->getBitWidth(), 0);
2184 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2185 if (LHSKnownZero != 0) {
2186 APInt RHSKnownOne(IT->getBitWidth(), 0);
2187 APInt RHSKnownZero(IT->getBitWidth(), 0);
2188 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2189
2190 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002191 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002192 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002193 }
2194 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002195
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002196 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002197 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002198 Value *W, *X, *Y, *Z;
2199 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2200 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2201 if (W != Y) {
2202 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002203 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002204 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002205 std::swap(W, X);
2206 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002207 std::swap(Y, Z);
2208 std::swap(W, X);
2209 }
2210 }
2211
2212 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002213 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002214 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002215 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002216 }
2217 }
2218 }
2219
Chris Lattner6b032052003-10-02 15:11:26 +00002220 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002221 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002222 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002223 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002224
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002225 // (X & FF00) + xx00 -> (X+xx00) & FF00
2226 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002227 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002228 if (Anded == CRHS) {
2229 // See if all bits from the first bit set in the Add RHS up are included
2230 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002231 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002232
2233 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002234 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002235
2236 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002237 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002238
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002239 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2240 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002241 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002242 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002243 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002244 }
2245 }
2246 }
2247
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002248 // Try to fold constant add into select arguments.
2249 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002250 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002251 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002252 }
2253
Reid Spencer1628cec2006-10-26 06:15:43 +00002254 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002255 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002256 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002257 CastInst *CI = dyn_cast<CastInst>(LHS);
2258 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002259 if (!CI) {
2260 CI = dyn_cast<CastInst>(RHS);
2261 Other = LHS;
2262 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002263 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002264 (CI->getType()->getPrimitiveSizeInBits() ==
2265 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002266 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002267 unsigned AS =
2268 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002269 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2270 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002271 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002272 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002273 }
2274 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002275
Chris Lattner42790482007-12-20 01:56:58 +00002276 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 {
2278 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002279 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280 if (!SI) {
2281 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002282 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283 }
Chris Lattner42790482007-12-20 01:56:58 +00002284 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002285 Value *TV = SI->getTrueValue();
2286 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288
2289 // Can we fold the add into the argument of the select?
2290 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002291 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2292 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002293 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002294 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2295 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002296 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002297 }
2298 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002299
2300 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2301 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2302 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2303 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002304
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002305 // Check for (add (sext x), y), see if we can merge this into an
2306 // integer add followed by a sext.
2307 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2308 // (add (sext x), cst) --> (sext (add x, cst'))
2309 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2310 Constant *CI =
2311 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2312 if (LHSConv->hasOneUse() &&
2313 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2314 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2315 // Insert the new, smaller add.
2316 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2317 CI, "addconv");
2318 InsertNewInstBefore(NewAdd, I);
2319 return new SExtInst(NewAdd, I.getType());
2320 }
2321 }
2322
2323 // (add (sext x), (sext y)) --> (sext (add int x, y))
2324 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2325 // Only do this if x/y have the same type, if at last one of them has a
2326 // single use (so we don't increase the number of sexts), and if the
2327 // integer add will not overflow.
2328 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2329 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2330 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2331 RHSConv->getOperand(0))) {
2332 // Insert the new integer add.
2333 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2334 RHSConv->getOperand(0),
2335 "addconv");
2336 InsertNewInstBefore(NewAdd, I);
2337 return new SExtInst(NewAdd, I.getType());
2338 }
2339 }
2340 }
2341
2342 // Check for (add double (sitofp x), y), see if we can merge this into an
2343 // integer add followed by a promotion.
2344 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2345 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2346 // ... if the constant fits in the integer value. This is useful for things
2347 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2348 // requires a constant pool load, and generally allows the add to be better
2349 // instcombined.
2350 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2351 Constant *CI =
2352 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2353 if (LHSConv->hasOneUse() &&
2354 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2355 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2356 // Insert the new integer add.
2357 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2358 CI, "addconv");
2359 InsertNewInstBefore(NewAdd, I);
2360 return new SIToFPInst(NewAdd, I.getType());
2361 }
2362 }
2363
2364 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2365 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2366 // Only do this if x/y have the same type, if at last one of them has a
2367 // single use (so we don't increase the number of int->fp conversions),
2368 // and if the integer add will not overflow.
2369 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2370 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2371 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2372 RHSConv->getOperand(0))) {
2373 // Insert the new integer add.
2374 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2375 RHSConv->getOperand(0),
2376 "addconv");
2377 InsertNewInstBefore(NewAdd, I);
2378 return new SIToFPInst(NewAdd, I.getType());
2379 }
2380 }
2381 }
2382
Chris Lattner7e708292002-06-25 16:13:24 +00002383 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002384}
2385
Chris Lattner7e708292002-06-25 16:13:24 +00002386Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002387 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002388
Chris Lattnerd137ab42008-07-17 06:07:20 +00002389 if (Op0 == Op1 && // sub X, X -> 0
2390 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002392
Chris Lattner233f7dc2002-08-12 21:17:25 +00002393 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002394 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002395 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002396
Chris Lattnere87597f2004-10-16 18:11:37 +00002397 if (isa<UndefValue>(Op0))
2398 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2399 if (isa<UndefValue>(Op1))
2400 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2401
Chris Lattnerd65460f2003-11-05 01:06:05 +00002402 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2403 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002404 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002405 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002406
Chris Lattnerd65460f2003-11-05 01:06:05 +00002407 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002408 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002409 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002410 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002411
Chris Lattner76b7a062007-01-15 07:02:54 +00002412 // -(X >>u 31) -> (X >>s 31)
2413 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002414 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002415 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002416 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002417 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002418 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002419 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002420 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002421 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002422 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002423 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002424 }
2425 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002426 }
2427 else if (SI->getOpcode() == Instruction::AShr) {
2428 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2429 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002430 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002431 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002432 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002434 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002435 }
2436 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002437 }
2438 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002439 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002440
2441 // Try to fold constant sub into select arguments.
2442 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002443 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002444 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002445 }
2446
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002447 if (I.getType() == Type::Int1Ty)
2448 return BinaryOperator::CreateXor(Op0, Op1);
2449
Chris Lattner43d84d62005-04-07 16:15:25 +00002450 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2451 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002452 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002453 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002455 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002456 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002457 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2458 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2459 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002460 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002461 Op1I->getOperand(0));
2462 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002463 }
2464
Chris Lattnerfd059242003-10-15 16:48:29 +00002465 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002466 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2467 // is not used by anyone else...
2468 //
Chris Lattner0517e722004-02-02 20:09:56 +00002469 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002470 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002471 // Swap the two operands of the subexpr...
2472 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2473 Op1I->setOperand(0, IIOp1);
2474 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002475
Chris Lattnera2881962003-02-18 19:28:33 +00002476 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002477 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002478 }
2479
2480 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2481 //
2482 if (Op1I->getOpcode() == Instruction::And &&
2483 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2484 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2485
Chris Lattnerf523d062004-06-09 05:08:07 +00002486 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002487 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2488 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002489 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002490
Reid Spencerac5209e2006-10-16 23:08:08 +00002491 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002492 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002493 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002494 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002495 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002496 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002497 ConstantExpr::getNeg(DivRHS));
2498
Chris Lattnerad3448c2003-02-18 19:57:07 +00002499 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002500 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002501 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002502 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002504 }
Chris Lattner40371712002-05-09 01:29:19 +00002505 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002506 }
Chris Lattnera2881962003-02-18 19:28:33 +00002507
Chris Lattner9919e3d2006-12-02 00:13:08 +00002508 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002509 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002510 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002511 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2512 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2513 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2514 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002515 } else if (Op0I->getOpcode() == Instruction::Sub) {
2516 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002517 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002518 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002519 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002520
Chris Lattner50af16a2004-11-13 19:50:12 +00002521 ConstantInt *C1;
2522 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002523 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002525
Chris Lattner50af16a2004-11-13 19:50:12 +00002526 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2527 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002528 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002529 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002530 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002531}
2532
Chris Lattnera0141b92007-07-15 20:42:37 +00002533/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2534/// comparison only checks the sign bit. If it only checks the sign bit, set
2535/// TrueIfSigned if the result of the comparison is true when the input value is
2536/// signed.
2537static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2538 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002539 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002540 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2541 TrueIfSigned = true;
2542 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002543 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2544 TrueIfSigned = true;
2545 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002546 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2547 TrueIfSigned = false;
2548 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002549 case ICmpInst::ICMP_UGT:
2550 // True if LHS u> RHS and RHS == high-bit-mask - 1
2551 TrueIfSigned = true;
2552 return RHS->getValue() ==
2553 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2554 case ICmpInst::ICMP_UGE:
2555 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2556 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002557 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002558 default:
2559 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002560 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002561}
2562
Chris Lattner7e708292002-06-25 16:13:24 +00002563Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002564 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002565 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002566
Chris Lattnere87597f2004-10-16 18:11:37 +00002567 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2568 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2569
Chris Lattner233f7dc2002-08-12 21:17:25 +00002570 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002571 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2572 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002573
2574 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002575 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002576 if (SI->getOpcode() == Instruction::Shl)
2577 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002579 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002580
Zhou Sheng843f07672007-04-19 05:39:12 +00002581 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002582 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2583 if (CI->equalsInt(1)) // X * 1 == X
2584 return ReplaceInstUsesWith(I, Op0);
2585 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002586 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002587
Zhou Sheng97b52c22007-03-29 01:57:21 +00002588 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002589 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002590 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002591 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002592 }
Robert Bocchino71698282004-07-27 21:02:21 +00002593 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002594 if (Op1F->isNullValue())
2595 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002596
Chris Lattnera2881962003-02-18 19:28:33 +00002597 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2598 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002599 if (Op1F->isExactlyValue(1.0))
2600 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2601 } else if (isa<VectorType>(Op1->getType())) {
2602 if (isa<ConstantAggregateZero>(Op1))
2603 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002604
2605 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2606 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2607 return BinaryOperator::CreateNeg(Op0, I.getName());
2608
2609 // As above, vector X*splat(1.0) -> X in all defined cases.
2610 if (Constant *Splat = Op1V->getSplatValue()) {
2611 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2612 if (F->isExactlyValue(1.0))
2613 return ReplaceInstUsesWith(I, Op0);
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2615 if (CI->equalsInt(1))
2616 return ReplaceInstUsesWith(I, Op0);
2617 }
2618 }
Chris Lattnera2881962003-02-18 19:28:33 +00002619 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002620
2621 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2622 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002623 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002624 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002625 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002626 Op1, "tmp");
2627 InsertNewInstBefore(Add, I);
2628 Value *C1C2 = ConstantExpr::getMul(Op1,
2629 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002630 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002631
2632 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002633
2634 // Try to fold constant mul into select arguments.
2635 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002636 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002637 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002638
2639 if (isa<PHINode>(Op0))
2640 if (Instruction *NV = FoldOpIntoPhi(I))
2641 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002642 }
2643
Chris Lattnera4f445b2003-03-10 23:23:04 +00002644 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2645 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002646 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002647
Nick Lewycky0c730792008-11-21 07:33:58 +00002648 // (X / Y) * Y = X - (X % Y)
2649 // (X / Y) * -Y = (X % Y) - X
2650 {
2651 Value *Op1 = I.getOperand(1);
2652 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2653 if (!BO ||
2654 (BO->getOpcode() != Instruction::UDiv &&
2655 BO->getOpcode() != Instruction::SDiv)) {
2656 Op1 = Op0;
2657 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2658 }
2659 Value *Neg = dyn_castNegVal(Op1);
2660 if (BO && BO->hasOneUse() &&
2661 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2662 (BO->getOpcode() == Instruction::UDiv ||
2663 BO->getOpcode() == Instruction::SDiv)) {
2664 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2665
2666 Instruction *Rem;
2667 if (BO->getOpcode() == Instruction::UDiv)
2668 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2669 else
2670 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2671
2672 InsertNewInstBefore(Rem, I);
2673 Rem->takeName(BO);
2674
2675 if (Op1BO == Op1)
2676 return BinaryOperator::CreateSub(Op0BO, Rem);
2677 else
2678 return BinaryOperator::CreateSub(Rem, Op0BO);
2679 }
2680 }
2681
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002682 if (I.getType() == Type::Int1Ty)
2683 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2684
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002685 // If one of the operands of the multiply is a cast from a boolean value, then
2686 // we know the bool is either zero or one, so this is a 'masking' multiply.
2687 // See if we can simplify things based on how the boolean was originally
2688 // formed.
2689 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002690 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002691 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002692 BoolCast = CI;
2693 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002694 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002695 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002696 BoolCast = CI;
2697 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002698 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002699 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2700 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002701 bool TIS = false;
2702
Reid Spencere4d87aa2006-12-23 06:05:41 +00002703 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002704 // multiply into a shift/and combination.
2705 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002706 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2707 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002708 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002709 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002710 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002711 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002712 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002713 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002714 BoolCast->getOperand(0)->getName()+
2715 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002716
2717 // If the multiply type is not the same as the source type, sign extend
2718 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002719 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002720 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2721 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002722 Instruction::CastOps opcode =
2723 (SrcBits == DstBits ? Instruction::BitCast :
2724 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2725 V = InsertCastBefore(opcode, V, I.getType(), I);
2726 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002727
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002728 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002729 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002730 }
2731 }
2732 }
2733
Chris Lattner7e708292002-06-25 16:13:24 +00002734 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002735}
2736
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002737/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2738/// instruction.
2739bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2740 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2741
2742 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2743 int NonNullOperand = -1;
2744 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2745 if (ST->isNullValue())
2746 NonNullOperand = 2;
2747 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2748 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2749 if (ST->isNullValue())
2750 NonNullOperand = 1;
2751
2752 if (NonNullOperand == -1)
2753 return false;
2754
2755 Value *SelectCond = SI->getOperand(0);
2756
2757 // Change the div/rem to use 'Y' instead of the select.
2758 I.setOperand(1, SI->getOperand(NonNullOperand));
2759
2760 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2761 // problem. However, the select, or the condition of the select may have
2762 // multiple uses. Based on our knowledge that the operand must be non-zero,
2763 // propagate the known value for the select into other uses of it, and
2764 // propagate a known value of the condition into its other users.
2765
2766 // If the select and condition only have a single use, don't bother with this,
2767 // early exit.
2768 if (SI->use_empty() && SelectCond->hasOneUse())
2769 return true;
2770
2771 // Scan the current block backward, looking for other uses of SI.
2772 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2773
2774 while (BBI != BBFront) {
2775 --BBI;
2776 // If we found a call to a function, we can't assume it will return, so
2777 // information from below it cannot be propagated above it.
2778 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2779 break;
2780
2781 // Replace uses of the select or its condition with the known values.
2782 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2783 I != E; ++I) {
2784 if (*I == SI) {
2785 *I = SI->getOperand(NonNullOperand);
2786 AddToWorkList(BBI);
2787 } else if (*I == SelectCond) {
2788 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2789 ConstantInt::getFalse();
2790 AddToWorkList(BBI);
2791 }
2792 }
2793
2794 // If we past the instruction, quit looking for it.
2795 if (&*BBI == SI)
2796 SI = 0;
2797 if (&*BBI == SelectCond)
2798 SelectCond = 0;
2799
2800 // If we ran out of things to eliminate, break out of the loop.
2801 if (SelectCond == 0 && SI == 0)
2802 break;
2803
2804 }
2805 return true;
2806}
2807
2808
Reid Spencer1628cec2006-10-26 06:15:43 +00002809/// This function implements the transforms on div instructions that work
2810/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2811/// used by the visitors to those instructions.
2812/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002813Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002815
Chris Lattner50b2ca42008-02-19 06:12:18 +00002816 // undef / X -> 0 for integer.
2817 // undef / X -> undef for FP (the undef could be a snan).
2818 if (isa<UndefValue>(Op0)) {
2819 if (Op0->getType()->isFPOrFPVector())
2820 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002821 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002822 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002823
2824 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002825 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002826 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002827
Reid Spencer1628cec2006-10-26 06:15:43 +00002828 return 0;
2829}
Misha Brukmanfd939082005-04-21 23:48:37 +00002830
Reid Spencer1628cec2006-10-26 06:15:43 +00002831/// This function implements the transforms common to both integer division
2832/// instructions (udiv and sdiv). It is called by the visitors to those integer
2833/// division instructions.
2834/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002835Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002836 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2837
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002838 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002839 if (Op0 == Op1) {
2840 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2841 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2842 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2843 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2844 }
2845
2846 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2847 return ReplaceInstUsesWith(I, CI);
2848 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002849
Reid Spencer1628cec2006-10-26 06:15:43 +00002850 if (Instruction *Common = commonDivTransforms(I))
2851 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002852
2853 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2854 // This does not apply for fdiv.
2855 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2856 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002857
2858 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2859 // div X, 1 == X
2860 if (RHS->equalsInt(1))
2861 return ReplaceInstUsesWith(I, Op0);
2862
2863 // (X / C1) / C2 -> X / (C1*C2)
2864 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2865 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2866 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002867 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2868 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2869 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002870 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002871 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002872 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002873
Reid Spencerbca0e382007-03-23 20:05:17 +00002874 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002875 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2876 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2877 return R;
2878 if (isa<PHINode>(Op0))
2879 if (Instruction *NV = FoldOpIntoPhi(I))
2880 return NV;
2881 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002882 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002883
Chris Lattnera2881962003-02-18 19:28:33 +00002884 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002885 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002886 if (LHS->equalsInt(0))
2887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2888
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002889 // It can't be division by zero, hence it must be division by one.
2890 if (I.getType() == Type::Int1Ty)
2891 return ReplaceInstUsesWith(I, Op0);
2892
Nick Lewycky895f0852008-11-27 20:21:08 +00002893 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2894 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2895 // div X, 1 == X
2896 if (X->isOne())
2897 return ReplaceInstUsesWith(I, Op0);
2898 }
2899
Reid Spencer1628cec2006-10-26 06:15:43 +00002900 return 0;
2901}
2902
2903Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2904 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2905
2906 // Handle the integer div common cases
2907 if (Instruction *Common = commonIDivTransforms(I))
2908 return Common;
2909
Reid Spencer1628cec2006-10-26 06:15:43 +00002910 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002911 // X udiv C^2 -> X >> C
2912 // Check to see if this is an unsigned division with an exact power of 2,
2913 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002914 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002915 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002916 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002917
2918 // X udiv C, where C >= signbit
2919 if (C->getValue().isNegative()) {
2920 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2921 I);
2922 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2923 ConstantInt::get(I.getType(), 1));
2924 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002925 }
2926
2927 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002928 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002929 if (RHSI->getOpcode() == Instruction::Shl &&
2930 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002931 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002932 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002933 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002934 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002935 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002936 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002937 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002938 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002939 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002940 }
2941 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002942 }
2943
Reid Spencer1628cec2006-10-26 06:15:43 +00002944 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2945 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002946 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002947 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002948 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002949 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002950 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002951 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002952 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002953 // Construct the "on true" case of the select
2954 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002955 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002956 Op0, TC, SI->getName()+".t");
2957 TSI = InsertNewInstBefore(TSI, I);
2958
2959 // Construct the "on false" case of the select
2960 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002961 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002962 Op0, FC, SI->getName()+".f");
2963 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002964
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002965 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002966 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002967 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002968 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002969 return 0;
2970}
2971
Reid Spencer1628cec2006-10-26 06:15:43 +00002972Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2973 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2974
2975 // Handle the integer div common cases
2976 if (Instruction *Common = commonIDivTransforms(I))
2977 return Common;
2978
2979 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2980 // sdiv X, -1 == -X
2981 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002982 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002983 }
2984
2985 // If the sign bits of both operands are zero (i.e. we can prove they are
2986 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002987 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002988 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002989 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002990 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002991 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002992 }
2993 }
2994
2995 return 0;
2996}
2997
2998Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2999 return commonDivTransforms(I);
3000}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003001
Reid Spencer0a783f72006-11-02 01:53:59 +00003002/// This function implements the transforms on rem instructions that work
3003/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3004/// is used by the visitors to those instructions.
3005/// @brief Transforms common to all three rem instructions
3006Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003008
Chris Lattner50b2ca42008-02-19 06:12:18 +00003009 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3010 if (I.getType()->isFPOrFPVector())
3011 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003012 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003013 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003014 if (isa<UndefValue>(Op1))
3015 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003016
3017 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003018 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3019 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003020
Reid Spencer0a783f72006-11-02 01:53:59 +00003021 return 0;
3022}
3023
3024/// This function implements the transforms common to both integer remainder
3025/// instructions (urem and srem). It is called by the visitors to those integer
3026/// remainder instructions.
3027/// @brief Common integer remainder transforms
3028Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3029 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3030
3031 if (Instruction *common = commonRemTransforms(I))
3032 return common;
3033
Dale Johannesened6af242009-01-21 00:35:19 +00003034 // 0 % X == 0 for integer, we don't need to preserve faults!
3035 if (Constant *LHS = dyn_cast<Constant>(Op0))
3036 if (LHS->isNullValue())
3037 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3038
Chris Lattner857e8cd2004-12-12 21:48:58 +00003039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003040 // X % 0 == undef, we don't need to preserve faults!
3041 if (RHS->equalsInt(0))
3042 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3043
Chris Lattnera2881962003-02-18 19:28:33 +00003044 if (RHS->equalsInt(1)) // X % 1 == 0
3045 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3046
Chris Lattner97943922006-02-28 05:49:21 +00003047 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3048 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3049 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3050 return R;
3051 } else if (isa<PHINode>(Op0I)) {
3052 if (Instruction *NV = FoldOpIntoPhi(I))
3053 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003054 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003055
3056 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003057 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003058 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003059 }
Chris Lattnera2881962003-02-18 19:28:33 +00003060 }
3061
Reid Spencer0a783f72006-11-02 01:53:59 +00003062 return 0;
3063}
3064
3065Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068 if (Instruction *common = commonIRemTransforms(I))
3069 return common;
3070
3071 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3072 // X urem C^2 -> X and C
3073 // Check to see if this is an unsigned remainder with an exact power of 2,
3074 // if so, convert to a bitwise and.
3075 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003076 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003077 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003078 }
3079
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003080 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003081 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3082 if (RHSI->getOpcode() == Instruction::Shl &&
3083 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003084 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003085 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003086 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003087 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003088 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003089 }
3090 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003091 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003092
Reid Spencer0a783f72006-11-02 01:53:59 +00003093 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3094 // where C1&C2 are powers of two.
3095 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3096 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3097 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3098 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003099 if ((STO->getValue().isPowerOf2()) &&
3100 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003101 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003102 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003103 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003104 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003105 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003106 }
3107 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003108 }
3109
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110 return 0;
3111}
3112
Reid Spencer0a783f72006-11-02 01:53:59 +00003113Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115
Dan Gohmancff55092007-11-05 23:16:33 +00003116 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003117 if (Instruction *common = commonIRemTransforms(I))
3118 return common;
3119
3120 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003121 if (!isa<Constant>(RHSNeg) ||
3122 (isa<ConstantInt>(RHSNeg) &&
3123 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003124 // X % -Y -> X % Y
3125 AddUsesToWorkList(I);
3126 I.setOperand(1, RHSNeg);
3127 return &I;
3128 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003129
Dan Gohmancff55092007-11-05 23:16:33 +00003130 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003131 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003132 if (I.getType()->isInteger()) {
3133 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3134 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3135 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003136 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003137 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003138 }
3139
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003140 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003141 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3142 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003143
Nick Lewycky9dce8732008-12-20 16:48:00 +00003144 bool hasNegative = false;
3145 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3146 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3147 if (RHS->getValue().isNegative())
3148 hasNegative = true;
3149
3150 if (hasNegative) {
3151 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003152 for (unsigned i = 0; i != VWidth; ++i) {
3153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3154 if (RHS->getValue().isNegative())
3155 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3156 else
3157 Elts[i] = RHS;
3158 }
3159 }
3160
3161 Constant *NewRHSV = ConstantVector::get(Elts);
3162 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003163 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003164 I.setOperand(1, NewRHSV);
3165 return &I;
3166 }
3167 }
3168 }
3169
Reid Spencer0a783f72006-11-02 01:53:59 +00003170 return 0;
3171}
3172
3173Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003174 return commonRemTransforms(I);
3175}
3176
Chris Lattner457dd822004-06-09 07:59:58 +00003177// isOneBitSet - Return true if there is exactly one bit set in the specified
3178// constant.
3179static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003180 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003181}
3182
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003183// isHighOnes - Return true if the constant is of the form 1+0+.
3184// This is the same as lowones(~X).
3185static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003186 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003187}
3188
Reid Spencere4d87aa2006-12-23 06:05:41 +00003189/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003190/// are carefully arranged to allow folding of expressions such as:
3191///
3192/// (A < B) | (A > B) --> (A != B)
3193///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003194/// Note that this is only valid if the first and second predicates have the
3195/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003196///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003197/// Three bits are used to represent the condition, as follows:
3198/// 0 A > B
3199/// 1 A == B
3200/// 2 A < B
3201///
3202/// <=> Value Definition
3203/// 000 0 Always false
3204/// 001 1 A > B
3205/// 010 2 A == B
3206/// 011 3 A >= B
3207/// 100 4 A < B
3208/// 101 5 A != B
3209/// 110 6 A <= B
3210/// 111 7 Always true
3211///
3212static unsigned getICmpCode(const ICmpInst *ICI) {
3213 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003214 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003215 case ICmpInst::ICMP_UGT: return 1; // 001
3216 case ICmpInst::ICMP_SGT: return 1; // 001
3217 case ICmpInst::ICMP_EQ: return 2; // 010
3218 case ICmpInst::ICMP_UGE: return 3; // 011
3219 case ICmpInst::ICMP_SGE: return 3; // 011
3220 case ICmpInst::ICMP_ULT: return 4; // 100
3221 case ICmpInst::ICMP_SLT: return 4; // 100
3222 case ICmpInst::ICMP_NE: return 5; // 101
3223 case ICmpInst::ICMP_ULE: return 6; // 110
3224 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003225 // True -> 7
3226 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003227 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003228 return 0;
3229 }
3230}
3231
Evan Cheng8db90722008-10-14 17:15:11 +00003232/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3233/// predicate into a three bit mask. It also returns whether it is an ordered
3234/// predicate by reference.
3235static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3236 isOrdered = false;
3237 switch (CC) {
3238 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3239 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003240 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3241 case FCmpInst::FCMP_UGT: return 1; // 001
3242 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3243 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003244 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3245 case FCmpInst::FCMP_UGE: return 3; // 011
3246 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3247 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003248 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3249 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003250 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3251 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003252 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003253 default:
3254 // Not expecting FCMP_FALSE and FCMP_TRUE;
3255 assert(0 && "Unexpected FCmp predicate!");
3256 return 0;
3257 }
3258}
3259
Reid Spencere4d87aa2006-12-23 06:05:41 +00003260/// getICmpValue - This is the complement of getICmpCode, which turns an
3261/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003262/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003263/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003264static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3265 switch (code) {
3266 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003267 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003268 case 1:
3269 if (sign)
3270 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3271 else
3272 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3273 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3274 case 3:
3275 if (sign)
3276 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3277 else
3278 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3279 case 4:
3280 if (sign)
3281 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3282 else
3283 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3284 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3285 case 6:
3286 if (sign)
3287 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3288 else
3289 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003290 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003291 }
3292}
3293
Evan Cheng8db90722008-10-14 17:15:11 +00003294/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3295/// opcode and two operands into either a FCmp instruction. isordered is passed
3296/// in to determine which kind of predicate to use in the new fcmp instruction.
3297static Value *getFCmpValue(bool isordered, unsigned code,
3298 Value *LHS, Value *RHS) {
3299 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003300 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003301 case 0:
3302 if (isordered)
3303 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3304 else
3305 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3306 case 1:
3307 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003308 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3309 else
3310 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003311 case 2:
3312 if (isordered)
3313 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3314 else
3315 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003316 case 3:
3317 if (isordered)
3318 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3319 else
3320 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3321 case 4:
3322 if (isordered)
3323 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3324 else
3325 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3326 case 5:
3327 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003328 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3329 else
3330 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3331 case 6:
3332 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003333 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3334 else
3335 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003336 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003337 }
3338}
3339
Chris Lattnerb9553d62008-11-16 04:55:20 +00003340/// PredicatesFoldable - Return true if both predicates match sign or if at
3341/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003342static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3343 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003344 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3345 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003346}
3347
3348namespace {
3349// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3350struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003351 InstCombiner &IC;
3352 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003353 ICmpInst::Predicate pred;
3354 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3355 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3356 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003357 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003358 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3359 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003360 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3361 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003362 return false;
3363 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364 Instruction *apply(Instruction &Log) const {
3365 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3366 if (ICI->getOperand(0) != LHS) {
3367 assert(ICI->getOperand(1) == LHS);
3368 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003369 }
3370
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003371 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003373 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003374 unsigned Code;
3375 switch (Log.getOpcode()) {
3376 case Instruction::And: Code = LHSCode & RHSCode; break;
3377 case Instruction::Or: Code = LHSCode | RHSCode; break;
3378 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003379 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003380 }
3381
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003382 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3383 ICmpInst::isSignedPredicate(ICI->getPredicate());
3384
3385 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003386 if (Instruction *I = dyn_cast<Instruction>(RV))
3387 return I;
3388 // Otherwise, it's a constant boolean value...
3389 return IC.ReplaceInstUsesWith(Log, RV);
3390 }
3391};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003392} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003393
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003394// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3395// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003396// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003397Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003398 ConstantInt *OpRHS,
3399 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003400 BinaryOperator &TheAnd) {
3401 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003402 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003403 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003404 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003405
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003406 switch (Op->getOpcode()) {
3407 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003408 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003409 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003410 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003411 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003412 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003413 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003414 }
3415 break;
3416 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003417 if (Together == AndRHS) // (X | C) & C --> C
3418 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003419
Chris Lattner6e7ba452005-01-01 16:22:27 +00003420 if (Op->hasOneUse() && Together != OpRHS) {
3421 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003422 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003423 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003424 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003425 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003426 }
3427 break;
3428 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003429 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003430 // Adding a one to a single bit bit-field should be turned into an XOR
3431 // of the bit. First thing to check is to see if this AND is with a
3432 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003433 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003434
3435 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003436 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003437 // Ok, at this point, we know that we are masking the result of the
3438 // ADD down to exactly one bit. If the constant we are adding has
3439 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003440 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003441
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003442 // Check to see if any bits below the one bit set in AndRHSV are set.
3443 if ((AddRHS & (AndRHSV-1)) == 0) {
3444 // If not, the only thing that can effect the output of the AND is
3445 // the bit specified by AndRHSV. If that bit is set, the effect of
3446 // the XOR is to toggle the bit. If it is clear, then the ADD has
3447 // no effect.
3448 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3449 TheAnd.setOperand(0, X);
3450 return &TheAnd;
3451 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003452 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003453 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003454 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003455 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003456 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003457 }
3458 }
3459 }
3460 }
3461 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003462
3463 case Instruction::Shl: {
3464 // We know that the AND will not produce any of the bits shifted in, so if
3465 // the anded constant includes them, clear them now!
3466 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003467 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003468 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003469 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3470 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003471
Zhou Sheng290bec52007-03-29 08:15:12 +00003472 if (CI->getValue() == ShlMask) {
3473 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003474 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3475 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003476 TheAnd.setOperand(1, CI);
3477 return &TheAnd;
3478 }
3479 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003480 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003481 case Instruction::LShr:
3482 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003483 // We know that the AND will not produce any of the bits shifted in, so if
3484 // the anded constant includes them, clear them now! This only applies to
3485 // unsigned shifts, because a signed shr may bring in set bits!
3486 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003487 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003488 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003489 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3490 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003491
Zhou Sheng290bec52007-03-29 08:15:12 +00003492 if (CI->getValue() == ShrMask) {
3493 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003494 return ReplaceInstUsesWith(TheAnd, Op);
3495 } else if (CI != AndRHS) {
3496 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3497 return &TheAnd;
3498 }
3499 break;
3500 }
3501 case Instruction::AShr:
3502 // Signed shr.
3503 // See if this is shifting in some sign extension, then masking it out
3504 // with an and.
3505 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003506 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003507 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003508 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3509 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003510 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003511 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003512 // Make the argument unsigned.
3513 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003514 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003516 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003517 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003518 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003519 }
3520 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 }
3522 return 0;
3523}
3524
Chris Lattner8b170942002-08-09 23:47:40 +00003525
Chris Lattnera96879a2004-09-29 17:40:11 +00003526/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3527/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003528/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3529/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003530/// insert new instructions.
3531Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003532 bool isSigned, bool Inside,
3533 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003534 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003535 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003536 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003537
Chris Lattnera96879a2004-09-29 17:40:11 +00003538 if (Inside) {
3539 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003540 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003541
Reid Spencere4d87aa2006-12-23 06:05:41 +00003542 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003543 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003544 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003545 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3546 return new ICmpInst(pred, V, Hi);
3547 }
3548
3549 // Emit V-Lo <u Hi-Lo
3550 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003552 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003553 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3554 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003555 }
3556
3557 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003558 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003559
Reid Spencere4e40032007-03-21 23:19:50 +00003560 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003561 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003562 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003563 ICmpInst::Predicate pred = (isSigned ?
3564 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3565 return new ICmpInst(pred, V, Hi);
3566 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003567
Reid Spencere4e40032007-03-21 23:19:50 +00003568 // Emit V-Lo >u Hi-1-Lo
3569 // Note that Hi has already had one subtracted from it, above.
3570 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003571 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003572 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003573 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3574 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003575}
3576
Chris Lattner7203e152005-09-18 07:22:02 +00003577// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3578// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3579// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3580// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003581static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003582 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003583 uint32_t BitWidth = Val->getType()->getBitWidth();
3584 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003585
3586 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003587 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003588 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003589 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003590 return true;
3591}
3592
Chris Lattner7203e152005-09-18 07:22:02 +00003593/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3594/// where isSub determines whether the operator is a sub. If we can fold one of
3595/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003596///
3597/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3598/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3599/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3600///
3601/// return (A +/- B).
3602///
3603Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003604 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003605 Instruction &I) {
3606 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3607 if (!LHSI || LHSI->getNumOperands() != 2 ||
3608 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3609
3610 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3611
3612 switch (LHSI->getOpcode()) {
3613 default: return 0;
3614 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003615 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003616 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003617 if ((Mask->getValue().countLeadingZeros() +
3618 Mask->getValue().countPopulation()) ==
3619 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003620 break;
3621
3622 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3623 // part, we don't need any explicit masks to take them out of A. If that
3624 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003625 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003626 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003627 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003628 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003629 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003630 break;
3631 }
3632 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003633 return 0;
3634 case Instruction::Or:
3635 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003636 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003637 if ((Mask->getValue().countLeadingZeros() +
3638 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003639 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003640 break;
3641 return 0;
3642 }
3643
3644 Instruction *New;
3645 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003646 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003647 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003648 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003649 return InsertNewInstBefore(New, I);
3650}
3651
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003652/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3653Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3654 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003655 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003656 ConstantInt *LHSCst, *RHSCst;
3657 ICmpInst::Predicate LHSCC, RHSCC;
3658
Chris Lattnerea065fb2008-11-16 05:10:52 +00003659 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003660 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003661 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003662 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003663
3664 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3665 // where C is a power of 2
3666 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3667 LHSCst->getValue().isPowerOf2()) {
3668 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3669 InsertNewInstBefore(NewOr, I);
3670 return new ICmpInst(LHSCC, NewOr, LHSCst);
3671 }
3672
3673 // From here on, we only handle:
3674 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3675 if (Val != Val2) return 0;
3676
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003677 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3678 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3679 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3680 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3681 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3682 return 0;
3683
3684 // We can't fold (ugt x, C) & (sgt x, C2).
3685 if (!PredicatesFoldable(LHSCC, RHSCC))
3686 return 0;
3687
3688 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003689 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003690 if (ICmpInst::isSignedPredicate(LHSCC) ||
3691 (ICmpInst::isEquality(LHSCC) &&
3692 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003693 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003694 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003695 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3696
3697 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003698 std::swap(LHS, RHS);
3699 std::swap(LHSCst, RHSCst);
3700 std::swap(LHSCC, RHSCC);
3701 }
3702
3703 // At this point, we know we have have two icmp instructions
3704 // comparing a value against two constants and and'ing the result
3705 // together. Because of the above check, we know that we only have
3706 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3707 // (from the FoldICmpLogical check above), that the two constants
3708 // are not equal and that the larger constant is on the RHS
3709 assert(LHSCst != RHSCst && "Compares not folded above?");
3710
3711 switch (LHSCC) {
3712 default: assert(0 && "Unknown integer condition code!");
3713 case ICmpInst::ICMP_EQ:
3714 switch (RHSCC) {
3715 default: assert(0 && "Unknown integer condition code!");
3716 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3717 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3718 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3719 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3720 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3721 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3722 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3723 return ReplaceInstUsesWith(I, LHS);
3724 }
3725 case ICmpInst::ICMP_NE:
3726 switch (RHSCC) {
3727 default: assert(0 && "Unknown integer condition code!");
3728 case ICmpInst::ICMP_ULT:
3729 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3730 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3731 break; // (X != 13 & X u< 15) -> no change
3732 case ICmpInst::ICMP_SLT:
3733 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3734 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3735 break; // (X != 13 & X s< 15) -> no change
3736 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3737 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3738 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3739 return ReplaceInstUsesWith(I, RHS);
3740 case ICmpInst::ICMP_NE:
3741 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3742 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3743 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3744 Val->getName()+".off");
3745 InsertNewInstBefore(Add, I);
3746 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3747 ConstantInt::get(Add->getType(), 1));
3748 }
3749 break; // (X != 13 & X != 15) -> no change
3750 }
3751 break;
3752 case ICmpInst::ICMP_ULT:
3753 switch (RHSCC) {
3754 default: assert(0 && "Unknown integer condition code!");
3755 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3756 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3757 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3758 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3759 break;
3760 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3761 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3762 return ReplaceInstUsesWith(I, LHS);
3763 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3764 break;
3765 }
3766 break;
3767 case ICmpInst::ICMP_SLT:
3768 switch (RHSCC) {
3769 default: assert(0 && "Unknown integer condition code!");
3770 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3771 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3772 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3773 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3774 break;
3775 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3776 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3777 return ReplaceInstUsesWith(I, LHS);
3778 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3779 break;
3780 }
3781 break;
3782 case ICmpInst::ICMP_UGT:
3783 switch (RHSCC) {
3784 default: assert(0 && "Unknown integer condition code!");
3785 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3786 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3787 return ReplaceInstUsesWith(I, RHS);
3788 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3789 break;
3790 case ICmpInst::ICMP_NE:
3791 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3792 return new ICmpInst(LHSCC, Val, RHSCst);
3793 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003794 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003795 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3796 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3797 break;
3798 }
3799 break;
3800 case ICmpInst::ICMP_SGT:
3801 switch (RHSCC) {
3802 default: assert(0 && "Unknown integer condition code!");
3803 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3804 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3805 return ReplaceInstUsesWith(I, RHS);
3806 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3807 break;
3808 case ICmpInst::ICMP_NE:
3809 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3810 return new ICmpInst(LHSCC, Val, RHSCst);
3811 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003812 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003813 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3814 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3815 break;
3816 }
3817 break;
3818 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003819
3820 return 0;
3821}
3822
3823
Chris Lattner7e708292002-06-25 16:13:24 +00003824Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003825 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003826 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003827
Chris Lattnere87597f2004-10-16 18:11:37 +00003828 if (isa<UndefValue>(Op1)) // X & undef -> 0
3829 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3830
Chris Lattner6e7ba452005-01-01 16:22:27 +00003831 // and X, X = X
3832 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003833 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003834
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003835 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003836 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003837 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003838 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003839 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003840 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003841 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003842 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003843 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003844 } else if (isa<ConstantAggregateZero>(Op1)) {
3845 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003846 }
3847 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003848
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003849 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003850 const APInt& AndRHSMask = AndRHS->getValue();
3851 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003852
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003853 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003854 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003855 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003856 Value *Op0LHS = Op0I->getOperand(0);
3857 Value *Op0RHS = Op0I->getOperand(1);
3858 switch (Op0I->getOpcode()) {
3859 case Instruction::Xor:
3860 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003861 // If the mask is only needed on one incoming arm, push it up.
3862 if (Op0I->hasOneUse()) {
3863 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3864 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003865 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003866 Op0RHS->getName()+".masked");
3867 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003868 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003869 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003870 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003871 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003872 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3873 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003874 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003875 Op0LHS->getName()+".masked");
3876 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003877 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003878 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3879 }
3880 }
3881
Chris Lattner6e7ba452005-01-01 16:22:27 +00003882 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003883 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003884 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3885 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3886 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3887 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003888 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003889 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003890 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003891 break;
3892
3893 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003894 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3895 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3896 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3897 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003898 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003899
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003900 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3901 // has 1's for all bits that the subtraction with A might affect.
3902 if (Op0I->hasOneUse()) {
3903 uint32_t BitWidth = AndRHSMask.getBitWidth();
3904 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3905 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3906
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003907 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003908 if (!(A && A->isZero()) && // avoid infinite recursion.
3909 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003910 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3911 InsertNewInstBefore(NewNeg, I);
3912 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3913 }
3914 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003915 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003916
3917 case Instruction::Shl:
3918 case Instruction::LShr:
3919 // (1 << x) & 1 --> zext(x == 0)
3920 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003921 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003922 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3923 Constant::getNullValue(I.getType()));
3924 InsertNewInstBefore(NewICmp, I);
3925 return new ZExtInst(NewICmp, I.getType());
3926 }
3927 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003928 }
3929
Chris Lattner58403262003-07-23 19:25:52 +00003930 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003931 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003932 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003933 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003934 // If this is an integer truncation or change from signed-to-unsigned, and
3935 // if the source is an and/or with immediate, transform it. This
3936 // frequently occurs for bitfield accesses.
3937 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003938 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003939 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003940 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003941 if (CastOp->getOpcode() == Instruction::And) {
3942 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003943 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3944 // This will fold the two constants together, which may allow
3945 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003946 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003947 CastOp->getOperand(0), I.getType(),
3948 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003949 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003950 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003951 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003952 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003953 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003954 } else if (CastOp->getOpcode() == Instruction::Or) {
3955 // Change: and (cast (or X, C1) to T), C2
3956 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003957 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003958 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3959 return ReplaceInstUsesWith(I, AndRHS);
3960 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003961 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003962 }
Chris Lattner06782f82003-07-23 19:36:21 +00003963 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003964
3965 // Try to fold constant and into select arguments.
3966 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003967 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003968 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003969 if (isa<PHINode>(Op0))
3970 if (Instruction *NV = FoldOpIntoPhi(I))
3971 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003972 }
3973
Chris Lattner8d969642003-03-10 23:06:50 +00003974 Value *Op0NotVal = dyn_castNotVal(Op0);
3975 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003976
Chris Lattner5b62aa72004-06-18 06:07:51 +00003977 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3978 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3979
Misha Brukmancb6267b2004-07-30 12:50:08 +00003980 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003981 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003982 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003983 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003984 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003985 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003986 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003987
3988 {
Chris Lattner003b6202007-06-15 05:58:24 +00003989 Value *A = 0, *B = 0, *C = 0, *D = 0;
3990 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003991 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3992 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003993
3994 // (A|B) & ~(A&B) -> A^B
3995 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3996 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003997 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003998 }
3999 }
4000
4001 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004002 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4003 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004004
4005 // ~(A&B) & (A|B) -> A^B
4006 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4007 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004009 }
4010 }
Chris Lattner64daab52006-04-01 08:03:55 +00004011
4012 if (Op0->hasOneUse() &&
4013 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4014 if (A == Op1) { // (A^B)&A -> A&(A^B)
4015 I.swapOperands(); // Simplify below
4016 std::swap(Op0, Op1);
4017 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4018 cast<BinaryOperator>(Op0)->swapOperands();
4019 I.swapOperands(); // Simplify below
4020 std::swap(Op0, Op1);
4021 }
4022 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004023
Chris Lattner64daab52006-04-01 08:03:55 +00004024 if (Op1->hasOneUse() &&
4025 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4026 if (B == Op0) { // B&(A^B) -> B&(B^A)
4027 cast<BinaryOperator>(Op1)->swapOperands();
4028 std::swap(A, B);
4029 }
4030 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004031 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004032 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004033 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004034 }
4035 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004036
4037 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004038 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4039 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4040 return BinaryOperator::CreateAnd(A, Op1);
4041 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4042 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4043 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004044 }
4045
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4047 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4048 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004049 return R;
4050
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004051 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4052 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4053 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004054 }
4055
Chris Lattner6fc205f2006-05-05 06:39:07 +00004056 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004057 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4058 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4059 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4060 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004061 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004062 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004063 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4064 I.getType(), TD) &&
4065 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4066 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004067 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004068 Op1C->getOperand(0),
4069 I.getName());
4070 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004071 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004072 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004073 }
Chris Lattnere511b742006-11-14 07:46:50 +00004074
4075 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004076 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4077 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4078 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004079 SI0->getOperand(1) == SI1->getOperand(1) &&
4080 (SI0->hasOneUse() || SI1->hasOneUse())) {
4081 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004083 SI1->getOperand(0),
4084 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004085 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004086 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004087 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004088 }
4089
Evan Cheng8db90722008-10-14 17:15:11 +00004090 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004091 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4092 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4093 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004094 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4095 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004096 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4097 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4098 // If either of the constants are nans, then the whole thing returns
4099 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004100 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004101 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4102 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4103 RHS->getOperand(0));
4104 }
Evan Cheng8db90722008-10-14 17:15:11 +00004105 } else {
4106 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4107 FCmpInst::Predicate Op0CC, Op1CC;
4108 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4109 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004110 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4111 // Swap RHS operands to match LHS.
4112 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4113 std::swap(Op1LHS, Op1RHS);
4114 }
Evan Cheng8db90722008-10-14 17:15:11 +00004115 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4116 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4117 if (Op0CC == Op1CC)
4118 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4119 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4120 Op1CC == FCmpInst::FCMP_FALSE)
4121 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4122 else if (Op0CC == FCmpInst::FCMP_TRUE)
4123 return ReplaceInstUsesWith(I, Op1);
4124 else if (Op1CC == FCmpInst::FCMP_TRUE)
4125 return ReplaceInstUsesWith(I, Op0);
4126 bool Op0Ordered;
4127 bool Op1Ordered;
4128 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4129 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4130 if (Op1Pred == 0) {
4131 std::swap(Op0, Op1);
4132 std::swap(Op0Pred, Op1Pred);
4133 std::swap(Op0Ordered, Op1Ordered);
4134 }
4135 if (Op0Pred == 0) {
4136 // uno && ueq -> uno && (uno || eq) -> ueq
4137 // ord && olt -> ord && (ord && lt) -> olt
4138 if (Op0Ordered == Op1Ordered)
4139 return ReplaceInstUsesWith(I, Op1);
4140 // uno && oeq -> uno && (ord && eq) -> false
4141 // uno && ord -> false
4142 if (!Op0Ordered)
4143 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4144 // ord && ueq -> ord && (uno || eq) -> oeq
4145 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4146 Op0LHS, Op0RHS));
4147 }
4148 }
4149 }
4150 }
Chris Lattner99c65742007-10-24 05:38:08 +00004151 }
4152 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004153
Chris Lattner7e708292002-06-25 16:13:24 +00004154 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004155}
4156
Chris Lattner8c34cd22008-10-05 02:13:19 +00004157/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4158/// capable of providing pieces of a bswap. The subexpression provides pieces
4159/// of a bswap if it is proven that each of the non-zero bytes in the output of
4160/// the expression came from the corresponding "byte swapped" byte in some other
4161/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4162/// we know that the expression deposits the low byte of %X into the high byte
4163/// of the bswap result and that all other bytes are zero. This expression is
4164/// accepted, the high byte of ByteValues is set to X to indicate a correct
4165/// match.
4166///
4167/// This function returns true if the match was unsuccessful and false if so.
4168/// On entry to the function the "OverallLeftShift" is a signed integer value
4169/// indicating the number of bytes that the subexpression is later shifted. For
4170/// example, if the expression is later right shifted by 16 bits, the
4171/// OverallLeftShift value would be -2 on entry. This is used to specify which
4172/// byte of ByteValues is actually being set.
4173///
4174/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4175/// byte is masked to zero by a user. For example, in (X & 255), X will be
4176/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4177/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4178/// always in the local (OverallLeftShift) coordinate space.
4179///
4180static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4181 SmallVector<Value*, 8> &ByteValues) {
4182 if (Instruction *I = dyn_cast<Instruction>(V)) {
4183 // If this is an or instruction, it may be an inner node of the bswap.
4184 if (I->getOpcode() == Instruction::Or) {
4185 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4186 ByteValues) ||
4187 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4188 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004189 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004190
4191 // If this is a logical shift by a constant multiple of 8, recurse with
4192 // OverallLeftShift and ByteMask adjusted.
4193 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4194 unsigned ShAmt =
4195 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4196 // Ensure the shift amount is defined and of a byte value.
4197 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4198 return true;
4199
4200 unsigned ByteShift = ShAmt >> 3;
4201 if (I->getOpcode() == Instruction::Shl) {
4202 // X << 2 -> collect(X, +2)
4203 OverallLeftShift += ByteShift;
4204 ByteMask >>= ByteShift;
4205 } else {
4206 // X >>u 2 -> collect(X, -2)
4207 OverallLeftShift -= ByteShift;
4208 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004209 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004210 }
4211
4212 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4213 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4214
4215 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4216 ByteValues);
4217 }
4218
4219 // If this is a logical 'and' with a mask that clears bytes, clear the
4220 // corresponding bytes in ByteMask.
4221 if (I->getOpcode() == Instruction::And &&
4222 isa<ConstantInt>(I->getOperand(1))) {
4223 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4224 unsigned NumBytes = ByteValues.size();
4225 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4226 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4227
4228 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4229 // If this byte is masked out by a later operation, we don't care what
4230 // the and mask is.
4231 if ((ByteMask & (1 << i)) == 0)
4232 continue;
4233
4234 // If the AndMask is all zeros for this byte, clear the bit.
4235 APInt MaskB = AndMask & Byte;
4236 if (MaskB == 0) {
4237 ByteMask &= ~(1U << i);
4238 continue;
4239 }
4240
4241 // If the AndMask is not all ones for this byte, it's not a bytezap.
4242 if (MaskB != Byte)
4243 return true;
4244
4245 // Otherwise, this byte is kept.
4246 }
4247
4248 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4249 ByteValues);
4250 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004251 }
4252
Chris Lattner8c34cd22008-10-05 02:13:19 +00004253 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4254 // the input value to the bswap. Some observations: 1) if more than one byte
4255 // is demanded from this input, then it could not be successfully assembled
4256 // into a byteswap. At least one of the two bytes would not be aligned with
4257 // their ultimate destination.
4258 if (!isPowerOf2_32(ByteMask)) return true;
4259 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004260
Chris Lattner8c34cd22008-10-05 02:13:19 +00004261 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4262 // is demanded, it needs to go into byte 0 of the result. This means that the
4263 // byte needs to be shifted until it lands in the right byte bucket. The
4264 // shift amount depends on the position: if the byte is coming from the high
4265 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4266 // low part, it must be shifted left.
4267 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4268 if (InputByteNo < ByteValues.size()/2) {
4269 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4270 return true;
4271 } else {
4272 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4273 return true;
4274 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004275
4276 // If the destination byte value is already defined, the values are or'd
4277 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004278 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004279 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004280 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004281 return false;
4282}
4283
4284/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4285/// If so, insert the new bswap intrinsic and return it.
4286Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004287 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004288 if (!ITy || ITy->getBitWidth() % 16 ||
4289 // ByteMask only allows up to 32-byte values.
4290 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004291 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004292
4293 /// ByteValues - For each byte of the result, we keep track of which value
4294 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004295 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004296 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004297
4298 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004299 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4300 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004301 return 0;
4302
4303 // Check to see if all of the bytes come from the same value.
4304 Value *V = ByteValues[0];
4305 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4306
4307 // Check to make sure that all of the bytes come from the same value.
4308 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4309 if (ByteValues[i] != V)
4310 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004311 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004312 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004313 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004314 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004315}
4316
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004317/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4318/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4319/// we can simplify this expression to "cond ? C : D or B".
4320static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4321 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004322 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004323 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004324 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004325 return 0;
4326
Chris Lattnera6a474d2008-11-16 04:26:55 +00004327 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004328 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004329 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004330 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004331 return SelectInst::Create(Cond, C, B);
4332 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004333 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004334 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004335 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004336 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004337 return 0;
4338}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004339
Chris Lattner69d4ced2008-11-16 05:20:07 +00004340/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4341Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4342 ICmpInst *LHS, ICmpInst *RHS) {
4343 Value *Val, *Val2;
4344 ConstantInt *LHSCst, *RHSCst;
4345 ICmpInst::Predicate LHSCC, RHSCC;
4346
4347 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4348 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4349 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4350 return 0;
4351
4352 // From here on, we only handle:
4353 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4354 if (Val != Val2) return 0;
4355
4356 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4357 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4358 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4359 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4360 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4361 return 0;
4362
4363 // We can't fold (ugt x, C) | (sgt x, C2).
4364 if (!PredicatesFoldable(LHSCC, RHSCC))
4365 return 0;
4366
4367 // Ensure that the larger constant is on the RHS.
4368 bool ShouldSwap;
4369 if (ICmpInst::isSignedPredicate(LHSCC) ||
4370 (ICmpInst::isEquality(LHSCC) &&
4371 ICmpInst::isSignedPredicate(RHSCC)))
4372 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4373 else
4374 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4375
4376 if (ShouldSwap) {
4377 std::swap(LHS, RHS);
4378 std::swap(LHSCst, RHSCst);
4379 std::swap(LHSCC, RHSCC);
4380 }
4381
4382 // At this point, we know we have have two icmp instructions
4383 // comparing a value against two constants and or'ing the result
4384 // together. Because of the above check, we know that we only have
4385 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4386 // FoldICmpLogical check above), that the two constants are not
4387 // equal.
4388 assert(LHSCst != RHSCst && "Compares not folded above?");
4389
4390 switch (LHSCC) {
4391 default: assert(0 && "Unknown integer condition code!");
4392 case ICmpInst::ICMP_EQ:
4393 switch (RHSCC) {
4394 default: assert(0 && "Unknown integer condition code!");
4395 case ICmpInst::ICMP_EQ:
4396 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4397 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4398 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4399 Val->getName()+".off");
4400 InsertNewInstBefore(Add, I);
4401 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4402 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4403 }
4404 break; // (X == 13 | X == 15) -> no change
4405 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4406 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4407 break;
4408 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4409 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4410 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4411 return ReplaceInstUsesWith(I, RHS);
4412 }
4413 break;
4414 case ICmpInst::ICMP_NE:
4415 switch (RHSCC) {
4416 default: assert(0 && "Unknown integer condition code!");
4417 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4418 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4419 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4420 return ReplaceInstUsesWith(I, LHS);
4421 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4422 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4423 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4424 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4425 }
4426 break;
4427 case ICmpInst::ICMP_ULT:
4428 switch (RHSCC) {
4429 default: assert(0 && "Unknown integer condition code!");
4430 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4431 break;
4432 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4433 // If RHSCst is [us]MAXINT, it is always false. Not handling
4434 // this can cause overflow.
4435 if (RHSCst->isMaxValue(false))
4436 return ReplaceInstUsesWith(I, LHS);
4437 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4438 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4439 break;
4440 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4441 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4442 return ReplaceInstUsesWith(I, RHS);
4443 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4444 break;
4445 }
4446 break;
4447 case ICmpInst::ICMP_SLT:
4448 switch (RHSCC) {
4449 default: assert(0 && "Unknown integer condition code!");
4450 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4451 break;
4452 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4453 // If RHSCst is [us]MAXINT, it is always false. Not handling
4454 // this can cause overflow.
4455 if (RHSCst->isMaxValue(true))
4456 return ReplaceInstUsesWith(I, LHS);
4457 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4458 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4459 break;
4460 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4461 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4462 return ReplaceInstUsesWith(I, RHS);
4463 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4464 break;
4465 }
4466 break;
4467 case ICmpInst::ICMP_UGT:
4468 switch (RHSCC) {
4469 default: assert(0 && "Unknown integer condition code!");
4470 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4471 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4472 return ReplaceInstUsesWith(I, LHS);
4473 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4474 break;
4475 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4476 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4477 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4478 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4479 break;
4480 }
4481 break;
4482 case ICmpInst::ICMP_SGT:
4483 switch (RHSCC) {
4484 default: assert(0 && "Unknown integer condition code!");
4485 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4486 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4487 return ReplaceInstUsesWith(I, LHS);
4488 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4489 break;
4490 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4491 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4492 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4493 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4494 break;
4495 }
4496 break;
4497 }
4498 return 0;
4499}
4500
Bill Wendlinga698a472008-12-01 08:23:25 +00004501/// FoldOrWithConstants - This helper function folds:
4502///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004503/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004504///
4505/// into:
4506///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004507/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004508///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004509/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004510Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004511 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004512 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4513 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004514
Bill Wendling286a0542008-12-02 06:24:20 +00004515 Value *V1 = 0;
4516 ConstantInt *CI2 = 0;
4517 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004518
Bill Wendling29976b92008-12-02 06:18:11 +00004519 APInt Xor = CI1->getValue() ^ CI2->getValue();
4520 if (!Xor.isAllOnesValue()) return 0;
4521
Bill Wendling286a0542008-12-02 06:24:20 +00004522 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004523 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004524 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4525 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004526 }
4527
4528 return 0;
4529}
4530
Chris Lattner7e708292002-06-25 16:13:24 +00004531Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004532 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004534
Chris Lattner42593e62007-03-24 23:56:43 +00004535 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004536 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004537
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004538 // or X, X = X
4539 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004540 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004541
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004542 // See if we can simplify any instructions used by the instruction whose sole
4543 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004544 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004545 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004546 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004547 } else if (isa<ConstantAggregateZero>(Op1)) {
4548 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4549 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4550 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4551 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004552 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004553
4554
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004555
Chris Lattner3f5b8772002-05-06 16:14:14 +00004556 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004557 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004558 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004559 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4560 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004561 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004562 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004563 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004564 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004565 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004566 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004567
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004568 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4569 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004570 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004571 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004572 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004573 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004574 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004575 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004576
4577 // Try to fold constant and into select arguments.
4578 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004579 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004580 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004581 if (isa<PHINode>(Op0))
4582 if (Instruction *NV = FoldOpIntoPhi(I))
4583 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004584 }
4585
Chris Lattner4f637d42006-01-06 17:59:59 +00004586 Value *A = 0, *B = 0;
4587 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004588
4589 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4590 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4591 return ReplaceInstUsesWith(I, Op1);
4592 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4593 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4594 return ReplaceInstUsesWith(I, Op0);
4595
Chris Lattner6423d4c2006-07-10 20:25:24 +00004596 // (A | B) | C and A | (B | C) -> bswap if possible.
4597 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004598 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004599 match(Op1, m_Or(m_Value(), m_Value())) ||
4600 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4601 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004602 if (Instruction *BSwap = MatchBSwap(I))
4603 return BSwap;
4604 }
4605
Chris Lattner6e4c6492005-05-09 04:58:36 +00004606 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4607 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004608 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004609 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004610 InsertNewInstBefore(NOr, I);
4611 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004612 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004613 }
4614
4615 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4616 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004617 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004618 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004619 InsertNewInstBefore(NOr, I);
4620 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004621 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004622 }
4623
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004624 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004625 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004626 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4627 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004628 Value *V1 = 0, *V2 = 0, *V3 = 0;
4629 C1 = dyn_cast<ConstantInt>(C);
4630 C2 = dyn_cast<ConstantInt>(D);
4631 if (C1 && C2) { // (A & C1)|(B & C2)
4632 // If we have: ((V + N) & C1) | (V & C2)
4633 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4634 // replace with V+N.
4635 if (C1->getValue() == ~C2->getValue()) {
4636 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4637 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4638 // Add commutes, try both ways.
4639 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4640 return ReplaceInstUsesWith(I, A);
4641 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4642 return ReplaceInstUsesWith(I, A);
4643 }
4644 // Or commutes, try both ways.
4645 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4646 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4647 // Add commutes, try both ways.
4648 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4649 return ReplaceInstUsesWith(I, B);
4650 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4651 return ReplaceInstUsesWith(I, B);
4652 }
4653 }
Chris Lattner044e5332007-04-08 08:01:49 +00004654 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004655 }
4656
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004657 // Check to see if we have any common things being and'ed. If so, find the
4658 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004659 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4660 if (A == B) // (A & C)|(A & D) == A & (C|D)
4661 V1 = A, V2 = C, V3 = D;
4662 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4663 V1 = A, V2 = B, V3 = C;
4664 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4665 V1 = C, V2 = A, V3 = D;
4666 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4667 V1 = C, V2 = A, V3 = B;
4668
4669 if (V1) {
4670 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004671 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4672 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004673 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004674 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004675
Dan Gohman1975d032008-10-30 20:40:10 +00004676 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004677 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4678 return Match;
4679 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4680 return Match;
4681 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4682 return Match;
4683 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4684 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004685
Bill Wendlingb01865c2008-11-30 13:52:49 +00004686 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004687 if ((match(C, m_Not(m_Specific(D))) &&
4688 match(B, m_Not(m_Specific(A)))))
4689 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004690 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004691 if ((match(A, m_Not(m_Specific(D))) &&
4692 match(B, m_Not(m_Specific(C)))))
4693 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004694 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004695 if ((match(C, m_Not(m_Specific(B))) &&
4696 match(D, m_Not(m_Specific(A)))))
4697 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004698 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004699 if ((match(A, m_Not(m_Specific(B))) &&
4700 match(D, m_Not(m_Specific(C)))))
4701 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004702 }
Chris Lattnere511b742006-11-14 07:46:50 +00004703
4704 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004705 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4706 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4707 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004708 SI0->getOperand(1) == SI1->getOperand(1) &&
4709 (SI0->hasOneUse() || SI1->hasOneUse())) {
4710 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004711 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004712 SI1->getOperand(0),
4713 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004714 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004715 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004716 }
4717 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004718
Bill Wendlingb3833d12008-12-01 01:07:11 +00004719 // ((A|B)&1)|(B&-2) -> (A&1) | B
4720 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4721 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004722 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004723 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004724 }
4725 // (B&-2)|((A|B)&1) -> (A&1) | B
4726 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4727 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004728 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004729 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004730 }
4731
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004732 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4733 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004734 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004735 } else {
4736 A = 0;
4737 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004738 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004739 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4740 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004741 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004742
Misha Brukmancb6267b2004-07-30 12:50:08 +00004743 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004744 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004745 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004746 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004748 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004749 }
Chris Lattnera2881962003-02-18 19:28:33 +00004750
Reid Spencere4d87aa2006-12-23 06:05:41 +00004751 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4752 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4753 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004754 return R;
4755
Chris Lattner69d4ced2008-11-16 05:20:07 +00004756 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4757 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4758 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004759 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004760
4761 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004762 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004763 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004764 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004765 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4766 !isa<ICmpInst>(Op1C->getOperand(0))) {
4767 const Type *SrcTy = Op0C->getOperand(0)->getType();
4768 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4769 // Only do this if the casts both really cause code to be
4770 // generated.
4771 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4772 I.getType(), TD) &&
4773 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4774 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004775 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004776 Op1C->getOperand(0),
4777 I.getName());
4778 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004779 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004780 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004781 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004782 }
Chris Lattner99c65742007-10-24 05:38:08 +00004783 }
4784
4785
4786 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4787 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4788 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4789 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004790 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004791 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004792 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4793 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4794 // If either of the constants are nans, then the whole thing returns
4795 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004796 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004797 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4798
4799 // Otherwise, no need to compare the two constants, compare the
4800 // rest.
4801 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4802 RHS->getOperand(0));
4803 }
Evan Cheng40300622008-10-14 18:44:08 +00004804 } else {
4805 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4806 FCmpInst::Predicate Op0CC, Op1CC;
4807 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4808 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4809 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4810 // Swap RHS operands to match LHS.
4811 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4812 std::swap(Op1LHS, Op1RHS);
4813 }
4814 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4815 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4816 if (Op0CC == Op1CC)
4817 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4818 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4819 Op1CC == FCmpInst::FCMP_TRUE)
4820 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4821 else if (Op0CC == FCmpInst::FCMP_FALSE)
4822 return ReplaceInstUsesWith(I, Op1);
4823 else if (Op1CC == FCmpInst::FCMP_FALSE)
4824 return ReplaceInstUsesWith(I, Op0);
4825 bool Op0Ordered;
4826 bool Op1Ordered;
4827 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4828 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4829 if (Op0Ordered == Op1Ordered) {
4830 // If both are ordered or unordered, return a new fcmp with
4831 // or'ed predicates.
4832 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4833 Op0LHS, Op0RHS);
4834 if (Instruction *I = dyn_cast<Instruction>(RV))
4835 return I;
4836 // Otherwise, it's a constant boolean value...
4837 return ReplaceInstUsesWith(I, RV);
4838 }
4839 }
4840 }
4841 }
Chris Lattner99c65742007-10-24 05:38:08 +00004842 }
4843 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004844
Chris Lattner7e708292002-06-25 16:13:24 +00004845 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004846}
4847
Dan Gohman844731a2008-05-13 00:00:25 +00004848namespace {
4849
Chris Lattnerc317d392004-02-16 01:20:27 +00004850// XorSelf - Implements: X ^ X --> 0
4851struct XorSelf {
4852 Value *RHS;
4853 XorSelf(Value *rhs) : RHS(rhs) {}
4854 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4855 Instruction *apply(BinaryOperator &Xor) const {
4856 return &Xor;
4857 }
4858};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004859
Dan Gohman844731a2008-05-13 00:00:25 +00004860}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004861
Chris Lattner7e708292002-06-25 16:13:24 +00004862Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004863 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004864 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004865
Evan Chengd34af782008-03-25 20:07:13 +00004866 if (isa<UndefValue>(Op1)) {
4867 if (isa<UndefValue>(Op0))
4868 // Handle undef ^ undef -> 0 special case. This is a common
4869 // idiom (misuse).
4870 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004871 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004872 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004873
Chris Lattnerc317d392004-02-16 01:20:27 +00004874 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4875 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004876 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004877 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004878 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004879
4880 // See if we can simplify any instructions used by the instruction whose sole
4881 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004882 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004883 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004884 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004885 } else if (isa<ConstantAggregateZero>(Op1)) {
4886 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004887 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004888
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004889 // Is this a ~ operation?
4890 if (Value *NotOp = dyn_castNotVal(&I)) {
4891 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4892 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4893 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4894 if (Op0I->getOpcode() == Instruction::And ||
4895 Op0I->getOpcode() == Instruction::Or) {
4896 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4897 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4898 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004899 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004900 Op0I->getOperand(1)->getName()+".not");
4901 InsertNewInstBefore(NotY, I);
4902 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004903 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004904 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004905 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004906 }
4907 }
4908 }
4909 }
4910
4911
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004912 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004913 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004914 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004915 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004916 return new ICmpInst(ICI->getInversePredicate(),
4917 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004918
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004919 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4920 return new FCmpInst(FCI->getInversePredicate(),
4921 FCI->getOperand(0), FCI->getOperand(1));
4922 }
4923
Nick Lewycky517e1f52008-05-31 19:01:33 +00004924 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4925 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4926 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4927 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4928 Instruction::CastOps Opcode = Op0C->getOpcode();
4929 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4930 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4931 Op0C->getDestTy())) {
4932 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4933 CI->getOpcode(), CI->getInversePredicate(),
4934 CI->getOperand(0), CI->getOperand(1)), I);
4935 NewCI->takeName(CI);
4936 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4937 }
4938 }
4939 }
4940 }
4941 }
4942
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004944 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004945 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4946 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004947 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4948 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004949 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004950 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004951 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004952
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004953 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004954 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004955 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004956 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004957 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004958 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004959 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004960 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004961 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004962 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004963 // (X + C) ^ signbit -> (X + C + signbit)
4964 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004965 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004966
Chris Lattner7c4049c2004-01-12 19:35:11 +00004967 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004968 } else if (Op0I->getOpcode() == Instruction::Or) {
4969 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004970 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004971 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4972 // Anything in both C1 and C2 is known to be zero, remove it from
4973 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004974 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004975 NewRHS = ConstantExpr::getAnd(NewRHS,
4976 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004977 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004978 I.setOperand(0, Op0I->getOperand(0));
4979 I.setOperand(1, NewRHS);
4980 return &I;
4981 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004982 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004983 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004984 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004985
4986 // Try to fold constant and into select arguments.
4987 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004988 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004989 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004990 if (isa<PHINode>(Op0))
4991 if (Instruction *NV = FoldOpIntoPhi(I))
4992 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004993 }
4994
Chris Lattner8d969642003-03-10 23:06:50 +00004995 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004996 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004997 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004998
Chris Lattner8d969642003-03-10 23:06:50 +00004999 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005000 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005001 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005002
Chris Lattner318bf792007-03-18 22:51:34 +00005003
5004 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5005 if (Op1I) {
5006 Value *A, *B;
5007 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5008 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005009 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005010 I.swapOperands();
5011 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005012 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005013 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005014 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005015 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005016 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5017 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5018 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5019 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005020 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005021 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005022 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005023 std::swap(A, B);
5024 }
Chris Lattner318bf792007-03-18 22:51:34 +00005025 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005026 I.swapOperands(); // Simplified below.
5027 std::swap(Op0, Op1);
5028 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005029 }
Chris Lattner318bf792007-03-18 22:51:34 +00005030 }
5031
5032 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5033 if (Op0I) {
5034 Value *A, *B;
5035 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5036 if (A == Op1) // (B|A)^B == (A|B)^B
5037 std::swap(A, B);
5038 if (B == Op1) { // (A|B)^B == A & ~B
5039 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005040 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5041 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005042 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005043 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5044 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5045 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5046 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005047 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5048 if (A == Op1) // (A&B)^A -> (B&A)^A
5049 std::swap(A, B);
5050 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005051 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005052 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005053 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5054 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005055 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005056 }
Chris Lattner318bf792007-03-18 22:51:34 +00005057 }
5058
5059 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5060 if (Op0I && Op1I && Op0I->isShift() &&
5061 Op0I->getOpcode() == Op1I->getOpcode() &&
5062 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5063 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5064 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005065 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005066 Op1I->getOperand(0),
5067 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005068 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005069 Op1I->getOperand(1));
5070 }
5071
5072 if (Op0I && Op1I) {
5073 Value *A, *B, *C, *D;
5074 // (A & B)^(A | B) -> A ^ B
5075 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5076 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5077 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005078 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005079 }
5080 // (A | B)^(A & B) -> A ^ B
5081 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5082 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5083 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005084 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005085 }
5086
5087 // (A & B)^(C & D)
5088 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5089 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5090 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5091 // (X & Y)^(X & Y) -> (Y^Z) & X
5092 Value *X = 0, *Y = 0, *Z = 0;
5093 if (A == C)
5094 X = A, Y = B, Z = D;
5095 else if (A == D)
5096 X = A, Y = B, Z = C;
5097 else if (B == C)
5098 X = B, Y = A, Z = D;
5099 else if (B == D)
5100 X = B, Y = A, Z = C;
5101
5102 if (X) {
5103 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005104 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5105 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005106 }
5107 }
5108 }
5109
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5111 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5112 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005113 return R;
5114
Chris Lattner6fc205f2006-05-05 06:39:07 +00005115 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005116 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005117 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005118 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5119 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005120 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005121 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005122 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5123 I.getType(), TD) &&
5124 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5125 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005126 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005127 Op1C->getOperand(0),
5128 I.getName());
5129 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005131 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005132 }
Chris Lattner99c65742007-10-24 05:38:08 +00005133 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005134
Chris Lattner7e708292002-06-25 16:13:24 +00005135 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005136}
5137
Chris Lattnera96879a2004-09-29 17:40:11 +00005138/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5139/// overflowed for this type.
5140static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005141 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005142 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005143
Reid Spencere4e40032007-03-21 23:19:50 +00005144 if (IsSigned)
5145 if (In2->getValue().isNegative())
5146 return Result->getValue().sgt(In1->getValue());
5147 else
5148 return Result->getValue().slt(In1->getValue());
5149 else
5150 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005151}
5152
Dan Gohman1df3fd62008-09-10 23:30:57 +00005153/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5154/// overflowed for this type.
5155static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5156 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005157 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005158
5159 if (IsSigned)
5160 if (In2->getValue().isNegative())
5161 return Result->getValue().slt(In1->getValue());
5162 else
5163 return Result->getValue().sgt(In1->getValue());
5164 else
5165 return Result->getValue().ugt(In1->getValue());
5166}
5167
Chris Lattner574da9b2005-01-13 20:14:25 +00005168/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5169/// code necessary to compute the offset from the base pointer (without adding
5170/// in the base pointer). Return the result as a signed integer of intptr size.
5171static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5172 TargetData &TD = IC.getTargetData();
5173 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 const Type *IntPtrTy = TD.getIntPtrType();
5175 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005176
5177 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005178 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005179 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005180
Gabor Greif177dd3f2008-06-12 21:37:33 +00005181 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5182 ++i, ++GTI) {
5183 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005184 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005185 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5186 if (OpC->isZero()) continue;
5187
5188 // Handle a struct index, which adds its field offset to the pointer.
5189 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5190 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5191
5192 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5193 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005194 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005195 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005196 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005197 ConstantInt::get(IntPtrTy, Size),
5198 GEP->getName()+".offs"), I);
5199 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005200 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005201
5202 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5203 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5204 Scale = ConstantExpr::getMul(OC, Scale);
5205 if (Constant *RC = dyn_cast<Constant>(Result))
5206 Result = ConstantExpr::getAdd(RC, Scale);
5207 else {
5208 // Emit an add instruction.
5209 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005210 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005211 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005212 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005213 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005214 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005215 // Convert to correct type.
5216 if (Op->getType() != IntPtrTy) {
5217 if (Constant *OpC = dyn_cast<Constant>(Op))
5218 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5219 else
5220 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5221 Op->getName()+".c"), I);
5222 }
5223 if (Size != 1) {
5224 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5225 if (Constant *OpC = dyn_cast<Constant>(Op))
5226 Op = ConstantExpr::getMul(OpC, Scale);
5227 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005228 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005229 GEP->getName()+".idx"), I);
5230 }
5231
5232 // Emit an add instruction.
5233 if (isa<Constant>(Op) && isa<Constant>(Result))
5234 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5235 cast<Constant>(Result));
5236 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005237 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005238 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005239 }
5240 return Result;
5241}
5242
Chris Lattner10c0d912008-04-22 02:53:33 +00005243
5244/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5245/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5246/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5247/// complex, and scales are involved. The above expression would also be legal
5248/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5249/// later form is less amenable to optimization though, and we are allowed to
5250/// generate the first by knowing that pointer arithmetic doesn't overflow.
5251///
5252/// If we can't emit an optimized form for this expression, this returns null.
5253///
5254static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5255 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005256 TargetData &TD = IC.getTargetData();
5257 gep_type_iterator GTI = gep_type_begin(GEP);
5258
5259 // Check to see if this gep only has a single variable index. If so, and if
5260 // any constant indices are a multiple of its scale, then we can compute this
5261 // in terms of the scale of the variable index. For example, if the GEP
5262 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5263 // because the expression will cross zero at the same point.
5264 unsigned i, e = GEP->getNumOperands();
5265 int64_t Offset = 0;
5266 for (i = 1; i != e; ++i, ++GTI) {
5267 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5268 // Compute the aggregate offset of constant indices.
5269 if (CI->isZero()) continue;
5270
5271 // Handle a struct index, which adds its field offset to the pointer.
5272 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5273 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5274 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005275 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005276 Offset += Size*CI->getSExtValue();
5277 }
5278 } else {
5279 // Found our variable index.
5280 break;
5281 }
5282 }
5283
5284 // If there are no variable indices, we must have a constant offset, just
5285 // evaluate it the general way.
5286 if (i == e) return 0;
5287
5288 Value *VariableIdx = GEP->getOperand(i);
5289 // Determine the scale factor of the variable element. For example, this is
5290 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005291 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005292
5293 // Verify that there are no other variable indices. If so, emit the hard way.
5294 for (++i, ++GTI; i != e; ++i, ++GTI) {
5295 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5296 if (!CI) return 0;
5297
5298 // Compute the aggregate offset of constant indices.
5299 if (CI->isZero()) continue;
5300
5301 // Handle a struct index, which adds its field offset to the pointer.
5302 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5303 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5304 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005305 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005306 Offset += Size*CI->getSExtValue();
5307 }
5308 }
5309
5310 // Okay, we know we have a single variable index, which must be a
5311 // pointer/array/vector index. If there is no offset, life is simple, return
5312 // the index.
5313 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5314 if (Offset == 0) {
5315 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5316 // we don't need to bother extending: the extension won't affect where the
5317 // computation crosses zero.
5318 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5319 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5320 VariableIdx->getNameStart(), &I);
5321 return VariableIdx;
5322 }
5323
5324 // Otherwise, there is an index. The computation we will do will be modulo
5325 // the pointer size, so get it.
5326 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5327
5328 Offset &= PtrSizeMask;
5329 VariableScale &= PtrSizeMask;
5330
5331 // To do this transformation, any constant index must be a multiple of the
5332 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5333 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5334 // multiple of the variable scale.
5335 int64_t NewOffs = Offset / (int64_t)VariableScale;
5336 if (Offset != NewOffs*(int64_t)VariableScale)
5337 return 0;
5338
5339 // Okay, we can do this evaluation. Start by converting the index to intptr.
5340 const Type *IntPtrTy = TD.getIntPtrType();
5341 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005342 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005343 true /*SExt*/,
5344 VariableIdx->getNameStart(), &I);
5345 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005346 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005347}
5348
5349
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005351/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005352Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5353 ICmpInst::Predicate Cond,
5354 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005355 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005356
Chris Lattner10c0d912008-04-22 02:53:33 +00005357 // Look through bitcasts.
5358 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5359 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005360
Chris Lattner574da9b2005-01-13 20:14:25 +00005361 Value *PtrBase = GEPLHS->getOperand(0);
5362 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005363 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005364 // This transformation (ignoring the base and scales) is valid because we
5365 // know pointers can't overflow. See if we can output an optimized form.
5366 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5367
5368 // If not, synthesize the offset the hard way.
5369 if (Offset == 0)
5370 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005371 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5372 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005373 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005374 // If the base pointers are different, but the indices are the same, just
5375 // compare the base pointer.
5376 if (PtrBase != GEPRHS->getOperand(0)) {
5377 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005378 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005379 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005380 if (IndicesTheSame)
5381 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5382 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5383 IndicesTheSame = false;
5384 break;
5385 }
5386
5387 // If all indices are the same, just compare the base pointers.
5388 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005389 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5390 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005391
5392 // Otherwise, the base pointers are different and the indices are
5393 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005394 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005395 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005396
Chris Lattnere9d782b2005-01-13 22:25:21 +00005397 // If one of the GEPs has all zero indices, recurse.
5398 bool AllZeros = true;
5399 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5400 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5401 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5402 AllZeros = false;
5403 break;
5404 }
5405 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005406 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5407 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005408
5409 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005410 AllZeros = true;
5411 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5412 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5413 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5414 AllZeros = false;
5415 break;
5416 }
5417 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005418 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005419
Chris Lattner4401c9c2005-01-14 00:20:05 +00005420 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5421 // If the GEPs only differ by one index, compare it.
5422 unsigned NumDifferences = 0; // Keep track of # differences.
5423 unsigned DiffOperand = 0; // The operand that differs.
5424 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5425 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005426 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5427 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005428 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005429 NumDifferences = 2;
5430 break;
5431 } else {
5432 if (NumDifferences++) break;
5433 DiffOperand = i;
5434 }
5435 }
5436
5437 if (NumDifferences == 0) // SAME GEP?
5438 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005439 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005440 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005441
Chris Lattner4401c9c2005-01-14 00:20:05 +00005442 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005443 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5444 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 // Make sure we do a signed comparison here.
5446 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005447 }
5448 }
5449
Reid Spencere4d87aa2006-12-23 06:05:41 +00005450 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005451 // the result to fold to a constant!
5452 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5453 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5454 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5455 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5456 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005457 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005458 }
5459 }
5460 return 0;
5461}
5462
Chris Lattnera5406232008-05-19 20:18:56 +00005463/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5464///
5465Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5466 Instruction *LHSI,
5467 Constant *RHSC) {
5468 if (!isa<ConstantFP>(RHSC)) return 0;
5469 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5470
5471 // Get the width of the mantissa. We don't want to hack on conversions that
5472 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005473 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005474 if (MantissaWidth == -1) return 0; // Unknown.
5475
5476 // Check to see that the input is converted from an integer type that is small
5477 // enough that preserves all bits. TODO: check here for "known" sign bits.
5478 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5479 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5480
5481 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005482 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5483 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005484 ++InputSize;
5485
5486 // If the conversion would lose info, don't hack on this.
5487 if ((int)InputSize > MantissaWidth)
5488 return 0;
5489
5490 // Otherwise, we can potentially simplify the comparison. We know that it
5491 // will always come through as an integer value and we know the constant is
5492 // not a NAN (it would have been previously simplified).
5493 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5494
5495 ICmpInst::Predicate Pred;
5496 switch (I.getPredicate()) {
5497 default: assert(0 && "Unexpected predicate!");
5498 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005499 case FCmpInst::FCMP_OEQ:
5500 Pred = ICmpInst::ICMP_EQ;
5501 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005502 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005503 case FCmpInst::FCMP_OGT:
5504 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5505 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005506 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005507 case FCmpInst::FCMP_OGE:
5508 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5509 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005510 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005511 case FCmpInst::FCMP_OLT:
5512 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5513 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005514 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005515 case FCmpInst::FCMP_OLE:
5516 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5517 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005518 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005519 case FCmpInst::FCMP_ONE:
5520 Pred = ICmpInst::ICMP_NE;
5521 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005522 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005523 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005524 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005525 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005526 }
5527
5528 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5529
5530 // Now we know that the APFloat is a normal number, zero or inf.
5531
Chris Lattner85162782008-05-20 03:50:52 +00005532 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005533 // comparing an i8 to 300.0.
5534 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5535
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005536 if (!LHSUnsigned) {
5537 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5538 // and large values.
5539 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5540 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5541 APFloat::rmNearestTiesToEven);
5542 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5543 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5544 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005545 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5546 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005547 }
5548 } else {
5549 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5550 // +INF and large values.
5551 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5552 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5553 APFloat::rmNearestTiesToEven);
5554 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5555 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5556 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005557 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5558 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005559 }
Chris Lattnera5406232008-05-19 20:18:56 +00005560 }
5561
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005562 if (!LHSUnsigned) {
5563 // See if the RHS value is < SignedMin.
5564 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5565 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5566 APFloat::rmNearestTiesToEven);
5567 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5568 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5569 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005570 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5571 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005572 }
Chris Lattnera5406232008-05-19 20:18:56 +00005573 }
5574
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005575 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5576 // [0, UMAX], but it may still be fractional. See if it is fractional by
5577 // casting the FP value to the integer value and back, checking for equality.
5578 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005579 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5580 if (!RHS.isZero() &&
5581 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005582 // If we had a comparison against a fractional value, we have to adjust the
5583 // compare predicate and sometimes the value. RHSC is rounded towards zero
5584 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005585 switch (Pred) {
5586 default: assert(0 && "Unexpected integer comparison!");
5587 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005588 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005589 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005590 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005591 case ICmpInst::ICMP_ULE:
5592 // (float)int <= 4.4 --> int <= 4
5593 // (float)int <= -4.4 --> false
5594 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005595 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005596 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005597 case ICmpInst::ICMP_SLE:
5598 // (float)int <= 4.4 --> int <= 4
5599 // (float)int <= -4.4 --> int < -4
5600 if (RHS.isNegative())
5601 Pred = ICmpInst::ICMP_SLT;
5602 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005603 case ICmpInst::ICMP_ULT:
5604 // (float)int < -4.4 --> false
5605 // (float)int < 4.4 --> int <= 4
5606 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005607 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005608 Pred = ICmpInst::ICMP_ULE;
5609 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005610 case ICmpInst::ICMP_SLT:
5611 // (float)int < -4.4 --> int < -4
5612 // (float)int < 4.4 --> int <= 4
5613 if (!RHS.isNegative())
5614 Pred = ICmpInst::ICMP_SLE;
5615 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005616 case ICmpInst::ICMP_UGT:
5617 // (float)int > 4.4 --> int > 4
5618 // (float)int > -4.4 --> true
5619 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005620 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005621 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005622 case ICmpInst::ICMP_SGT:
5623 // (float)int > 4.4 --> int > 4
5624 // (float)int > -4.4 --> int >= -4
5625 if (RHS.isNegative())
5626 Pred = ICmpInst::ICMP_SGE;
5627 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005628 case ICmpInst::ICMP_UGE:
5629 // (float)int >= -4.4 --> true
5630 // (float)int >= 4.4 --> int > 4
5631 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005632 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005633 Pred = ICmpInst::ICMP_UGT;
5634 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005635 case ICmpInst::ICMP_SGE:
5636 // (float)int >= -4.4 --> int >= -4
5637 // (float)int >= 4.4 --> int > 4
5638 if (!RHS.isNegative())
5639 Pred = ICmpInst::ICMP_SGT;
5640 break;
5641 }
5642 }
5643
5644 // Lower this FP comparison into an appropriate integer version of the
5645 // comparison.
5646 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5647}
5648
Reid Spencere4d87aa2006-12-23 06:05:41 +00005649Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5650 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005651 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005652
Chris Lattner58e97462007-01-14 19:42:17 +00005653 // Fold trivial predicates.
5654 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005655 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005656 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005657 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005658
5659 // Simplify 'fcmp pred X, X'
5660 if (Op0 == Op1) {
5661 switch (I.getPredicate()) {
5662 default: assert(0 && "Unknown predicate!");
5663 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5664 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5665 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005666 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005667 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5668 case FCmpInst::FCMP_OLT: // True if ordered and less than
5669 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005670 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005671
5672 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5673 case FCmpInst::FCMP_ULT: // True if unordered or less than
5674 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5675 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5676 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5677 I.setPredicate(FCmpInst::FCMP_UNO);
5678 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5679 return &I;
5680
5681 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5682 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5683 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5684 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5685 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5686 I.setPredicate(FCmpInst::FCMP_ORD);
5687 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5688 return &I;
5689 }
5690 }
5691
Reid Spencere4d87aa2006-12-23 06:05:41 +00005692 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005693 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005694
Reid Spencere4d87aa2006-12-23 06:05:41 +00005695 // Handle fcmp with constant RHS
5696 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005697 // If the constant is a nan, see if we can fold the comparison based on it.
5698 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5699 if (CFP->getValueAPF().isNaN()) {
5700 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005702 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5703 "Comparison must be either ordered or unordered!");
5704 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005705 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005706 }
5707 }
5708
Reid Spencere4d87aa2006-12-23 06:05:41 +00005709 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5710 switch (LHSI->getOpcode()) {
5711 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005712 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5713 // block. If in the same block, we're encouraging jump threading. If
5714 // not, we are just pessimizing the code by making an i1 phi.
5715 if (LHSI->getParent() == I.getParent())
5716 if (Instruction *NV = FoldOpIntoPhi(I))
5717 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005719 case Instruction::SIToFP:
5720 case Instruction::UIToFP:
5721 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5722 return NV;
5723 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005724 case Instruction::Select:
5725 // If either operand of the select is a constant, we can fold the
5726 // comparison into the select arms, which will cause one to be
5727 // constant folded and the select turned into a bitwise or.
5728 Value *Op1 = 0, *Op2 = 0;
5729 if (LHSI->hasOneUse()) {
5730 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5731 // Fold the known value into the constant operand.
5732 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5733 // Insert a new FCmp of the other select operand.
5734 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5735 LHSI->getOperand(2), RHSC,
5736 I.getName()), I);
5737 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5738 // Fold the known value into the constant operand.
5739 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5740 // Insert a new FCmp of the other select operand.
5741 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5742 LHSI->getOperand(1), RHSC,
5743 I.getName()), I);
5744 }
5745 }
5746
5747 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005748 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005749 break;
5750 }
5751 }
5752
5753 return Changed ? &I : 0;
5754}
5755
5756Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5757 bool Changed = SimplifyCompare(I);
5758 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5759 const Type *Ty = Op0->getType();
5760
5761 // icmp X, X
5762 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005763 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005764 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005765
5766 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005767 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005768
Reid Spencere4d87aa2006-12-23 06:05:41 +00005769 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005770 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005771 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5772 isa<ConstantPointerNull>(Op0)) &&
5773 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005774 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005775 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005776 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005777
Reid Spencere4d87aa2006-12-23 06:05:41 +00005778 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005779 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005780 switch (I.getPredicate()) {
5781 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005782 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005783 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005784 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005785 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005786 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005787 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005788 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005789
Reid Spencere4d87aa2006-12-23 06:05:41 +00005790 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005791 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005792 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005793 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005794 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005795 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005796 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005797 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005798 case ICmpInst::ICMP_SGT:
5799 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005800 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005801 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5802 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5803 InsertNewInstBefore(Not, I);
5804 return BinaryOperator::CreateAnd(Not, Op0);
5805 }
5806 case ICmpInst::ICMP_UGE:
5807 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5808 // FALL THROUGH
5809 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005810 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005811 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005812 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005813 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005814 case ICmpInst::ICMP_SGE:
5815 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5816 // FALL THROUGH
5817 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5818 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5819 InsertNewInstBefore(Not, I);
5820 return BinaryOperator::CreateOr(Not, Op0);
5821 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005822 }
Chris Lattner8b170942002-08-09 23:47:40 +00005823 }
5824
Dan Gohman81b28ce2008-09-16 18:46:06 +00005825 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005826 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005827 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005828
Chris Lattnerb6566012008-01-05 01:18:20 +00005829 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5830 if (I.isEquality() && CI->isNullValue() &&
5831 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5832 // (icmp cond A B) if cond is equality
5833 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005834 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005835
Dan Gohman81b28ce2008-09-16 18:46:06 +00005836 // If we have an icmp le or icmp ge instruction, turn it into the
5837 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5838 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005839 switch (I.getPredicate()) {
5840 default: break;
5841 case ICmpInst::ICMP_ULE:
5842 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5843 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5844 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5845 case ICmpInst::ICMP_SLE:
5846 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5847 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5848 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5849 case ICmpInst::ICMP_UGE:
5850 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5851 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5852 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5853 case ICmpInst::ICMP_SGE:
5854 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5855 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5856 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5857 }
5858
Chris Lattner183661e2008-07-11 05:40:05 +00005859 // See if we can fold the comparison based on range information we can get
5860 // by checking whether bits are known to be zero or one in the input.
5861 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5862 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5863
5864 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005865 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005866 bool UnusedBit;
5867 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5868
Chris Lattner886ab6c2009-01-31 08:15:18 +00005869 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005870 isSignBit ? APInt::getSignBit(BitWidth)
5871 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005872 KnownZero, KnownOne, 0))
5873 return &I;
5874
5875 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005876 // in. Compute the Min, Max and RHS values based on the known bits. For the
5877 // EQ and NE we use unsigned values.
5878 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005879 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5880 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5881 else
5882 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5883
Chris Lattner183661e2008-07-11 05:40:05 +00005884 // If Min and Max are known to be the same, then SimplifyDemandedBits
5885 // figured out that the LHS is a constant. Just constant fold this now so
5886 // that code below can assume that Min != Max.
5887 if (Min == Max)
5888 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5889 ConstantInt::get(Min),
5890 CI));
5891
5892 // Based on the range information we know about the LHS, see if we can
5893 // simplify this comparison. For example, (x&4) < 8 is always true.
5894 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005895 switch (I.getPredicate()) { // LE/GE have been folded already.
5896 default: assert(0 && "Unknown icmp opcode!");
5897 case ICmpInst::ICMP_EQ:
5898 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5900 break;
5901 case ICmpInst::ICMP_NE:
5902 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5903 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5904 break;
5905 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005906 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005907 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005908 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005909 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005910 if (RHSVal == Max) // A <u MAX -> A != MAX
5911 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5912 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5913 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5914
5915 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5916 if (CI->isMinValue(true))
5917 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5918 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005919 break;
5920 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005921 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005922 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005923 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005924 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005925
5926 if (RHSVal == Min) // A >u MIN -> A != MIN
5927 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5928 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5929 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5930
5931 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5932 if (CI->isMaxValue(true))
5933 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5934 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005935 break;
5936 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005937 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005938 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005939 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005940 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005941 if (RHSVal == Max) // A <s MAX -> A != MAX
5942 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005943 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005944 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005945 break;
5946 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005947 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005948 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005949 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005950 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005951
5952 if (RHSVal == Min) // A >s MIN -> A != MIN
5953 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5954 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5955 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005956 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005957 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005958 }
5959
5960 // Test if the ICmpInst instruction is used exclusively by a select as
5961 // part of a minimum or maximum operation. If so, refrain from doing
5962 // any other folding. This helps out other analyses which understand
5963 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5964 // and CodeGen. And in this case, at least one of the comparison
5965 // operands has at least one user besides the compare (the select),
5966 // which would often largely negate the benefit of folding anyway.
5967 if (I.hasOneUse())
5968 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5969 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5970 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5971 return 0;
5972
5973 // See if we are doing a comparison between a constant and an instruction that
5974 // can be folded into the comparison.
5975 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005977 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005979 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005980 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5981 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005982 }
5983
Chris Lattner01deb9d2007-04-03 17:43:25 +00005984 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005985 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5986 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005988 case Instruction::GetElementPtr:
5989 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005991 bool isAllZeros = true;
5992 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5993 if (!isa<Constant>(LHSI->getOperand(i)) ||
5994 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5995 isAllZeros = false;
5996 break;
5997 }
5998 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005999 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006000 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6001 }
6002 break;
6003
Chris Lattner6970b662005-04-23 15:31:55 +00006004 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006005 // Only fold icmp into the PHI if the phi and fcmp are in the same
6006 // block. If in the same block, we're encouraging jump threading. If
6007 // not, we are just pessimizing the code by making an i1 phi.
6008 if (LHSI->getParent() == I.getParent())
6009 if (Instruction *NV = FoldOpIntoPhi(I))
6010 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006011 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006012 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006013 // If either operand of the select is a constant, we can fold the
6014 // comparison into the select arms, which will cause one to be
6015 // constant folded and the select turned into a bitwise or.
6016 Value *Op1 = 0, *Op2 = 0;
6017 if (LHSI->hasOneUse()) {
6018 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6019 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006020 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6021 // Insert a new ICmp of the other select operand.
6022 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6023 LHSI->getOperand(2), RHSC,
6024 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006025 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6026 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006027 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6028 // Insert a new ICmp of the other select operand.
6029 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6030 LHSI->getOperand(1), RHSC,
6031 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006032 }
6033 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006034
Chris Lattner6970b662005-04-23 15:31:55 +00006035 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006036 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006037 break;
6038 }
Chris Lattner4802d902007-04-06 18:57:34 +00006039 case Instruction::Malloc:
6040 // If we have (malloc != null), and if the malloc has a single use, we
6041 // can assume it is successful and remove the malloc.
6042 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6043 AddToWorkList(LHSI);
6044 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006045 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006046 }
6047 break;
6048 }
Chris Lattner6970b662005-04-23 15:31:55 +00006049 }
6050
Reid Spencere4d87aa2006-12-23 06:05:41 +00006051 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006052 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006053 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006054 return NI;
6055 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006056 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6057 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006058 return NI;
6059
Reid Spencere4d87aa2006-12-23 06:05:41 +00006060 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006061 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6062 // now.
6063 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6064 if (isa<PointerType>(Op0->getType()) &&
6065 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006066 // We keep moving the cast from the left operand over to the right
6067 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006068 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006069
Chris Lattner57d86372007-01-06 01:45:59 +00006070 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6071 // so eliminate it as well.
6072 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6073 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006074
Chris Lattnerde90b762003-11-03 04:25:02 +00006075 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006076 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006077 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006078 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006079 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006080 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006081 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006082 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006083 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006084 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006085 }
Chris Lattner57d86372007-01-06 01:45:59 +00006086 }
6087
6088 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006089 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006090 // This comes up when you have code like
6091 // int X = A < B;
6092 // if (X) ...
6093 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006094 // with a constant or another cast from the same type.
6095 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006096 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006097 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006098 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006099
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006100 // See if it's the same type of instruction on the left and right.
6101 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6102 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006103 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006104 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006105 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006106 default: break;
6107 case Instruction::Add:
6108 case Instruction::Sub:
6109 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006110 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006111 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6112 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006113 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6114 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6115 if (CI->getValue().isSignBit()) {
6116 ICmpInst::Predicate Pred = I.isSignedPredicate()
6117 ? I.getUnsignedPredicate()
6118 : I.getSignedPredicate();
6119 return new ICmpInst(Pred, Op0I->getOperand(0),
6120 Op1I->getOperand(0));
6121 }
6122
6123 if (CI->getValue().isMaxSignedValue()) {
6124 ICmpInst::Predicate Pred = I.isSignedPredicate()
6125 ? I.getUnsignedPredicate()
6126 : I.getSignedPredicate();
6127 Pred = I.getSwappedPredicate(Pred);
6128 return new ICmpInst(Pred, Op0I->getOperand(0),
6129 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006130 }
6131 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006132 break;
6133 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006134 if (!I.isEquality())
6135 break;
6136
Nick Lewycky5d52c452008-08-21 05:56:10 +00006137 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6138 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6139 // Mask = -1 >> count-trailing-zeros(Cst).
6140 if (!CI->isZero() && !CI->isOne()) {
6141 const APInt &AP = CI->getValue();
6142 ConstantInt *Mask = ConstantInt::get(
6143 APInt::getLowBitsSet(AP.getBitWidth(),
6144 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006145 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006146 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6147 Mask);
6148 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6149 Mask);
6150 InsertNewInstBefore(And1, I);
6151 InsertNewInstBefore(And2, I);
6152 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006153 }
6154 }
6155 break;
6156 }
6157 }
6158 }
6159 }
6160
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006161 // ~x < ~y --> y < x
6162 { Value *A, *B;
6163 if (match(Op0, m_Not(m_Value(A))) &&
6164 match(Op1, m_Not(m_Value(B))))
6165 return new ICmpInst(I.getPredicate(), B, A);
6166 }
6167
Chris Lattner65b72ba2006-09-18 04:22:48 +00006168 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006169 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006170
6171 // -x == -y --> x == y
6172 if (match(Op0, m_Neg(m_Value(A))) &&
6173 match(Op1, m_Neg(m_Value(B))))
6174 return new ICmpInst(I.getPredicate(), A, B);
6175
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006176 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6177 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6178 Value *OtherVal = A == Op1 ? B : A;
6179 return new ICmpInst(I.getPredicate(), OtherVal,
6180 Constant::getNullValue(A->getType()));
6181 }
6182
6183 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6184 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006185 ConstantInt *C1, *C2;
6186 if (match(B, m_ConstantInt(C1)) &&
6187 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6188 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6189 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6190 return new ICmpInst(I.getPredicate(), A,
6191 InsertNewInstBefore(Xor, I));
6192 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006193
6194 // A^B == A^D -> B == D
6195 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6196 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6197 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6198 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6199 }
6200 }
6201
6202 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6203 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006204 // A == (A^B) -> B == 0
6205 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006206 return new ICmpInst(I.getPredicate(), OtherVal,
6207 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006208 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006209
6210 // (A-B) == A -> B == 0
6211 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6212 return new ICmpInst(I.getPredicate(), B,
6213 Constant::getNullValue(B->getType()));
6214
6215 // A == (A-B) -> B == 0
6216 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006217 return new ICmpInst(I.getPredicate(), B,
6218 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006219
Chris Lattner9c2328e2006-11-14 06:06:06 +00006220 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6221 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6222 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6223 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6224 Value *X = 0, *Y = 0, *Z = 0;
6225
6226 if (A == C) {
6227 X = B; Y = D; Z = A;
6228 } else if (A == D) {
6229 X = B; Y = C; Z = A;
6230 } else if (B == C) {
6231 X = A; Y = D; Z = B;
6232 } else if (B == D) {
6233 X = A; Y = C; Z = B;
6234 }
6235
6236 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006237 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6238 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006239 I.setOperand(0, Op1);
6240 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6241 return &I;
6242 }
6243 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006244 }
Chris Lattner7e708292002-06-25 16:13:24 +00006245 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006246}
6247
Chris Lattner562ef782007-06-20 23:46:26 +00006248
6249/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6250/// and CmpRHS are both known to be integer constants.
6251Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6252 ConstantInt *DivRHS) {
6253 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6254 const APInt &CmpRHSV = CmpRHS->getValue();
6255
6256 // FIXME: If the operand types don't match the type of the divide
6257 // then don't attempt this transform. The code below doesn't have the
6258 // logic to deal with a signed divide and an unsigned compare (and
6259 // vice versa). This is because (x /s C1) <s C2 produces different
6260 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6261 // (x /u C1) <u C2. Simply casting the operands and result won't
6262 // work. :( The if statement below tests that condition and bails
6263 // if it finds it.
6264 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6265 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6266 return 0;
6267 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006268 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006269 if (DivIsSigned && DivRHS->isAllOnesValue())
6270 return 0; // The overflow computation also screws up here
6271 if (DivRHS->isOne())
6272 return 0; // Not worth bothering, and eliminates some funny cases
6273 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006274
6275 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6276 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6277 // C2 (CI). By solving for X we can turn this into a range check
6278 // instead of computing a divide.
6279 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6280
6281 // Determine if the product overflows by seeing if the product is
6282 // not equal to the divide. Make sure we do the same kind of divide
6283 // as in the LHS instruction that we're folding.
6284 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6285 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6286
6287 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006288 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006289
Chris Lattner1dbfd482007-06-21 18:11:19 +00006290 // Figure out the interval that is being checked. For example, a comparison
6291 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6292 // Compute this interval based on the constants involved and the signedness of
6293 // the compare/divide. This computes a half-open interval, keeping track of
6294 // whether either value in the interval overflows. After analysis each
6295 // overflow variable is set to 0 if it's corresponding bound variable is valid
6296 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6297 int LoOverflow = 0, HiOverflow = 0;
6298 ConstantInt *LoBound = 0, *HiBound = 0;
6299
Chris Lattner562ef782007-06-20 23:46:26 +00006300 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006301 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006302 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006303 HiOverflow = LoOverflow = ProdOV;
6304 if (!HiOverflow)
6305 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006306 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006307 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006308 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006309 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6310 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006311 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006312 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6313 HiOverflow = LoOverflow = ProdOV;
6314 if (!HiOverflow)
6315 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006316 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006317 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006318 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006319 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6320 if (!LoOverflow) {
6321 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6322 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6323 true) ? -1 : 0;
6324 }
Chris Lattner562ef782007-06-20 23:46:26 +00006325 }
Dan Gohman76491272008-02-13 22:09:18 +00006326 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006327 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006328 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006329 LoBound = AddOne(DivRHS);
6330 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006331 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6332 HiOverflow = 1; // [INTMIN+1, overflow)
6333 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6334 }
Dan Gohman76491272008-02-13 22:09:18 +00006335 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006336 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006337 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006338 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006339 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006340 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006341 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006342 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6343 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006344 if (!HiOverflow)
6345 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006346 }
6347
Chris Lattner1dbfd482007-06-21 18:11:19 +00006348 // Dividing by a negative swaps the condition. LT <-> GT
6349 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006350 }
6351
6352 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006353 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006354 default: assert(0 && "Unhandled icmp opcode!");
6355 case ICmpInst::ICMP_EQ:
6356 if (LoOverflow && HiOverflow)
6357 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6358 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006359 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006360 ICmpInst::ICMP_UGE, X, LoBound);
6361 else if (LoOverflow)
6362 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6363 ICmpInst::ICMP_ULT, X, HiBound);
6364 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006365 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006366 case ICmpInst::ICMP_NE:
6367 if (LoOverflow && HiOverflow)
6368 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6369 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006370 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006371 ICmpInst::ICMP_ULT, X, LoBound);
6372 else if (LoOverflow)
6373 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6374 ICmpInst::ICMP_UGE, X, HiBound);
6375 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006376 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006377 case ICmpInst::ICMP_ULT:
6378 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006379 if (LoOverflow == +1) // Low bound is greater than input range.
6380 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6381 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006382 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006383 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006384 case ICmpInst::ICMP_UGT:
6385 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006386 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006387 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006388 else if (HiOverflow == -1) // High bound less than input range.
6389 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6390 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006391 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6392 else
6393 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6394 }
6395}
6396
6397
Chris Lattner01deb9d2007-04-03 17:43:25 +00006398/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6399///
6400Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6401 Instruction *LHSI,
6402 ConstantInt *RHS) {
6403 const APInt &RHSV = RHS->getValue();
6404
6405 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006406 case Instruction::Trunc:
6407 if (ICI.isEquality() && LHSI->hasOneUse()) {
6408 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6409 // of the high bits truncated out of x are known.
6410 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6411 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6412 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6413 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6414 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6415
6416 // If all the high bits are known, we can do this xform.
6417 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6418 // Pull in the high bits from known-ones set.
6419 APInt NewRHS(RHS->getValue());
6420 NewRHS.zext(SrcBits);
6421 NewRHS |= KnownOne;
6422 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6423 ConstantInt::get(NewRHS));
6424 }
6425 }
6426 break;
6427
Duncan Sands0091bf22007-04-04 06:42:45 +00006428 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006429 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6430 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6431 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006432 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6433 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006434 Value *CompareVal = LHSI->getOperand(0);
6435
6436 // If the sign bit of the XorCST is not set, there is no change to
6437 // the operation, just stop using the Xor.
6438 if (!XorCST->getValue().isNegative()) {
6439 ICI.setOperand(0, CompareVal);
6440 AddToWorkList(LHSI);
6441 return &ICI;
6442 }
6443
6444 // Was the old condition true if the operand is positive?
6445 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6446
6447 // If so, the new one isn't.
6448 isTrueIfPositive ^= true;
6449
6450 if (isTrueIfPositive)
6451 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6452 else
6453 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6454 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006455
6456 if (LHSI->hasOneUse()) {
6457 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6458 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6459 const APInt &SignBit = XorCST->getValue();
6460 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6461 ? ICI.getUnsignedPredicate()
6462 : ICI.getSignedPredicate();
6463 return new ICmpInst(Pred, LHSI->getOperand(0),
6464 ConstantInt::get(RHSV ^ SignBit));
6465 }
6466
6467 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006468 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006469 const APInt &NotSignBit = XorCST->getValue();
6470 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6471 ? ICI.getUnsignedPredicate()
6472 : ICI.getSignedPredicate();
6473 Pred = ICI.getSwappedPredicate(Pred);
6474 return new ICmpInst(Pred, LHSI->getOperand(0),
6475 ConstantInt::get(RHSV ^ NotSignBit));
6476 }
6477 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006478 }
6479 break;
6480 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6481 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6482 LHSI->getOperand(0)->hasOneUse()) {
6483 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6484
6485 // If the LHS is an AND of a truncating cast, we can widen the
6486 // and/compare to be the input width without changing the value
6487 // produced, eliminating a cast.
6488 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6489 // We can do this transformation if either the AND constant does not
6490 // have its sign bit set or if it is an equality comparison.
6491 // Extending a relational comparison when we're checking the sign
6492 // bit would not work.
6493 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006494 (ICI.isEquality() ||
6495 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006496 uint32_t BitWidth =
6497 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6498 APInt NewCST = AndCST->getValue();
6499 NewCST.zext(BitWidth);
6500 APInt NewCI = RHSV;
6501 NewCI.zext(BitWidth);
6502 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006503 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006504 ConstantInt::get(NewCST),LHSI->getName());
6505 InsertNewInstBefore(NewAnd, ICI);
6506 return new ICmpInst(ICI.getPredicate(), NewAnd,
6507 ConstantInt::get(NewCI));
6508 }
6509 }
6510
6511 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6512 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6513 // happens a LOT in code produced by the C front-end, for bitfield
6514 // access.
6515 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6516 if (Shift && !Shift->isShift())
6517 Shift = 0;
6518
6519 ConstantInt *ShAmt;
6520 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6521 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6522 const Type *AndTy = AndCST->getType(); // Type of the and.
6523
6524 // We can fold this as long as we can't shift unknown bits
6525 // into the mask. This can only happen with signed shift
6526 // rights, as they sign-extend.
6527 if (ShAmt) {
6528 bool CanFold = Shift->isLogicalShift();
6529 if (!CanFold) {
6530 // To test for the bad case of the signed shr, see if any
6531 // of the bits shifted in could be tested after the mask.
6532 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6533 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6534
6535 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6536 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6537 AndCST->getValue()) == 0)
6538 CanFold = true;
6539 }
6540
6541 if (CanFold) {
6542 Constant *NewCst;
6543 if (Shift->getOpcode() == Instruction::Shl)
6544 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6545 else
6546 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6547
6548 // Check to see if we are shifting out any of the bits being
6549 // compared.
6550 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6551 // If we shifted bits out, the fold is not going to work out.
6552 // As a special case, check to see if this means that the
6553 // result is always true or false now.
6554 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6555 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6556 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6557 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6558 } else {
6559 ICI.setOperand(1, NewCst);
6560 Constant *NewAndCST;
6561 if (Shift->getOpcode() == Instruction::Shl)
6562 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6563 else
6564 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6565 LHSI->setOperand(1, NewAndCST);
6566 LHSI->setOperand(0, Shift->getOperand(0));
6567 AddToWorkList(Shift); // Shift is dead.
6568 AddUsesToWorkList(ICI);
6569 return &ICI;
6570 }
6571 }
6572 }
6573
6574 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6575 // preferable because it allows the C<<Y expression to be hoisted out
6576 // of a loop if Y is invariant and X is not.
6577 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6578 ICI.isEquality() && !Shift->isArithmeticShift() &&
6579 isa<Instruction>(Shift->getOperand(0))) {
6580 // Compute C << Y.
6581 Value *NS;
6582 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006583 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006584 Shift->getOperand(1), "tmp");
6585 } else {
6586 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006587 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006588 Shift->getOperand(1), "tmp");
6589 }
6590 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6591
6592 // Compute X & (C << Y).
6593 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006594 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006595 InsertNewInstBefore(NewAnd, ICI);
6596
6597 ICI.setOperand(0, NewAnd);
6598 return &ICI;
6599 }
6600 }
6601 break;
6602
Chris Lattnera0141b92007-07-15 20:42:37 +00006603 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6604 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6605 if (!ShAmt) break;
6606
6607 uint32_t TypeBits = RHSV.getBitWidth();
6608
6609 // Check that the shift amount is in range. If not, don't perform
6610 // undefined shifts. When the shift is visited it will be
6611 // simplified.
6612 if (ShAmt->uge(TypeBits))
6613 break;
6614
6615 if (ICI.isEquality()) {
6616 // If we are comparing against bits always shifted out, the
6617 // comparison cannot succeed.
6618 Constant *Comp =
6619 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6620 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6621 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6622 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6623 return ReplaceInstUsesWith(ICI, Cst);
6624 }
6625
6626 if (LHSI->hasOneUse()) {
6627 // Otherwise strength reduce the shift into an and.
6628 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6629 Constant *Mask =
6630 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006631
Chris Lattnera0141b92007-07-15 20:42:37 +00006632 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006633 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006634 Mask, LHSI->getName()+".mask");
6635 Value *And = InsertNewInstBefore(AndI, ICI);
6636 return new ICmpInst(ICI.getPredicate(), And,
6637 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006638 }
6639 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006640
6641 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6642 bool TrueIfSigned = false;
6643 if (LHSI->hasOneUse() &&
6644 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6645 // (X << 31) <s 0 --> (X&1) != 0
6646 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6647 (TypeBits-ShAmt->getZExtValue()-1));
6648 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006649 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006650 Mask, LHSI->getName()+".mask");
6651 Value *And = InsertNewInstBefore(AndI, ICI);
6652
6653 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6654 And, Constant::getNullValue(And->getType()));
6655 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006656 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006657 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006658
6659 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006660 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006661 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006662 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006663 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006664
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006665 // Check that the shift amount is in range. If not, don't perform
6666 // undefined shifts. When the shift is visited it will be
6667 // simplified.
6668 uint32_t TypeBits = RHSV.getBitWidth();
6669 if (ShAmt->uge(TypeBits))
6670 break;
6671
6672 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006673
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006674 // If we are comparing against bits always shifted out, the
6675 // comparison cannot succeed.
6676 APInt Comp = RHSV << ShAmtVal;
6677 if (LHSI->getOpcode() == Instruction::LShr)
6678 Comp = Comp.lshr(ShAmtVal);
6679 else
6680 Comp = Comp.ashr(ShAmtVal);
6681
6682 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6683 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6684 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6685 return ReplaceInstUsesWith(ICI, Cst);
6686 }
6687
6688 // Otherwise, check to see if the bits shifted out are known to be zero.
6689 // If so, we can compare against the unshifted value:
6690 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006691 if (LHSI->hasOneUse() &&
6692 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006693 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6694 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6695 ConstantExpr::getShl(RHS, ShAmt));
6696 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006697
Evan Chengf30752c2008-04-23 00:38:06 +00006698 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006699 // Otherwise strength reduce the shift into an and.
6700 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6701 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006702
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006703 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006704 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006705 Mask, LHSI->getName()+".mask");
6706 Value *And = InsertNewInstBefore(AndI, ICI);
6707 return new ICmpInst(ICI.getPredicate(), And,
6708 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006709 }
6710 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006711 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006712
6713 case Instruction::SDiv:
6714 case Instruction::UDiv:
6715 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6716 // Fold this div into the comparison, producing a range check.
6717 // Determine, based on the divide type, what the range is being
6718 // checked. If there is an overflow on the low or high side, remember
6719 // it, otherwise compute the range [low, hi) bounding the new value.
6720 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006721 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6722 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6723 DivRHS))
6724 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006725 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006726
6727 case Instruction::Add:
6728 // Fold: icmp pred (add, X, C1), C2
6729
6730 if (!ICI.isEquality()) {
6731 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6732 if (!LHSC) break;
6733 const APInt &LHSV = LHSC->getValue();
6734
6735 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6736 .subtract(LHSV);
6737
6738 if (ICI.isSignedPredicate()) {
6739 if (CR.getLower().isSignBit()) {
6740 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6741 ConstantInt::get(CR.getUpper()));
6742 } else if (CR.getUpper().isSignBit()) {
6743 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6744 ConstantInt::get(CR.getLower()));
6745 }
6746 } else {
6747 if (CR.getLower().isMinValue()) {
6748 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6749 ConstantInt::get(CR.getUpper()));
6750 } else if (CR.getUpper().isMinValue()) {
6751 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6752 ConstantInt::get(CR.getLower()));
6753 }
6754 }
6755 }
6756 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 }
6758
6759 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6760 if (ICI.isEquality()) {
6761 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6762
6763 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6764 // the second operand is a constant, simplify a bit.
6765 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6766 switch (BO->getOpcode()) {
6767 case Instruction::SRem:
6768 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6769 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6770 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6771 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6772 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006773 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006774 BO->getName());
6775 InsertNewInstBefore(NewRem, ICI);
6776 return new ICmpInst(ICI.getPredicate(), NewRem,
6777 Constant::getNullValue(BO->getType()));
6778 }
6779 }
6780 break;
6781 case Instruction::Add:
6782 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6783 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6784 if (BO->hasOneUse())
6785 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6786 Subtract(RHS, BOp1C));
6787 } else if (RHSV == 0) {
6788 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6789 // efficiently invertible, or if the add has just this one use.
6790 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6791
6792 if (Value *NegVal = dyn_castNegVal(BOp1))
6793 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6794 else if (Value *NegVal = dyn_castNegVal(BOp0))
6795 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6796 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006797 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798 InsertNewInstBefore(Neg, ICI);
6799 Neg->takeName(BO);
6800 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6801 }
6802 }
6803 break;
6804 case Instruction::Xor:
6805 // For the xor case, we can xor two constants together, eliminating
6806 // the explicit xor.
6807 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6808 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6809 ConstantExpr::getXor(RHS, BOC));
6810
6811 // FALLTHROUGH
6812 case Instruction::Sub:
6813 // Replace (([sub|xor] A, B) != 0) with (A != B)
6814 if (RHSV == 0)
6815 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6816 BO->getOperand(1));
6817 break;
6818
6819 case Instruction::Or:
6820 // If bits are being or'd in that are not present in the constant we
6821 // are comparing against, then the comparison could never succeed!
6822 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6823 Constant *NotCI = ConstantExpr::getNot(RHS);
6824 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6825 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6826 isICMP_NE));
6827 }
6828 break;
6829
6830 case Instruction::And:
6831 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6832 // If bits are being compared against that are and'd out, then the
6833 // comparison can never succeed!
6834 if ((RHSV & ~BOC->getValue()) != 0)
6835 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6836 isICMP_NE));
6837
6838 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6839 if (RHS == BOC && RHSV.isPowerOf2())
6840 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6841 ICmpInst::ICMP_NE, LHSI,
6842 Constant::getNullValue(RHS->getType()));
6843
6844 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006845 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006846 Value *X = BO->getOperand(0);
6847 Constant *Zero = Constant::getNullValue(X->getType());
6848 ICmpInst::Predicate pred = isICMP_NE ?
6849 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6850 return new ICmpInst(pred, X, Zero);
6851 }
6852
6853 // ((X & ~7) == 0) --> X < 8
6854 if (RHSV == 0 && isHighOnes(BOC)) {
6855 Value *X = BO->getOperand(0);
6856 Constant *NegX = ConstantExpr::getNeg(BOC);
6857 ICmpInst::Predicate pred = isICMP_NE ?
6858 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6859 return new ICmpInst(pred, X, NegX);
6860 }
6861 }
6862 default: break;
6863 }
6864 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6865 // Handle icmp {eq|ne} <intrinsic>, intcst.
6866 if (II->getIntrinsicID() == Intrinsic::bswap) {
6867 AddToWorkList(II);
6868 ICI.setOperand(0, II->getOperand(1));
6869 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6870 return &ICI;
6871 }
6872 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 }
6874 return 0;
6875}
6876
6877/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6878/// We only handle extending casts so far.
6879///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006880Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6881 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006882 Value *LHSCIOp = LHSCI->getOperand(0);
6883 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006884 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006885 Value *RHSCIOp;
6886
Chris Lattner8c756c12007-05-05 22:41:33 +00006887 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6888 // integer type is the same size as the pointer type.
6889 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6890 getTargetData().getPointerSizeInBits() ==
6891 cast<IntegerType>(DestTy)->getBitWidth()) {
6892 Value *RHSOp = 0;
6893 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006894 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006895 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6896 RHSOp = RHSC->getOperand(0);
6897 // If the pointer types don't match, insert a bitcast.
6898 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006899 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006900 }
6901
6902 if (RHSOp)
6903 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6904 }
6905
6906 // The code below only handles extension cast instructions, so far.
6907 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006908 if (LHSCI->getOpcode() != Instruction::ZExt &&
6909 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006910 return 0;
6911
Reid Spencere4d87aa2006-12-23 06:05:41 +00006912 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6913 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006914
Reid Spencere4d87aa2006-12-23 06:05:41 +00006915 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006916 // Not an extension from the same type?
6917 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006918 if (RHSCIOp->getType() != LHSCIOp->getType())
6919 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006920
Nick Lewycky4189a532008-01-28 03:48:02 +00006921 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006922 // and the other is a zext), then we can't handle this.
6923 if (CI->getOpcode() != LHSCI->getOpcode())
6924 return 0;
6925
Nick Lewycky4189a532008-01-28 03:48:02 +00006926 // Deal with equality cases early.
6927 if (ICI.isEquality())
6928 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6929
6930 // A signed comparison of sign extended values simplifies into a
6931 // signed comparison.
6932 if (isSignedCmp && isSignedExt)
6933 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6934
6935 // The other three cases all fold into an unsigned comparison.
6936 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006937 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006938
Reid Spencere4d87aa2006-12-23 06:05:41 +00006939 // If we aren't dealing with a constant on the RHS, exit early
6940 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6941 if (!CI)
6942 return 0;
6943
6944 // Compute the constant that would happen if we truncated to SrcTy then
6945 // reextended to DestTy.
6946 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6947 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6948
6949 // If the re-extended constant didn't change...
6950 if (Res2 == CI) {
6951 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6952 // For example, we might have:
6953 // %A = sext short %X to uint
6954 // %B = icmp ugt uint %A, 1330
6955 // It is incorrect to transform this into
6956 // %B = icmp ugt short %X, 1330
6957 // because %A may have negative value.
6958 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006959 // However, we allow this when the compare is EQ/NE, because they are
6960 // signless.
6961 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006962 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006963 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006964 }
6965
6966 // The re-extended constant changed so the constant cannot be represented
6967 // in the shorter type. Consequently, we cannot emit a simple comparison.
6968
6969 // First, handle some easy cases. We know the result cannot be equal at this
6970 // point so handle the ICI.isEquality() cases
6971 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006972 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006973 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006974 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006975
6976 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6977 // should have been folded away previously and not enter in here.
6978 Value *Result;
6979 if (isSignedCmp) {
6980 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006981 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006982 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006983 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006984 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006985 } else {
6986 // We're performing an unsigned comparison.
6987 if (isSignedExt) {
6988 // We're performing an unsigned comp with a sign extended value.
6989 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006990 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006991 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6992 NegOne, ICI.getName()), ICI);
6993 } else {
6994 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006995 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006996 }
6997 }
6998
6999 // Finally, return the value computed.
7000 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007001 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007002 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007003
7004 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7005 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7006 "ICmp should be folded!");
7007 if (Constant *CI = dyn_cast<Constant>(Result))
7008 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7009 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007010}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007011
Reid Spencer832254e2007-02-02 02:16:23 +00007012Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7013 return commonShiftTransforms(I);
7014}
7015
7016Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7017 return commonShiftTransforms(I);
7018}
7019
7020Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007021 if (Instruction *R = commonShiftTransforms(I))
7022 return R;
7023
7024 Value *Op0 = I.getOperand(0);
7025
7026 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7027 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7028 if (CSI->isAllOnesValue())
7029 return ReplaceInstUsesWith(I, CSI);
7030
7031 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb44b3662009-03-18 16:32:19 +00007032 if (!isa<VectorType>(I.getType())) {
7033 if (MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007034 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Chris Lattnerb44b3662009-03-18 16:32:19 +00007035 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman0001e562009-02-24 02:00:40 +00007036
Chris Lattnerb44b3662009-03-18 16:32:19 +00007037 // Arithmetic shifting an all-sign-bit value is a no-op.
7038 unsigned NumSignBits = ComputeNumSignBits(Op0);
7039 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7040 return ReplaceInstUsesWith(I, Op0);
7041 }
Dan Gohman0001e562009-02-24 02:00:40 +00007042
Chris Lattner348f6652007-12-06 01:59:46 +00007043 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007044}
7045
7046Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7047 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007049
7050 // shl X, 0 == X and shr X, 0 == X
7051 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007052 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007053 Op0 == Constant::getNullValue(Op0->getType()))
7054 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007055
Reid Spencere4d87aa2006-12-23 06:05:41 +00007056 if (isa<UndefValue>(Op0)) {
7057 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007058 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007059 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7061 }
7062 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007063 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7064 return ReplaceInstUsesWith(I, Op0);
7065 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007067 }
7068
Chris Lattner2eefe512004-04-09 19:05:30 +00007069 // Try to fold constant and into select arguments.
7070 if (isa<Constant>(Op0))
7071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007072 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007073 return R;
7074
Reid Spencerb83eb642006-10-20 07:07:24 +00007075 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007076 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7077 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007078 return 0;
7079}
7080
Reid Spencerb83eb642006-10-20 07:07:24 +00007081Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007082 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007083 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007084
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007085 // See if we can simplify any instructions used by the instruction whose sole
7086 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007087 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00007088 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007089 return &I;
7090
Chris Lattner4d5542c2006-01-06 07:12:35 +00007091 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7092 // of a signed value.
7093 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007094 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007095 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007096 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7097 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007098 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007099 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007100 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007101 }
7102
7103 // ((X*C1) << C2) == (X * (C1 << C2))
7104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7105 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7106 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007107 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007108 ConstantExpr::getShl(BOOp, Op1));
7109
7110 // Try to fold constant and into select arguments.
7111 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7113 return R;
7114 if (isa<PHINode>(Op0))
7115 if (Instruction *NV = FoldOpIntoPhi(I))
7116 return NV;
7117
Chris Lattner8999dd32007-12-22 09:07:47 +00007118 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7119 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7120 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7121 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7122 // place. Don't try to do this transformation in this case. Also, we
7123 // require that the input operand is a shift-by-constant so that we have
7124 // confidence that the shifts will get folded together. We could do this
7125 // xform in more cases, but it is unlikely to be profitable.
7126 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7127 isa<ConstantInt>(TrOp->getOperand(1))) {
7128 // Okay, we'll do this xform. Make the shift of shift.
7129 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007130 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007131 I.getName());
7132 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7133
7134 // For logical shifts, the truncation has the effect of making the high
7135 // part of the register be zeros. Emulate this by inserting an AND to
7136 // clear the top bits as needed. This 'and' will usually be zapped by
7137 // other xforms later if dead.
7138 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7139 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7140 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7141
7142 // The mask we constructed says what the trunc would do if occurring
7143 // between the shifts. We want to know the effect *after* the second
7144 // shift. We know that it is a logical shift by a constant, so adjust the
7145 // mask as appropriate.
7146 if (I.getOpcode() == Instruction::Shl)
7147 MaskV <<= Op1->getZExtValue();
7148 else {
7149 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7150 MaskV = MaskV.lshr(Op1->getZExtValue());
7151 }
7152
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007153 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007154 TI->getName());
7155 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7156
7157 // Return the value truncated to the interesting size.
7158 return new TruncInst(And, I.getType());
7159 }
7160 }
7161
Chris Lattner4d5542c2006-01-06 07:12:35 +00007162 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007163 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7164 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7165 Value *V1, *V2;
7166 ConstantInt *CC;
7167 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007168 default: break;
7169 case Instruction::Add:
7170 case Instruction::And:
7171 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007172 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007173 // These operators commute.
7174 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007175 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007176 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007177 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007178 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007179 Op0BO->getName());
7180 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007181 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007182 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007183 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007184 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007185 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007186 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007187 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007188 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007189
Chris Lattner150f12a2005-09-18 06:30:59 +00007190 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007191 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007192 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007193 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007194 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7195 m_ConstantInt(CC))) &&
7196 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007197 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007198 Op0BO->getOperand(0), Op1,
7199 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007200 InsertNewInstBefore(YS, I); // (Y << C)
7201 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007202 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007203 V1->getName()+".mask");
7204 InsertNewInstBefore(XM, I); // X & (CC << C)
7205
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007206 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007207 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007208 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007209
Reid Spencera07cb7d2007-02-02 14:41:37 +00007210 // FALL THROUGH.
7211 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007212 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007213 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007214 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007215 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007216 Op0BO->getOperand(1), Op1,
7217 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007218 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007219 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007220 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007221 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007222 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007223 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007224 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007225 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007226 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007227
Chris Lattner13d4ab42006-05-31 21:14:00 +00007228 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007229 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7230 match(Op0BO->getOperand(0),
7231 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007232 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007233 cast<BinaryOperator>(Op0BO->getOperand(0))
7234 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007235 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007236 Op0BO->getOperand(1), Op1,
7237 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007238 InsertNewInstBefore(YS, I); // (Y << C)
7239 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007240 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007241 V1->getName()+".mask");
7242 InsertNewInstBefore(XM, I); // X & (CC << C)
7243
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007244 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007245 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007246
Chris Lattner11021cb2005-09-18 05:12:10 +00007247 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007248 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007249 }
7250
7251
7252 // If the operand is an bitwise operator with a constant RHS, and the
7253 // shift is the only use, we can pull it out of the shift.
7254 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7255 bool isValid = true; // Valid only for And, Or, Xor
7256 bool highBitSet = false; // Transform if high bit of constant set?
7257
7258 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007259 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007260 case Instruction::Add:
7261 isValid = isLeftShift;
7262 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007263 case Instruction::Or:
7264 case Instruction::Xor:
7265 highBitSet = false;
7266 break;
7267 case Instruction::And:
7268 highBitSet = true;
7269 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007270 }
7271
7272 // If this is a signed shift right, and the high bit is modified
7273 // by the logical operation, do not perform the transformation.
7274 // The highBitSet boolean indicates the value of the high bit of
7275 // the constant which would cause it to be modified for this
7276 // operation.
7277 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007278 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007279 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007280
7281 if (isValid) {
7282 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7283
7284 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007285 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007286 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007287 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007288
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007289 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007290 NewRHS);
7291 }
7292 }
7293 }
7294 }
7295
Chris Lattnerad0124c2006-01-06 07:52:12 +00007296 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007297 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7298 if (ShiftOp && !ShiftOp->isShift())
7299 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007300
Reid Spencerb83eb642006-10-20 07:07:24 +00007301 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007302 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007303 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7304 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007305 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7306 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7307 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007308
Zhou Sheng4351c642007-04-02 08:20:41 +00007309 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007310
7311 const IntegerType *Ty = cast<IntegerType>(I.getType());
7312
7313 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007314 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007315 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7316 // saturates.
7317 if (AmtSum >= TypeBits) {
7318 if (I.getOpcode() != Instruction::AShr)
7319 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7320 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7321 }
7322
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007323 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007324 ConstantInt::get(Ty, AmtSum));
7325 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7326 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007327 if (AmtSum >= TypeBits)
7328 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7329
Chris Lattnerb87056f2007-02-05 00:57:54 +00007330 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007331 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007332 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7333 I.getOpcode() == Instruction::LShr) {
7334 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007335 if (AmtSum >= TypeBits)
7336 AmtSum = TypeBits-1;
7337
Chris Lattnerb87056f2007-02-05 00:57:54 +00007338 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007339 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007340 InsertNewInstBefore(Shift, I);
7341
Zhou Shenge9e03f62007-03-28 15:02:20 +00007342 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007343 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007344 }
7345
Chris Lattnerb87056f2007-02-05 00:57:54 +00007346 // Okay, if we get here, one shift must be left, and the other shift must be
7347 // right. See if the amounts are equal.
7348 if (ShiftAmt1 == ShiftAmt2) {
7349 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7350 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007351 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007352 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007353 }
7354 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7355 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007356 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007357 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007358 }
7359 // We can simplify ((X << C) >>s C) into a trunc + sext.
7360 // NOTE: we could do this for any C, but that would make 'unusual' integer
7361 // types. For now, just stick to ones well-supported by the code
7362 // generators.
7363 const Type *SExtType = 0;
7364 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007365 case 1 :
7366 case 8 :
7367 case 16 :
7368 case 32 :
7369 case 64 :
7370 case 128:
7371 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7372 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007373 default: break;
7374 }
7375 if (SExtType) {
7376 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7377 InsertNewInstBefore(NewTrunc, I);
7378 return new SExtInst(NewTrunc, Ty);
7379 }
7380 // Otherwise, we can't handle it yet.
7381 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007382 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007383
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007384 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007385 if (I.getOpcode() == Instruction::Shl) {
7386 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7387 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007388 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007390 InsertNewInstBefore(Shift, I);
7391
Reid Spencer55702aa2007-03-25 21:11:44 +00007392 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007393 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007394 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007395
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007396 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007397 if (I.getOpcode() == Instruction::LShr) {
7398 assert(ShiftOp->getOpcode() == Instruction::Shl);
7399 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007400 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007401 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007402
Reid Spencerd5e30f02007-03-26 17:18:58 +00007403 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007404 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007405 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007406
7407 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7408 } else {
7409 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007410 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007411
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007412 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007413 if (I.getOpcode() == Instruction::Shl) {
7414 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7415 ShiftOp->getOpcode() == Instruction::AShr);
7416 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007417 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007418 ConstantInt::get(Ty, ShiftDiff));
7419 InsertNewInstBefore(Shift, I);
7420
Reid Spencer55702aa2007-03-25 21:11:44 +00007421 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007422 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007423 }
7424
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007425 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007426 if (I.getOpcode() == Instruction::LShr) {
7427 assert(ShiftOp->getOpcode() == Instruction::Shl);
7428 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007429 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007430 InsertNewInstBefore(Shift, I);
7431
Reid Spencer68d27cf2007-03-26 23:45:51 +00007432 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007433 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007434 }
7435
7436 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007437 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007438 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007439 return 0;
7440}
7441
Chris Lattnera1be5662002-05-02 17:06:02 +00007442
Chris Lattnercfd65102005-10-29 04:36:15 +00007443/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7444/// expression. If so, decompose it, returning some value X, such that Val is
7445/// X*Scale+Offset.
7446///
7447static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007448 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007449 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007450 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007451 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007452 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007453 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007454 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7456 if (I->getOpcode() == Instruction::Shl) {
7457 // This is a value scaled by '1 << the shift amt'.
7458 Scale = 1U << RHS->getZExtValue();
7459 Offset = 0;
7460 return I->getOperand(0);
7461 } else if (I->getOpcode() == Instruction::Mul) {
7462 // This value is scaled by 'RHS'.
7463 Scale = RHS->getZExtValue();
7464 Offset = 0;
7465 return I->getOperand(0);
7466 } else if (I->getOpcode() == Instruction::Add) {
7467 // We have X+C. Check to see if we really have (X*C2)+C1,
7468 // where C1 is divisible by C2.
7469 unsigned SubScale;
7470 Value *SubVal =
7471 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7472 Offset += RHS->getZExtValue();
7473 Scale = SubScale;
7474 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007475 }
7476 }
7477 }
7478
7479 // Otherwise, we can't look past this.
7480 Scale = 1;
7481 Offset = 0;
7482 return Val;
7483}
7484
7485
Chris Lattnerb3f83972005-10-24 06:03:58 +00007486/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7487/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007488Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007489 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007490 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007491
Chris Lattnerb53c2382005-10-24 06:22:12 +00007492 // Remove any uses of AI that are dead.
7493 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007494
Chris Lattnerb53c2382005-10-24 06:22:12 +00007495 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7496 Instruction *User = cast<Instruction>(*UI++);
7497 if (isInstructionTriviallyDead(User)) {
7498 while (UI != E && *UI == User)
7499 ++UI; // If this instruction uses AI more than once, don't break UI.
7500
Chris Lattnerb53c2382005-10-24 06:22:12 +00007501 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007502 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007503 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007504 }
7505 }
7506
Chris Lattnerb3f83972005-10-24 06:03:58 +00007507 // Get the type really allocated and the type casted to.
7508 const Type *AllocElTy = AI.getAllocatedType();
7509 const Type *CastElTy = PTy->getElementType();
7510 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007511
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007512 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7513 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007514 if (CastElTyAlign < AllocElTyAlign) return 0;
7515
Chris Lattner39387a52005-10-24 06:35:18 +00007516 // If the allocation has multiple uses, only promote it if we are strictly
7517 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007518 // same, we open the door to infinite loops of various kinds. (A reference
7519 // from a dbg.declare doesn't count as a use for this purpose.)
7520 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7521 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007522
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007523 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7524 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007525 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007526
Chris Lattner455fcc82005-10-29 03:19:53 +00007527 // See if we can satisfy the modulus by pulling a scale out of the array
7528 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007529 unsigned ArraySizeScale;
7530 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007531 Value *NumElements = // See if the array size is a decomposable linear expr.
7532 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7533
Chris Lattner455fcc82005-10-29 03:19:53 +00007534 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7535 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007536 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7537 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007538
Chris Lattner455fcc82005-10-29 03:19:53 +00007539 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7540 Value *Amt = 0;
7541 if (Scale == 1) {
7542 Amt = NumElements;
7543 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007544 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007545 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7546 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007547 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007548 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007549 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007550 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007551 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007552 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007553 }
7554
Jeff Cohen86796be2007-04-04 16:58:57 +00007555 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7556 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007557 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007558 Amt = InsertNewInstBefore(Tmp, AI);
7559 }
7560
Chris Lattnerb3f83972005-10-24 06:03:58 +00007561 AllocationInst *New;
7562 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007563 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007564 else
Chris Lattner6934a042007-02-11 01:23:03 +00007565 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007566 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007567 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007568
Dale Johannesena0a66372009-03-05 00:39:02 +00007569 // If the allocation has one real use plus a dbg.declare, just remove the
7570 // declare.
7571 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7572 EraseInstFromFunction(*DI);
7573 }
7574 // If the allocation has multiple real uses, insert a cast and change all
7575 // things that used it to use the new cast. This will also hack on CI, but it
7576 // will die soon.
7577 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007578 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007579 // New is the allocation instruction, pointer typed. AI is the original
7580 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7581 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007582 InsertNewInstBefore(NewCast, AI);
7583 AI.replaceAllUsesWith(NewCast);
7584 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007585 return ReplaceInstUsesWith(CI, New);
7586}
7587
Chris Lattner70074e02006-05-13 02:06:03 +00007588/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007589/// and return it as type Ty without inserting any new casts and without
7590/// changing the computed value. This is used by code that tries to decide
7591/// whether promoting or shrinking integer operations to wider or smaller types
7592/// will allow us to eliminate a truncate or extend.
7593///
7594/// This is a truncation operation if Ty is smaller than V->getType(), or an
7595/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007596///
7597/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7598/// should return true if trunc(V) can be computed by computing V in the smaller
7599/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7600/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7601/// efficiently truncated.
7602///
7603/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7604/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7605/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007606bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7607 unsigned CastOpc,
7608 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007609 // We can always evaluate constants in another type.
7610 if (isa<ConstantInt>(V))
7611 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007612
7613 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007614 if (!I) return false;
7615
7616 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007617
Chris Lattner951626b2007-08-02 06:11:14 +00007618 // If this is an extension or truncate, we can often eliminate it.
7619 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7620 // If this is a cast from the destination type, we can trivially eliminate
7621 // it, and this will remove a cast overall.
7622 if (I->getOperand(0)->getType() == Ty) {
7623 // If the first operand is itself a cast, and is eliminable, do not count
7624 // this as an eliminable cast. We would prefer to eliminate those two
7625 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007626 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007627 ++NumCastsRemoved;
7628 return true;
7629 }
7630 }
7631
7632 // We can't extend or shrink something that has multiple uses: doing so would
7633 // require duplicating the instruction in general, which isn't profitable.
7634 if (!I->hasOneUse()) return false;
7635
Evan Chengf35fd542009-01-15 17:01:23 +00007636 unsigned Opc = I->getOpcode();
7637 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007638 case Instruction::Add:
7639 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007640 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007641 case Instruction::And:
7642 case Instruction::Or:
7643 case Instruction::Xor:
7644 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007645 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007646 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007647 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007648 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007649
Chris Lattner46b96052006-11-29 07:18:39 +00007650 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007651 // If we are truncating the result of this SHL, and if it's a shift of a
7652 // constant amount, we can always perform a SHL in a smaller type.
7653 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007654 uint32_t BitWidth = Ty->getBitWidth();
7655 if (BitWidth < OrigTy->getBitWidth() &&
7656 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007657 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007658 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007659 }
7660 break;
7661 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007662 // If this is a truncate of a logical shr, we can truncate it to a smaller
7663 // lshr iff we know that the bits we would otherwise be shifting in are
7664 // already zeros.
7665 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007666 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7667 uint32_t BitWidth = Ty->getBitWidth();
7668 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007669 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007670 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7671 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007672 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007673 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007674 }
7675 }
Chris Lattner46b96052006-11-29 07:18:39 +00007676 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007677 case Instruction::ZExt:
7678 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007679 case Instruction::Trunc:
7680 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007681 // can safely replace it. Note that replacing it does not reduce the number
7682 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007683 if (Opc == CastOpc)
7684 return true;
7685
7686 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007687 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007688 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007689 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007690 case Instruction::Select: {
7691 SelectInst *SI = cast<SelectInst>(I);
7692 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007693 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007694 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007695 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007696 }
Chris Lattner8114b712008-06-18 04:00:49 +00007697 case Instruction::PHI: {
7698 // We can change a phi if we can change all operands.
7699 PHINode *PN = cast<PHINode>(I);
7700 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7701 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007702 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007703 return false;
7704 return true;
7705 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007706 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007707 // TODO: Can handle more cases here.
7708 break;
7709 }
7710
7711 return false;
7712}
7713
7714/// EvaluateInDifferentType - Given an expression that
7715/// CanEvaluateInDifferentType returns true for, actually insert the code to
7716/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007717Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007718 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007719 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007720 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007721
7722 // Otherwise, it must be an instruction.
7723 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007724 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007725 unsigned Opc = I->getOpcode();
7726 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007727 case Instruction::Add:
7728 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007729 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007730 case Instruction::And:
7731 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007732 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007733 case Instruction::AShr:
7734 case Instruction::LShr:
7735 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007736 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007737 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007738 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007739 break;
7740 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007741 case Instruction::Trunc:
7742 case Instruction::ZExt:
7743 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007744 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007745 // just return the source. There's no need to insert it because it is not
7746 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007747 if (I->getOperand(0)->getType() == Ty)
7748 return I->getOperand(0);
7749
Chris Lattner8114b712008-06-18 04:00:49 +00007750 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007751 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007752 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007753 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007754 case Instruction::Select: {
7755 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7756 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7757 Res = SelectInst::Create(I->getOperand(0), True, False);
7758 break;
7759 }
Chris Lattner8114b712008-06-18 04:00:49 +00007760 case Instruction::PHI: {
7761 PHINode *OPN = cast<PHINode>(I);
7762 PHINode *NPN = PHINode::Create(Ty);
7763 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7764 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7765 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7766 }
7767 Res = NPN;
7768 break;
7769 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007770 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007771 // TODO: Can handle more cases here.
7772 assert(0 && "Unreachable!");
7773 break;
7774 }
7775
Chris Lattner8114b712008-06-18 04:00:49 +00007776 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007777 return InsertNewInstBefore(Res, *I);
7778}
7779
Reid Spencer3da59db2006-11-27 01:05:10 +00007780/// @brief Implement the transforms common to all CastInst visitors.
7781Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007782 Value *Src = CI.getOperand(0);
7783
Dan Gohman23d9d272007-05-11 21:10:54 +00007784 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007785 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007786 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007787 if (Instruction::CastOps opc =
7788 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7789 // The first cast (CSrc) is eliminable so we need to fix up or replace
7790 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007791 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007792 }
7793 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007794
Reid Spencer3da59db2006-11-27 01:05:10 +00007795 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007796 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7797 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7798 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007799
7800 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007801 if (isa<PHINode>(Src))
7802 if (Instruction *NV = FoldOpIntoPhi(CI))
7803 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007804
Reid Spencer3da59db2006-11-27 01:05:10 +00007805 return 0;
7806}
7807
Chris Lattner46cd5a12009-01-09 05:44:56 +00007808/// FindElementAtOffset - Given a type and a constant offset, determine whether
7809/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007810/// the specified offset. If so, fill them into NewIndices and return the
7811/// resultant element type, otherwise return null.
7812static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7813 SmallVectorImpl<Value*> &NewIndices,
7814 const TargetData *TD) {
7815 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007816
7817 // Start with the index over the outer type. Note that the type size
7818 // might be zero (even if the offset isn't zero) if the indexed type
7819 // is something like [0 x {int, int}]
7820 const Type *IntPtrTy = TD->getIntPtrType();
7821 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007822 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007823 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007824 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007825
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007826 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007827 if (Offset < 0) {
7828 --FirstIdx;
7829 Offset += TySize;
7830 assert(Offset >= 0);
7831 }
7832 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7833 }
7834
7835 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7836
7837 // Index into the types. If we fail, set OrigBase to null.
7838 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007839 // Indexing into tail padding between struct/array elements.
7840 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007841 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007842
Chris Lattner46cd5a12009-01-09 05:44:56 +00007843 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7844 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007845 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7846 "Offset must stay within the indexed type");
7847
Chris Lattner46cd5a12009-01-09 05:44:56 +00007848 unsigned Elt = SL->getElementContainingOffset(Offset);
7849 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7850
7851 Offset -= SL->getElementOffset(Elt);
7852 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007853 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007854 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007855 assert(EltSize && "Cannot index into a zero-sized array");
7856 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7857 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007858 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007859 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007860 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007861 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007862 }
7863 }
7864
Chris Lattner3914f722009-01-24 01:00:13 +00007865 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007866}
7867
Chris Lattnerd3e28342007-04-27 17:44:50 +00007868/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7869Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7870 Value *Src = CI.getOperand(0);
7871
Chris Lattnerd3e28342007-04-27 17:44:50 +00007872 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007873 // If casting the result of a getelementptr instruction with no offset, turn
7874 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007875 if (GEP->hasAllZeroIndices()) {
7876 // Changing the cast operand is usually not a good idea but it is safe
7877 // here because the pointer operand is being replaced with another
7878 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007879 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007880 CI.setOperand(0, GEP->getOperand(0));
7881 return &CI;
7882 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007883
7884 // If the GEP has a single use, and the base pointer is a bitcast, and the
7885 // GEP computes a constant offset, see if we can convert these three
7886 // instructions into fewer. This typically happens with unions and other
7887 // non-type-safe code.
7888 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7889 if (GEP->hasAllConstantIndices()) {
7890 // We are guaranteed to get a constant from EmitGEPOffset.
7891 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7892 int64_t Offset = OffsetV->getSExtValue();
7893
7894 // Get the base pointer input of the bitcast, and the type it points to.
7895 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7896 const Type *GEPIdxTy =
7897 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007898 SmallVector<Value*, 8> NewIndices;
7899 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7900 // If we were able to index down into an element, create the GEP
7901 // and bitcast the result. This eliminates one bitcast, potentially
7902 // two.
7903 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7904 NewIndices.begin(),
7905 NewIndices.end(), "");
7906 InsertNewInstBefore(NGEP, CI);
7907 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007908
Chris Lattner46cd5a12009-01-09 05:44:56 +00007909 if (isa<BitCastInst>(CI))
7910 return new BitCastInst(NGEP, CI.getType());
7911 assert(isa<PtrToIntInst>(CI));
7912 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007913 }
7914 }
7915 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007916 }
7917
7918 return commonCastTransforms(CI);
7919}
7920
7921
Chris Lattnerc739cd62007-03-03 05:27:34 +00007922/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7923/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007924/// cases.
7925/// @brief Implement the transforms common to CastInst with integer operands
7926Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7927 if (Instruction *Result = commonCastTransforms(CI))
7928 return Result;
7929
7930 Value *Src = CI.getOperand(0);
7931 const Type *SrcTy = Src->getType();
7932 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007933 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7934 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007935
Reid Spencer3da59db2006-11-27 01:05:10 +00007936 // See if we can simplify any instructions used by the LHS whose sole
7937 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007938 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007939 return &CI;
7940
7941 // If the source isn't an instruction or has more than one use then we
7942 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007943 Instruction *SrcI = dyn_cast<Instruction>(Src);
7944 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007945 return 0;
7946
Chris Lattnerc739cd62007-03-03 05:27:34 +00007947 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007948 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007949 if (!isa<BitCastInst>(CI) &&
7950 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007951 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007952 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007953 // eliminates the cast, so it is always a win. If this is a zero-extension,
7954 // we need to do an AND to maintain the clear top-part of the computation,
7955 // so we require that the input have eliminated at least one cast. If this
7956 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007957 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007958 bool DoXForm = false;
7959 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007960 switch (CI.getOpcode()) {
7961 default:
7962 // All the others use floating point so we shouldn't actually
7963 // get here because of the check above.
7964 assert(0 && "Unknown cast type");
7965 case Instruction::Trunc:
7966 DoXForm = true;
7967 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007968 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007969 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007970 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 // If it's unnecessary to issue an AND to clear the high bits, it's
7972 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00007973 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007974 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7975 if (MaskedValueIsZero(TryRes, Mask))
7976 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007977
7978 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007979 if (TryI->use_empty())
7980 EraseInstFromFunction(*TryI);
7981 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007982 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007983 }
Evan Chengf35fd542009-01-15 17:01:23 +00007984 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007985 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007986 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007987 // If we do not have to emit the truncate + sext pair, then it's always
7988 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007989 //
7990 // It's not safe to eliminate the trunc + sext pair if one of the
7991 // eliminated cast is a truncate. e.g.
7992 // t2 = trunc i32 t1 to i16
7993 // t3 = sext i16 t2 to i32
7994 // !=
7995 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00007996 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007997 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7998 if (NumSignBits > (DestBitSize - SrcBitSize))
7999 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008000
8001 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008002 if (TryI->use_empty())
8003 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008004 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008005 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008006 }
Evan Chengf35fd542009-01-15 17:01:23 +00008007 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008008
8009 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008010 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8011 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008012 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8013 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008014 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008015 // Just replace this cast with the result.
8016 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008017
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 assert(Res->getType() == DestTy);
8019 switch (CI.getOpcode()) {
8020 default: assert(0 && "Unknown cast type!");
8021 case Instruction::Trunc:
8022 case Instruction::BitCast:
8023 // Just replace this cast with the result.
8024 return ReplaceInstUsesWith(CI, Res);
8025 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008026 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008027
8028 // If the high bits are already zero, just replace this cast with the
8029 // result.
8030 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8031 if (MaskedValueIsZero(Res, Mask))
8032 return ReplaceInstUsesWith(CI, Res);
8033
8034 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008035 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8036 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008037 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008038 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008039 case Instruction::SExt: {
8040 // If the high bits are already filled with sign bit, just replace this
8041 // cast with the result.
8042 unsigned NumSignBits = ComputeNumSignBits(Res);
8043 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008044 return ReplaceInstUsesWith(CI, Res);
8045
Reid Spencer3da59db2006-11-27 01:05:10 +00008046 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008047 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008048 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8049 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008050 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008051 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 }
8053 }
8054
8055 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8056 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8057
8058 switch (SrcI->getOpcode()) {
8059 case Instruction::Add:
8060 case Instruction::Mul:
8061 case Instruction::And:
8062 case Instruction::Or:
8063 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008064 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008065 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8066 // Don't insert two casts if they cannot be eliminated. We allow
8067 // two casts to be inserted if the sizes are the same. This could
8068 // only be converting signedness, which is a noop.
8069 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008070 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8071 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008072 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008073 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8074 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008075 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008076 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008077 }
8078 }
8079
8080 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8081 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8082 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008083 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008084 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008085 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008086 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008087 }
8088 break;
8089 case Instruction::SDiv:
8090 case Instruction::UDiv:
8091 case Instruction::SRem:
8092 case Instruction::URem:
8093 // If we are just changing the sign, rewrite.
8094 if (DestBitSize == SrcBitSize) {
8095 // Don't insert two casts if they cannot be eliminated. We allow
8096 // two casts to be inserted if the sizes are the same. This could
8097 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008098 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8099 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008100 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8101 Op0, DestTy, *SrcI);
8102 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8103 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008104 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008105 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8106 }
8107 }
8108 break;
8109
8110 case Instruction::Shl:
8111 // Allow changing the sign of the source operand. Do not allow
8112 // changing the size of the shift, UNLESS the shift amount is a
8113 // constant. We must not change variable sized shifts to a smaller
8114 // size, because it is undefined to shift more bits out than exist
8115 // in the value.
8116 if (DestBitSize == SrcBitSize ||
8117 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008118 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8119 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008120 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8121 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008122 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008123 }
8124 break;
8125 case Instruction::AShr:
8126 // If this is a signed shr, and if all bits shifted in are about to be
8127 // truncated off, turn it into an unsigned shr to allow greater
8128 // simplifications.
8129 if (DestBitSize < SrcBitSize &&
8130 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008131 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8133 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008134 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008135 }
8136 }
8137 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008138 }
8139 return 0;
8140}
8141
Chris Lattner8a9f5712007-04-11 06:57:46 +00008142Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008143 if (Instruction *Result = commonIntCastTransforms(CI))
8144 return Result;
8145
8146 Value *Src = CI.getOperand(0);
8147 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008148 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8149 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008150
8151 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8152 switch (SrcI->getOpcode()) {
8153 default: break;
8154 case Instruction::LShr:
8155 // We can shrink lshr to something smaller if we know the bits shifted in
8156 // are already zeros.
8157 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008158 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008159
8160 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008161 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008162 Value* SrcIOp0 = SrcI->getOperand(0);
8163 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008164 if (ShAmt >= DestBitWidth) // All zeros.
8165 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8166
8167 // Okay, we can shrink this. Truncate the input, then return a new
8168 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008169 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8170 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8171 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008172 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008173 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008174 } else { // This is a variable shr.
8175
8176 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8177 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8178 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008179 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008180 Value *One = ConstantInt::get(SrcI->getType(), 1);
8181
Reid Spencer832254e2007-02-02 02:16:23 +00008182 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008183 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008184 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008185 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008186 SrcI->getOperand(0),
8187 "tmp"), CI);
8188 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008189 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008190 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008191 }
8192 break;
8193 }
8194 }
8195
8196 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008197}
8198
Evan Chengb98a10e2008-03-24 00:21:34 +00008199/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8200/// in order to eliminate the icmp.
8201Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8202 bool DoXform) {
8203 // If we are just checking for a icmp eq of a single bit and zext'ing it
8204 // to an integer, then shift the bit to the appropriate place and then
8205 // cast to integer to avoid the comparison.
8206 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8207 const APInt &Op1CV = Op1C->getValue();
8208
8209 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8210 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8211 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8212 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8213 if (!DoXform) return ICI;
8214
8215 Value *In = ICI->getOperand(0);
8216 Value *Sh = ConstantInt::get(In->getType(),
8217 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008218 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008219 In->getName()+".lobit"),
8220 CI);
8221 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008222 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008223 false/*ZExt*/, "tmp", &CI);
8224
8225 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8226 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008227 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008228 In->getName()+".not"),
8229 CI);
8230 }
8231
8232 return ReplaceInstUsesWith(CI, In);
8233 }
8234
8235
8236
8237 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8238 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8239 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8240 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8241 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8242 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8243 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8244 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8245 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8246 // This only works for EQ and NE
8247 ICI->isEquality()) {
8248 // If Op1C some other power of two, convert:
8249 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8250 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8251 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8252 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8253
8254 APInt KnownZeroMask(~KnownZero);
8255 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8256 if (!DoXform) return ICI;
8257
8258 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8259 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8260 // (X&4) == 2 --> false
8261 // (X&4) != 2 --> true
8262 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8263 Res = ConstantExpr::getZExt(Res, CI.getType());
8264 return ReplaceInstUsesWith(CI, Res);
8265 }
8266
8267 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8268 Value *In = ICI->getOperand(0);
8269 if (ShiftAmt) {
8270 // Perform a logical shr by shiftamt.
8271 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008272 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008273 ConstantInt::get(In->getType(), ShiftAmt),
8274 In->getName()+".lobit"), CI);
8275 }
8276
8277 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8278 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008279 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008280 InsertNewInstBefore(cast<Instruction>(In), CI);
8281 }
8282
8283 if (CI.getType() == In->getType())
8284 return ReplaceInstUsesWith(CI, In);
8285 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008286 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008287 }
8288 }
8289 }
8290
8291 return 0;
8292}
8293
Chris Lattner8a9f5712007-04-11 06:57:46 +00008294Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 // If one of the common conversion will work ..
8296 if (Instruction *Result = commonIntCastTransforms(CI))
8297 return Result;
8298
8299 Value *Src = CI.getOperand(0);
8300
Chris Lattnera84f47c2009-02-17 20:47:23 +00008301 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8302 // types and if the sizes are just right we can convert this into a logical
8303 // 'and' which will be much cheaper than the pair of casts.
8304 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8305 // Get the sizes of the types involved. We know that the intermediate type
8306 // will be smaller than A or C, but don't know the relation between A and C.
8307 Value *A = CSrc->getOperand(0);
8308 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8309 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8310 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8311 // If we're actually extending zero bits, then if
8312 // SrcSize < DstSize: zext(a & mask)
8313 // SrcSize == DstSize: a & mask
8314 // SrcSize > DstSize: trunc(a) & mask
8315 if (SrcSize < DstSize) {
8316 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8317 Constant *AndConst = ConstantInt::get(AndValue);
8318 Instruction *And =
8319 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8320 InsertNewInstBefore(And, CI);
8321 return new ZExtInst(And, CI.getType());
8322 } else if (SrcSize == DstSize) {
8323 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8324 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8325 } else if (SrcSize > DstSize) {
8326 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8327 InsertNewInstBefore(Trunc, CI);
8328 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8329 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008330 }
8331 }
8332
Evan Chengb98a10e2008-03-24 00:21:34 +00008333 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8334 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008335
Evan Chengb98a10e2008-03-24 00:21:34 +00008336 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8337 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8338 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8339 // of the (zext icmp) will be transformed.
8340 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8341 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8342 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8343 (transformZExtICmp(LHS, CI, false) ||
8344 transformZExtICmp(RHS, CI, false))) {
8345 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8346 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008347 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008348 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008349 }
8350
Reid Spencer3da59db2006-11-27 01:05:10 +00008351 return 0;
8352}
8353
Chris Lattner8a9f5712007-04-11 06:57:46 +00008354Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008355 if (Instruction *I = commonIntCastTransforms(CI))
8356 return I;
8357
Chris Lattner8a9f5712007-04-11 06:57:46 +00008358 Value *Src = CI.getOperand(0);
8359
Dan Gohman1975d032008-10-30 20:40:10 +00008360 // Canonicalize sign-extend from i1 to a select.
8361 if (Src->getType() == Type::Int1Ty)
8362 return SelectInst::Create(Src,
8363 ConstantInt::getAllOnesValue(CI.getType()),
8364 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008365
8366 // See if the value being truncated is already sign extended. If so, just
8367 // eliminate the trunc/sext pair.
8368 if (getOpcode(Src) == Instruction::Trunc) {
8369 Value *Op = cast<User>(Src)->getOperand(0);
8370 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8371 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8372 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8373 unsigned NumSignBits = ComputeNumSignBits(Op);
8374
8375 if (OpBits == DestBits) {
8376 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8377 // bits, it is already ready.
8378 if (NumSignBits > DestBits-MidBits)
8379 return ReplaceInstUsesWith(CI, Op);
8380 } else if (OpBits < DestBits) {
8381 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8382 // bits, just sext from i32.
8383 if (NumSignBits > OpBits-MidBits)
8384 return new SExtInst(Op, CI.getType(), "tmp");
8385 } else {
8386 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8387 // bits, just truncate to i32.
8388 if (NumSignBits > OpBits-MidBits)
8389 return new TruncInst(Op, CI.getType(), "tmp");
8390 }
8391 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008392
8393 // If the input is a shl/ashr pair of a same constant, then this is a sign
8394 // extension from a smaller value. If we could trust arbitrary bitwidth
8395 // integers, we could turn this into a truncate to the smaller bit and then
8396 // use a sext for the whole extension. Since we don't, look deeper and check
8397 // for a truncate. If the source and dest are the same type, eliminate the
8398 // trunc and extend and just do shifts. For example, turn:
8399 // %a = trunc i32 %i to i8
8400 // %b = shl i8 %a, 6
8401 // %c = ashr i8 %b, 6
8402 // %d = sext i8 %c to i32
8403 // into:
8404 // %a = shl i32 %i, 30
8405 // %d = ashr i32 %a, 30
8406 Value *A = 0;
8407 ConstantInt *BA = 0, *CA = 0;
8408 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8409 m_ConstantInt(CA))) &&
8410 BA == CA && isa<TruncInst>(A)) {
8411 Value *I = cast<TruncInst>(A)->getOperand(0);
8412 if (I->getType() == CI.getType()) {
8413 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8414 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8415 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8416 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8417 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8418 CI.getName()), CI);
8419 return BinaryOperator::CreateAShr(I, ShAmtV);
8420 }
8421 }
8422
Chris Lattnerba417832007-04-11 06:12:58 +00008423 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008424}
8425
Chris Lattnerb7530652008-01-27 05:29:54 +00008426/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8427/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008428static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008429 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008430 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008431 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8432 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008433 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008434 return 0;
8435}
8436
8437/// LookThroughFPExtensions - If this is an fp extension instruction, look
8438/// through it until we get the source value.
8439static Value *LookThroughFPExtensions(Value *V) {
8440 if (Instruction *I = dyn_cast<Instruction>(V))
8441 if (I->getOpcode() == Instruction::FPExt)
8442 return LookThroughFPExtensions(I->getOperand(0));
8443
8444 // If this value is a constant, return the constant in the smallest FP type
8445 // that can accurately represent it. This allows us to turn
8446 // (float)((double)X+2.0) into x+2.0f.
8447 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8448 if (CFP->getType() == Type::PPC_FP128Ty)
8449 return V; // No constant folding of this.
8450 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008451 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008452 return V;
8453 if (CFP->getType() == Type::DoubleTy)
8454 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008455 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008456 return V;
8457 // Don't try to shrink to various long double types.
8458 }
8459
8460 return V;
8461}
8462
8463Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8464 if (Instruction *I = commonCastTransforms(CI))
8465 return I;
8466
8467 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8468 // smaller than the destination type, we can eliminate the truncate by doing
8469 // the add as the smaller type. This applies to add/sub/mul/div as well as
8470 // many builtins (sqrt, etc).
8471 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8472 if (OpI && OpI->hasOneUse()) {
8473 switch (OpI->getOpcode()) {
8474 default: break;
8475 case Instruction::Add:
8476 case Instruction::Sub:
8477 case Instruction::Mul:
8478 case Instruction::FDiv:
8479 case Instruction::FRem:
8480 const Type *SrcTy = OpI->getType();
8481 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8482 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8483 if (LHSTrunc->getType() != SrcTy &&
8484 RHSTrunc->getType() != SrcTy) {
8485 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8486 // If the source types were both smaller than the destination type of
8487 // the cast, do this xform.
8488 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8489 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8490 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8491 CI.getType(), CI);
8492 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8493 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008494 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008495 }
8496 }
8497 break;
8498 }
8499 }
8500 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008501}
8502
8503Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8504 return commonCastTransforms(CI);
8505}
8506
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008507Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008508 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8509 if (OpI == 0)
8510 return commonCastTransforms(FI);
8511
8512 // fptoui(uitofp(X)) --> X
8513 // fptoui(sitofp(X)) --> X
8514 // This is safe if the intermediate type has enough bits in its mantissa to
8515 // accurately represent all values of X. For example, do not do this with
8516 // i64->float->i64. This is also safe for sitofp case, because any negative
8517 // 'X' value would cause an undefined result for the fptoui.
8518 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8519 OpI->getOperand(0)->getType() == FI.getType() &&
8520 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8521 OpI->getType()->getFPMantissaWidth())
8522 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008523
8524 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008525}
8526
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008527Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008528 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8529 if (OpI == 0)
8530 return commonCastTransforms(FI);
8531
8532 // fptosi(sitofp(X)) --> X
8533 // fptosi(uitofp(X)) --> X
8534 // This is safe if the intermediate type has enough bits in its mantissa to
8535 // accurately represent all values of X. For example, do not do this with
8536 // i64->float->i64. This is also safe for sitofp case, because any negative
8537 // 'X' value would cause an undefined result for the fptoui.
8538 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8539 OpI->getOperand(0)->getType() == FI.getType() &&
8540 (int)FI.getType()->getPrimitiveSizeInBits() <=
8541 OpI->getType()->getFPMantissaWidth())
8542 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008543
8544 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008545}
8546
8547Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8548 return commonCastTransforms(CI);
8549}
8550
8551Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8552 return commonCastTransforms(CI);
8553}
8554
8555Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008556 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008557}
8558
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008559Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8560 if (Instruction *I = commonCastTransforms(CI))
8561 return I;
8562
8563 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8564 if (!DestPointee->isSized()) return 0;
8565
8566 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8567 ConstantInt *Cst;
8568 Value *X;
8569 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8570 m_ConstantInt(Cst)))) {
8571 // If the source and destination operands have the same type, see if this
8572 // is a single-index GEP.
8573 if (X->getType() == CI.getType()) {
8574 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008575 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008576
8577 // Convert the constant to intptr type.
8578 APInt Offset = Cst->getValue();
8579 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8580
8581 // If Offset is evenly divisible by Size, we can do this xform.
8582 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8583 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008584 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008585 }
8586 }
8587 // TODO: Could handle other cases, e.g. where add is indexing into field of
8588 // struct etc.
8589 } else if (CI.getOperand(0)->hasOneUse() &&
8590 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8591 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8592 // "inttoptr+GEP" instead of "add+intptr".
8593
8594 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008595 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008596
8597 // Convert the constant to intptr type.
8598 APInt Offset = Cst->getValue();
8599 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8600
8601 // If Offset is evenly divisible by Size, we can do this xform.
8602 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8603 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8604
8605 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8606 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008607 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008608 }
8609 }
8610 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008611}
8612
Chris Lattnerd3e28342007-04-27 17:44:50 +00008613Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008614 // If the operands are integer typed then apply the integer transforms,
8615 // otherwise just apply the common ones.
8616 Value *Src = CI.getOperand(0);
8617 const Type *SrcTy = Src->getType();
8618 const Type *DestTy = CI.getType();
8619
Chris Lattner42a75512007-01-15 02:27:26 +00008620 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008621 if (Instruction *Result = commonIntCastTransforms(CI))
8622 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008623 } else if (isa<PointerType>(SrcTy)) {
8624 if (Instruction *I = commonPointerCastTransforms(CI))
8625 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008626 } else {
8627 if (Instruction *Result = commonCastTransforms(CI))
8628 return Result;
8629 }
8630
8631
8632 // Get rid of casts from one type to the same type. These are useless and can
8633 // be replaced by the operand.
8634 if (DestTy == Src->getType())
8635 return ReplaceInstUsesWith(CI, Src);
8636
Reid Spencer3da59db2006-11-27 01:05:10 +00008637 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008638 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8639 const Type *DstElTy = DstPTy->getElementType();
8640 const Type *SrcElTy = SrcPTy->getElementType();
8641
Nate Begeman83ad90a2008-03-31 00:22:16 +00008642 // If the address spaces don't match, don't eliminate the bitcast, which is
8643 // required for changing types.
8644 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8645 return 0;
8646
Chris Lattnerd3e28342007-04-27 17:44:50 +00008647 // If we are casting a malloc or alloca to a pointer to a type of the same
8648 // size, rewrite the allocation instruction to allocate the "right" type.
8649 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8650 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8651 return V;
8652
Chris Lattnerd717c182007-05-05 22:32:24 +00008653 // If the source and destination are pointers, and this cast is equivalent
8654 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008655 // This can enhance SROA and other transforms that want type-safe pointers.
8656 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8657 unsigned NumZeros = 0;
8658 while (SrcElTy != DstElTy &&
8659 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8660 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8661 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8662 ++NumZeros;
8663 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008664
Chris Lattnerd3e28342007-04-27 17:44:50 +00008665 // If we found a path from the src to dest, create the getelementptr now.
8666 if (SrcElTy == DstElTy) {
8667 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008668 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8669 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008670 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008671 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008672
Reid Spencer3da59db2006-11-27 01:05:10 +00008673 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8674 if (SVI->hasOneUse()) {
8675 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8676 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008677 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008678 cast<VectorType>(DestTy)->getNumElements() ==
8679 SVI->getType()->getNumElements() &&
8680 SVI->getType()->getNumElements() ==
8681 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008682 CastInst *Tmp;
8683 // If either of the operands is a cast from CI.getType(), then
8684 // evaluating the shuffle in the casted destination's type will allow
8685 // us to eliminate at least one cast.
8686 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8687 Tmp->getOperand(0)->getType() == DestTy) ||
8688 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8689 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008690 Value *LHS = InsertCastBefore(Instruction::BitCast,
8691 SVI->getOperand(0), DestTy, CI);
8692 Value *RHS = InsertCastBefore(Instruction::BitCast,
8693 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008694 // Return a new shuffle vector. Use the same element ID's, as we
8695 // know the vector types match #elts.
8696 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008697 }
8698 }
8699 }
8700 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008701 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008702}
8703
Chris Lattnere576b912004-04-09 23:46:01 +00008704/// GetSelectFoldableOperands - We want to turn code that looks like this:
8705/// %C = or %A, %B
8706/// %D = select %cond, %C, %A
8707/// into:
8708/// %C = select %cond, %B, 0
8709/// %D = or %A, %C
8710///
8711/// Assuming that the specified instruction is an operand to the select, return
8712/// a bitmask indicating which operands of this instruction are foldable if they
8713/// equal the other incoming value of the select.
8714///
8715static unsigned GetSelectFoldableOperands(Instruction *I) {
8716 switch (I->getOpcode()) {
8717 case Instruction::Add:
8718 case Instruction::Mul:
8719 case Instruction::And:
8720 case Instruction::Or:
8721 case Instruction::Xor:
8722 return 3; // Can fold through either operand.
8723 case Instruction::Sub: // Can only fold on the amount subtracted.
8724 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008725 case Instruction::LShr:
8726 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008727 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008728 default:
8729 return 0; // Cannot fold
8730 }
8731}
8732
8733/// GetSelectFoldableConstant - For the same transformation as the previous
8734/// function, return the identity constant that goes into the select.
8735static Constant *GetSelectFoldableConstant(Instruction *I) {
8736 switch (I->getOpcode()) {
8737 default: assert(0 && "This cannot happen!"); abort();
8738 case Instruction::Add:
8739 case Instruction::Sub:
8740 case Instruction::Or:
8741 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008742 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008743 case Instruction::LShr:
8744 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008745 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008746 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008747 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008748 case Instruction::Mul:
8749 return ConstantInt::get(I->getType(), 1);
8750 }
8751}
8752
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008753/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8754/// have the same opcode and only one use each. Try to simplify this.
8755Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8756 Instruction *FI) {
8757 if (TI->getNumOperands() == 1) {
8758 // If this is a non-volatile load or a cast from the same type,
8759 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008760 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008761 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8762 return 0;
8763 } else {
8764 return 0; // unknown unary op.
8765 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008766
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008767 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008768 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8769 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008770 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008771 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008772 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008773 }
8774
Reid Spencer832254e2007-02-02 02:16:23 +00008775 // Only handle binary operators here.
8776 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008777 return 0;
8778
8779 // Figure out if the operations have any operands in common.
8780 Value *MatchOp, *OtherOpT, *OtherOpF;
8781 bool MatchIsOpZero;
8782 if (TI->getOperand(0) == FI->getOperand(0)) {
8783 MatchOp = TI->getOperand(0);
8784 OtherOpT = TI->getOperand(1);
8785 OtherOpF = FI->getOperand(1);
8786 MatchIsOpZero = true;
8787 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8788 MatchOp = TI->getOperand(1);
8789 OtherOpT = TI->getOperand(0);
8790 OtherOpF = FI->getOperand(0);
8791 MatchIsOpZero = false;
8792 } else if (!TI->isCommutative()) {
8793 return 0;
8794 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8795 MatchOp = TI->getOperand(0);
8796 OtherOpT = TI->getOperand(1);
8797 OtherOpF = FI->getOperand(0);
8798 MatchIsOpZero = true;
8799 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8800 MatchOp = TI->getOperand(1);
8801 OtherOpT = TI->getOperand(0);
8802 OtherOpF = FI->getOperand(1);
8803 MatchIsOpZero = true;
8804 } else {
8805 return 0;
8806 }
8807
8808 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008809 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8810 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008811 InsertNewInstBefore(NewSI, SI);
8812
8813 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8814 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008815 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008816 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008817 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008818 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008819 assert(0 && "Shouldn't get here");
8820 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008821}
8822
Dan Gohman81b28ce2008-09-16 18:46:06 +00008823/// visitSelectInstWithICmp - Visit a SelectInst that has an
8824/// ICmpInst as its first operand.
8825///
8826Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8827 ICmpInst *ICI) {
8828 bool Changed = false;
8829 ICmpInst::Predicate Pred = ICI->getPredicate();
8830 Value *CmpLHS = ICI->getOperand(0);
8831 Value *CmpRHS = ICI->getOperand(1);
8832 Value *TrueVal = SI.getTrueValue();
8833 Value *FalseVal = SI.getFalseValue();
8834
8835 // Check cases where the comparison is with a constant that
8836 // can be adjusted to fit the min/max idiom. We may edit ICI in
8837 // place here, so make sure the select is the only user.
8838 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008839 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008840 switch (Pred) {
8841 default: break;
8842 case ICmpInst::ICMP_ULT:
8843 case ICmpInst::ICMP_SLT: {
8844 // X < MIN ? T : F --> F
8845 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8846 return ReplaceInstUsesWith(SI, FalseVal);
8847 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8848 Constant *AdjustedRHS = SubOne(CI);
8849 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8850 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8851 Pred = ICmpInst::getSwappedPredicate(Pred);
8852 CmpRHS = AdjustedRHS;
8853 std::swap(FalseVal, TrueVal);
8854 ICI->setPredicate(Pred);
8855 ICI->setOperand(1, CmpRHS);
8856 SI.setOperand(1, TrueVal);
8857 SI.setOperand(2, FalseVal);
8858 Changed = true;
8859 }
8860 break;
8861 }
8862 case ICmpInst::ICMP_UGT:
8863 case ICmpInst::ICMP_SGT: {
8864 // X > MAX ? T : F --> F
8865 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8866 return ReplaceInstUsesWith(SI, FalseVal);
8867 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8868 Constant *AdjustedRHS = AddOne(CI);
8869 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8870 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8871 Pred = ICmpInst::getSwappedPredicate(Pred);
8872 CmpRHS = AdjustedRHS;
8873 std::swap(FalseVal, TrueVal);
8874 ICI->setPredicate(Pred);
8875 ICI->setOperand(1, CmpRHS);
8876 SI.setOperand(1, TrueVal);
8877 SI.setOperand(2, FalseVal);
8878 Changed = true;
8879 }
8880 break;
8881 }
8882 }
8883
Dan Gohman1975d032008-10-30 20:40:10 +00008884 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8885 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008886 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008887 if (match(TrueVal, m_ConstantInt<-1>()) &&
8888 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008889 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008890 else if (match(TrueVal, m_ConstantInt<0>()) &&
8891 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008892 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8893
Dan Gohman1975d032008-10-30 20:40:10 +00008894 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8895 // If we are just checking for a icmp eq of a single bit and zext'ing it
8896 // to an integer, then shift the bit to the appropriate place and then
8897 // cast to integer to avoid the comparison.
8898 const APInt &Op1CV = CI->getValue();
8899
8900 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8901 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8902 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008903 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008904 Value *In = ICI->getOperand(0);
8905 Value *Sh = ConstantInt::get(In->getType(),
8906 In->getType()->getPrimitiveSizeInBits()-1);
8907 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8908 In->getName()+".lobit"),
8909 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008910 if (In->getType() != SI.getType())
8911 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008912 true/*SExt*/, "tmp", ICI);
8913
8914 if (Pred == ICmpInst::ICMP_SGT)
8915 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8916 In->getName()+".not"), *ICI);
8917
8918 return ReplaceInstUsesWith(SI, In);
8919 }
8920 }
8921 }
8922
Dan Gohman81b28ce2008-09-16 18:46:06 +00008923 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8924 // Transform (X == Y) ? X : Y -> Y
8925 if (Pred == ICmpInst::ICMP_EQ)
8926 return ReplaceInstUsesWith(SI, FalseVal);
8927 // Transform (X != Y) ? X : Y -> X
8928 if (Pred == ICmpInst::ICMP_NE)
8929 return ReplaceInstUsesWith(SI, TrueVal);
8930 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8931
8932 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8933 // Transform (X == Y) ? Y : X -> X
8934 if (Pred == ICmpInst::ICMP_EQ)
8935 return ReplaceInstUsesWith(SI, FalseVal);
8936 // Transform (X != Y) ? Y : X -> Y
8937 if (Pred == ICmpInst::ICMP_NE)
8938 return ReplaceInstUsesWith(SI, TrueVal);
8939 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8940 }
8941
8942 /// NOTE: if we wanted to, this is where to detect integer ABS
8943
8944 return Changed ? &SI : 0;
8945}
8946
Chris Lattner3d69f462004-03-12 05:52:32 +00008947Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008948 Value *CondVal = SI.getCondition();
8949 Value *TrueVal = SI.getTrueValue();
8950 Value *FalseVal = SI.getFalseValue();
8951
8952 // select true, X, Y -> X
8953 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008954 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008955 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008956
8957 // select C, X, X -> X
8958 if (TrueVal == FalseVal)
8959 return ReplaceInstUsesWith(SI, TrueVal);
8960
Chris Lattnere87597f2004-10-16 18:11:37 +00008961 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8962 return ReplaceInstUsesWith(SI, FalseVal);
8963 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8964 return ReplaceInstUsesWith(SI, TrueVal);
8965 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8966 if (isa<Constant>(TrueVal))
8967 return ReplaceInstUsesWith(SI, TrueVal);
8968 else
8969 return ReplaceInstUsesWith(SI, FalseVal);
8970 }
8971
Reid Spencer4fe16d62007-01-11 18:21:29 +00008972 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008973 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008974 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008975 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008976 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008977 } else {
8978 // Change: A = select B, false, C --> A = and !B, C
8979 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008980 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008981 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008982 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008983 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008984 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008985 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008986 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008987 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008988 } else {
8989 // Change: A = select B, C, true --> A = or !B, C
8990 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008991 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008992 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008993 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008994 }
8995 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008996
8997 // select a, b, a -> a&b
8998 // select a, a, b -> a|b
8999 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009000 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009001 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009002 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009003 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009004
Chris Lattner2eefe512004-04-09 19:05:30 +00009005 // Selecting between two integer constants?
9006 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9007 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009008 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009009 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009010 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009011 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009012 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009013 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009014 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009015 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009016 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009017 }
Chris Lattner457dd822004-06-09 07:59:58 +00009018
Reid Spencere4d87aa2006-12-23 06:05:41 +00009019 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009020
Reid Spencere4d87aa2006-12-23 06:05:41 +00009021 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009022 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009023 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009024 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009025 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009026 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009027 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00009028 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009029 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009030 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009031 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009032 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009033
9034 // Then cast to the appropriate width.
9035 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009036 }
9037 }
9038
9039
9040 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009041 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009042 // non-constant value, eliminate this whole mess. This corresponds to
9043 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009044 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009045 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009046 cast<Constant>(IC->getOperand(1))->isNullValue())
9047 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9048 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009049 isa<ConstantInt>(ICA->getOperand(1)) &&
9050 (ICA->getOperand(1) == TrueValC ||
9051 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009052 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9053 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009054 // know whether we have a icmp_ne or icmp_eq and whether the
9055 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009056 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009057 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009058 Value *V = ICA;
9059 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009060 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009061 Instruction::Xor, V, ICA->getOperand(1)), SI);
9062 return ReplaceInstUsesWith(SI, V);
9063 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009064 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009065 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009066
9067 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009068 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9069 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009070 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009071 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9072 // This is not safe in general for floating point:
9073 // consider X== -0, Y== +0.
9074 // It becomes safe if either operand is a nonzero constant.
9075 ConstantFP *CFPt, *CFPf;
9076 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9077 !CFPt->getValueAPF().isZero()) ||
9078 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9079 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009080 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009081 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009082 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009083 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009084 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009085 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009086
Reid Spencere4d87aa2006-12-23 06:05:41 +00009087 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009088 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009089 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9090 // This is not safe in general for floating point:
9091 // consider X== -0, Y== +0.
9092 // It becomes safe if either operand is a nonzero constant.
9093 ConstantFP *CFPt, *CFPf;
9094 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9095 !CFPt->getValueAPF().isZero()) ||
9096 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9097 !CFPf->getValueAPF().isZero()))
9098 return ReplaceInstUsesWith(SI, FalseVal);
9099 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009100 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009101 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9102 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009103 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009104 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009105 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009106 }
9107
9108 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009109 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9110 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9111 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009112
Chris Lattner87875da2005-01-13 22:52:24 +00009113 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9114 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9115 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009116 Instruction *AddOp = 0, *SubOp = 0;
9117
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009118 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9119 if (TI->getOpcode() == FI->getOpcode())
9120 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9121 return IV;
9122
9123 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9124 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009125 if (TI->getOpcode() == Instruction::Sub &&
9126 FI->getOpcode() == Instruction::Add) {
9127 AddOp = FI; SubOp = TI;
9128 } else if (FI->getOpcode() == Instruction::Sub &&
9129 TI->getOpcode() == Instruction::Add) {
9130 AddOp = TI; SubOp = FI;
9131 }
9132
9133 if (AddOp) {
9134 Value *OtherAddOp = 0;
9135 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9136 OtherAddOp = AddOp->getOperand(1);
9137 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9138 OtherAddOp = AddOp->getOperand(0);
9139 }
9140
9141 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009142 // So at this point we know we have (Y -> OtherAddOp):
9143 // select C, (add X, Y), (sub X, Z)
9144 Value *NegVal; // Compute -Z
9145 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9146 NegVal = ConstantExpr::getNeg(C);
9147 } else {
9148 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009149 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009150 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009151
9152 Value *NewTrueOp = OtherAddOp;
9153 Value *NewFalseOp = NegVal;
9154 if (AddOp != TI)
9155 std::swap(NewTrueOp, NewFalseOp);
9156 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009157 SelectInst::Create(CondVal, NewTrueOp,
9158 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009159
9160 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009161 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009162 }
9163 }
9164 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009165
Chris Lattnere576b912004-04-09 23:46:01 +00009166 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009167 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009168 // See the comment above GetSelectFoldableOperands for a description of the
9169 // transformation we are doing here.
9170 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9171 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9172 !isa<Constant>(FalseVal))
9173 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9174 unsigned OpToFold = 0;
9175 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9176 OpToFold = 1;
9177 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9178 OpToFold = 2;
9179 }
9180
9181 if (OpToFold) {
9182 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009183 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009184 SelectInst::Create(SI.getCondition(),
9185 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009186 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009187 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009189 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009190 else {
9191 assert(0 && "Unknown instruction!!");
9192 }
9193 }
9194 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009195
Chris Lattnere576b912004-04-09 23:46:01 +00009196 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9197 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9198 !isa<Constant>(TrueVal))
9199 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9200 unsigned OpToFold = 0;
9201 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9202 OpToFold = 1;
9203 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9204 OpToFold = 2;
9205 }
9206
9207 if (OpToFold) {
9208 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009209 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009210 SelectInst::Create(SI.getCondition(), C,
9211 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009212 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009213 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009215 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009216 else
Chris Lattnere576b912004-04-09 23:46:01 +00009217 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009218 }
9219 }
9220 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009221
9222 if (BinaryOperator::isNot(CondVal)) {
9223 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9224 SI.setOperand(1, FalseVal);
9225 SI.setOperand(2, TrueVal);
9226 return &SI;
9227 }
9228
Chris Lattner3d69f462004-03-12 05:52:32 +00009229 return 0;
9230}
9231
Dan Gohmaneee962e2008-04-10 18:43:06 +00009232/// EnforceKnownAlignment - If the specified pointer points to an object that
9233/// we control, modify the object's alignment to PrefAlign. This isn't
9234/// often possible though. If alignment is important, a more reliable approach
9235/// is to simply align all global variables and allocation instructions to
9236/// their preferred alignment from the beginning.
9237///
9238static unsigned EnforceKnownAlignment(Value *V,
9239 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009240
Dan Gohmaneee962e2008-04-10 18:43:06 +00009241 User *U = dyn_cast<User>(V);
9242 if (!U) return Align;
9243
9244 switch (getOpcode(U)) {
9245 default: break;
9246 case Instruction::BitCast:
9247 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9248 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009249 // If all indexes are zero, it is just the alignment of the base pointer.
9250 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009251 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009252 if (!isa<Constant>(*i) ||
9253 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009254 AllZeroOperands = false;
9255 break;
9256 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009257
9258 if (AllZeroOperands) {
9259 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009260 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009261 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009262 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009263 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009264 }
9265
9266 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9267 // If there is a large requested alignment and we can, bump up the alignment
9268 // of the global.
9269 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009270 if (GV->getAlignment() >= PrefAlign)
9271 Align = GV->getAlignment();
9272 else {
9273 GV->setAlignment(PrefAlign);
9274 Align = PrefAlign;
9275 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009276 }
9277 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9278 // If there is a requested alignment and if this is an alloca, round up. We
9279 // don't do this for malloc, because some systems can't respect the request.
9280 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009281 if (AI->getAlignment() >= PrefAlign)
9282 Align = AI->getAlignment();
9283 else {
9284 AI->setAlignment(PrefAlign);
9285 Align = PrefAlign;
9286 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009287 }
9288 }
9289
9290 return Align;
9291}
9292
9293/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9294/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9295/// and it is more than the alignment of the ultimate object, see if we can
9296/// increase the alignment of the ultimate object, making this check succeed.
9297unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9298 unsigned PrefAlign) {
9299 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9300 sizeof(PrefAlign) * CHAR_BIT;
9301 APInt Mask = APInt::getAllOnesValue(BitWidth);
9302 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9303 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9304 unsigned TrailZ = KnownZero.countTrailingOnes();
9305 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9306
9307 if (PrefAlign > Align)
9308 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9309
9310 // We don't need to make any adjustment.
9311 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009312}
9313
Chris Lattnerf497b022008-01-13 23:50:23 +00009314Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009315 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009316 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009317 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009318 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009319
9320 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009321 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009322 return MI;
9323 }
9324
9325 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9326 // load/store.
9327 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9328 if (MemOpLength == 0) return 0;
9329
Chris Lattner37ac6082008-01-14 00:28:35 +00009330 // Source and destination pointer types are always "i8*" for intrinsic. See
9331 // if the size is something we can handle with a single primitive load/store.
9332 // A single load+store correctly handles overlapping memory in the memmove
9333 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009334 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009335 if (Size == 0) return MI; // Delete this mem transfer.
9336
9337 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009338 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009339
Chris Lattner37ac6082008-01-14 00:28:35 +00009340 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009341 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009342
9343 // Memcpy forces the use of i8* for the source and destination. That means
9344 // that if you're using memcpy to move one double around, you'll get a cast
9345 // from double* to i8*. We'd much rather use a double load+store rather than
9346 // an i64 load+store, here because this improves the odds that the source or
9347 // dest address will be promotable. See if we can find a better type than the
9348 // integer datatype.
9349 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9350 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9351 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9352 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9353 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009354 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009355 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9356 if (STy->getNumElements() == 1)
9357 SrcETy = STy->getElementType(0);
9358 else
9359 break;
9360 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9361 if (ATy->getNumElements() == 1)
9362 SrcETy = ATy->getElementType();
9363 else
9364 break;
9365 } else
9366 break;
9367 }
9368
Dan Gohman8f8e2692008-05-23 01:52:21 +00009369 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009370 NewPtrTy = PointerType::getUnqual(SrcETy);
9371 }
9372 }
9373
9374
Chris Lattnerf497b022008-01-13 23:50:23 +00009375 // If the memcpy/memmove provides better alignment info than we can
9376 // infer, use it.
9377 SrcAlign = std::max(SrcAlign, CopyAlign);
9378 DstAlign = std::max(DstAlign, CopyAlign);
9379
9380 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9381 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009382 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9383 InsertNewInstBefore(L, *MI);
9384 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9385
9386 // Set the size of the copy to 0, it will be deleted on the next iteration.
9387 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9388 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009389}
Chris Lattner3d69f462004-03-12 05:52:32 +00009390
Chris Lattner69ea9d22008-04-30 06:39:11 +00009391Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9392 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009393 if (MI->getAlignment() < Alignment) {
9394 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009395 return MI;
9396 }
9397
9398 // Extract the length and alignment and fill if they are constant.
9399 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9400 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9401 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9402 return 0;
9403 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009404 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009405
9406 // If the length is zero, this is a no-op
9407 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9408
9409 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9410 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9411 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9412
9413 Value *Dest = MI->getDest();
9414 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9415
9416 // Alignment 0 is identity for alignment 1 for memset, but not store.
9417 if (Alignment == 0) Alignment = 1;
9418
9419 // Extract the fill value and store.
9420 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9421 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9422 Alignment), *MI);
9423
9424 // Set the size of the copy to 0, it will be deleted on the next iteration.
9425 MI->setLength(Constant::getNullValue(LenC->getType()));
9426 return MI;
9427 }
9428
9429 return 0;
9430}
9431
9432
Chris Lattner8b0ea312006-01-13 20:11:04 +00009433/// visitCallInst - CallInst simplification. This mostly only handles folding
9434/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9435/// the heavy lifting.
9436///
Chris Lattner9fe38862003-06-19 17:00:31 +00009437Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009438 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9439 if (!II) return visitCallSite(&CI);
9440
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009441 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9442 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009443 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009444 bool Changed = false;
9445
9446 // memmove/cpy/set of zero bytes is a noop.
9447 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9448 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9449
Chris Lattner35b9e482004-10-12 04:52:52 +00009450 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009451 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009452 // Replace the instruction with just byte operations. We would
9453 // transform other cases to loads/stores, but we don't know if
9454 // alignment is sufficient.
9455 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009456 }
9457
Chris Lattner35b9e482004-10-12 04:52:52 +00009458 // If we have a memmove and the source operation is a constant global,
9459 // then the source and dest pointers can't alias, so we can change this
9460 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009461 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009462 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9463 if (GVSrc->isConstant()) {
9464 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009465 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9466 const Type *Tys[1];
9467 Tys[0] = CI.getOperand(3)->getType();
9468 CI.setOperand(0,
9469 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009470 Changed = true;
9471 }
Chris Lattnera935db82008-05-28 05:30:41 +00009472
9473 // memmove(x,x,size) -> noop.
9474 if (MMI->getSource() == MMI->getDest())
9475 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009476 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009477
Chris Lattner95a959d2006-03-06 20:18:44 +00009478 // If we can determine a pointer alignment that is bigger than currently
9479 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009480 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009481 if (Instruction *I = SimplifyMemTransfer(MI))
9482 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009483 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9484 if (Instruction *I = SimplifyMemSet(MSI))
9485 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009486 }
9487
Chris Lattner8b0ea312006-01-13 20:11:04 +00009488 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009489 }
9490
9491 switch (II->getIntrinsicID()) {
9492 default: break;
9493 case Intrinsic::bswap:
9494 // bswap(bswap(x)) -> x
9495 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9496 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9497 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9498 break;
9499 case Intrinsic::ppc_altivec_lvx:
9500 case Intrinsic::ppc_altivec_lvxl:
9501 case Intrinsic::x86_sse_loadu_ps:
9502 case Intrinsic::x86_sse2_loadu_pd:
9503 case Intrinsic::x86_sse2_loadu_dq:
9504 // Turn PPC lvx -> load if the pointer is known aligned.
9505 // Turn X86 loadups -> load if the pointer is known aligned.
9506 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9507 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9508 PointerType::getUnqual(II->getType()),
9509 CI);
9510 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009511 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009512 break;
9513 case Intrinsic::ppc_altivec_stvx:
9514 case Intrinsic::ppc_altivec_stvxl:
9515 // Turn stvx -> store if the pointer is known aligned.
9516 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9517 const Type *OpPtrTy =
9518 PointerType::getUnqual(II->getOperand(1)->getType());
9519 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9520 return new StoreInst(II->getOperand(1), Ptr);
9521 }
9522 break;
9523 case Intrinsic::x86_sse_storeu_ps:
9524 case Intrinsic::x86_sse2_storeu_pd:
9525 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009526 // Turn X86 storeu -> store if the pointer is known aligned.
9527 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9528 const Type *OpPtrTy =
9529 PointerType::getUnqual(II->getOperand(2)->getType());
9530 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9531 return new StoreInst(II->getOperand(2), Ptr);
9532 }
9533 break;
9534
9535 case Intrinsic::x86_sse_cvttss2si: {
9536 // These intrinsics only demands the 0th element of its input vector. If
9537 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009538 unsigned VWidth =
9539 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9540 APInt DemandedElts(VWidth, 1);
9541 APInt UndefElts(VWidth, 0);
9542 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009543 UndefElts)) {
9544 II->setOperand(1, V);
9545 return II;
9546 }
9547 break;
9548 }
9549
9550 case Intrinsic::ppc_altivec_vperm:
9551 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9552 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9553 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009554
Chris Lattner0521e3c2008-06-18 04:33:20 +00009555 // Check that all of the elements are integer constants or undefs.
9556 bool AllEltsOk = true;
9557 for (unsigned i = 0; i != 16; ++i) {
9558 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9559 !isa<UndefValue>(Mask->getOperand(i))) {
9560 AllEltsOk = false;
9561 break;
9562 }
9563 }
9564
9565 if (AllEltsOk) {
9566 // Cast the input vectors to byte vectors.
9567 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9568 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9569 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009570
Chris Lattner0521e3c2008-06-18 04:33:20 +00009571 // Only extract each element once.
9572 Value *ExtractedElts[32];
9573 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9574
Chris Lattnere2ed0572006-04-06 19:19:17 +00009575 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009576 if (isa<UndefValue>(Mask->getOperand(i)))
9577 continue;
9578 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9579 Idx &= 31; // Match the hardware behavior.
9580
9581 if (ExtractedElts[Idx] == 0) {
9582 Instruction *Elt =
9583 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9584 InsertNewInstBefore(Elt, CI);
9585 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009586 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009587
Chris Lattner0521e3c2008-06-18 04:33:20 +00009588 // Insert this value into the result vector.
9589 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9590 i, "tmp");
9591 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009592 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009593 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009594 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009595 }
9596 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009597
Chris Lattner0521e3c2008-06-18 04:33:20 +00009598 case Intrinsic::stackrestore: {
9599 // If the save is right next to the restore, remove the restore. This can
9600 // happen when variable allocas are DCE'd.
9601 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9602 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9603 BasicBlock::iterator BI = SS;
9604 if (&*++BI == II)
9605 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009606 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009607 }
9608
9609 // Scan down this block to see if there is another stack restore in the
9610 // same block without an intervening call/alloca.
9611 BasicBlock::iterator BI = II;
9612 TerminatorInst *TI = II->getParent()->getTerminator();
9613 bool CannotRemove = false;
9614 for (++BI; &*BI != TI; ++BI) {
9615 if (isa<AllocaInst>(BI)) {
9616 CannotRemove = true;
9617 break;
9618 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009619 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9620 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9621 // If there is a stackrestore below this one, remove this one.
9622 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9623 return EraseInstFromFunction(CI);
9624 // Otherwise, ignore the intrinsic.
9625 } else {
9626 // If we found a non-intrinsic call, we can't remove the stack
9627 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009628 CannotRemove = true;
9629 break;
9630 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009631 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009632 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009633
9634 // If the stack restore is in a return/unwind block and if there are no
9635 // allocas or calls between the restore and the return, nuke the restore.
9636 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9637 return EraseInstFromFunction(CI);
9638 break;
9639 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009640 }
9641
Chris Lattner8b0ea312006-01-13 20:11:04 +00009642 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009643}
9644
9645// InvokeInst simplification
9646//
9647Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009648 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009649}
9650
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009651/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9652/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009653static bool isSafeToEliminateVarargsCast(const CallSite CS,
9654 const CastInst * const CI,
9655 const TargetData * const TD,
9656 const int ix) {
9657 if (!CI->isLosslessCast())
9658 return false;
9659
9660 // The size of ByVal arguments is derived from the type, so we
9661 // can't change to a type with a different size. If the size were
9662 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009663 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009664 return true;
9665
9666 const Type* SrcTy =
9667 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9668 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9669 if (!SrcTy->isSized() || !DstTy->isSized())
9670 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009671 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009672 return false;
9673 return true;
9674}
9675
Chris Lattnera44d8a22003-10-07 22:32:43 +00009676// visitCallSite - Improvements for call and invoke instructions.
9677//
9678Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009679 bool Changed = false;
9680
9681 // If the callee is a constexpr cast of a function, attempt to move the cast
9682 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009683 if (transformConstExprCastCall(CS)) return 0;
9684
Chris Lattner6c266db2003-10-07 22:54:13 +00009685 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009686
Chris Lattner08b22ec2005-05-13 07:09:09 +00009687 if (Function *CalleeF = dyn_cast<Function>(Callee))
9688 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9689 Instruction *OldCall = CS.getInstruction();
9690 // If the call and callee calling conventions don't match, this call must
9691 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009692 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009693 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9694 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009695 if (!OldCall->use_empty())
9696 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9697 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9698 return EraseInstFromFunction(*OldCall);
9699 return 0;
9700 }
9701
Chris Lattner17be6352004-10-18 02:59:09 +00009702 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9703 // This instruction is not reachable, just remove it. We insert a store to
9704 // undef so that we know that this code is not reachable, despite the fact
9705 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009706 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009707 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009708 CS.getInstruction());
9709
9710 if (!CS.getInstruction()->use_empty())
9711 CS.getInstruction()->
9712 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9713
9714 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9715 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009716 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9717 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009718 }
Chris Lattner17be6352004-10-18 02:59:09 +00009719 return EraseInstFromFunction(*CS.getInstruction());
9720 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009721
Duncan Sandscdb6d922007-09-17 10:26:40 +00009722 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9723 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9724 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9725 return transformCallThroughTrampoline(CS);
9726
Chris Lattner6c266db2003-10-07 22:54:13 +00009727 const PointerType *PTy = cast<PointerType>(Callee->getType());
9728 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9729 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009730 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009731 // See if we can optimize any arguments passed through the varargs area of
9732 // the call.
9733 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009734 E = CS.arg_end(); I != E; ++I, ++ix) {
9735 CastInst *CI = dyn_cast<CastInst>(*I);
9736 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9737 *I = CI->getOperand(0);
9738 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009739 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009740 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009741 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009742
Duncan Sandsf0c33542007-12-19 21:13:37 +00009743 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009744 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009745 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009746 Changed = true;
9747 }
9748
Chris Lattner6c266db2003-10-07 22:54:13 +00009749 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009750}
9751
Chris Lattner9fe38862003-06-19 17:00:31 +00009752// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9753// attempt to move the cast to the arguments of the call/invoke.
9754//
9755bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9756 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9757 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009758 if (CE->getOpcode() != Instruction::BitCast ||
9759 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009760 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009761 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009762 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009763 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009764
9765 // Okay, this is a cast from a function to a different type. Unless doing so
9766 // would cause a type conversion of one of our arguments, change this call to
9767 // be a direct call with arguments casted to the appropriate types.
9768 //
9769 const FunctionType *FT = Callee->getFunctionType();
9770 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009771 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009772
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009773 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009774 return false; // TODO: Handle multiple return values.
9775
Chris Lattnerf78616b2004-01-14 06:06:08 +00009776 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009777 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009778 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009779 // Conversion is ok if changing from one pointer type to another or from
9780 // a pointer to an integer of the same size.
9781 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009782 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009783 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009784
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009785 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009786 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009787 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009788 return false; // Cannot transform this return value.
9789
Chris Lattner58d74912008-03-12 17:45:29 +00009790 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009791 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009792 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009793 return false; // Attribute not compatible with transformed value.
9794 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009795
Chris Lattnerf78616b2004-01-14 06:06:08 +00009796 // If the callsite is an invoke instruction, and the return value is used by
9797 // a PHI node in a successor, we cannot change the return type of the call
9798 // because there is no place to put the cast instruction (without breaking
9799 // the critical edge). Bail out in this case.
9800 if (!Caller->use_empty())
9801 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9802 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9803 UI != E; ++UI)
9804 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9805 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009806 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009807 return false;
9808 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009809
9810 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9811 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009812
Chris Lattner9fe38862003-06-19 17:00:31 +00009813 CallSite::arg_iterator AI = CS.arg_begin();
9814 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9815 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009816 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009817
9818 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009819 return false; // Cannot transform this parameter value.
9820
Devang Patel19c87462008-09-26 22:53:05 +00009821 if (CallerPAL.getParamAttributes(i + 1)
9822 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009823 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009824
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009825 // Converting from one pointer type to another or between a pointer and an
9826 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009827 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009828 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9829 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009830 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009831 }
9832
9833 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009834 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009835 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009836
Chris Lattner58d74912008-03-12 17:45:29 +00009837 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9838 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009839 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009840 // won't be dropping them. Check that these extra arguments have attributes
9841 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009842 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9843 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009844 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009845 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009846 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009847 return false;
9848 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009849
Chris Lattner9fe38862003-06-19 17:00:31 +00009850 // Okay, we decided that this is a safe thing to do: go ahead and start
9851 // inserting cast instructions as necessary...
9852 std::vector<Value*> Args;
9853 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009854 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009855 attrVec.reserve(NumCommonArgs);
9856
9857 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009858 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009859
9860 // If the return value is not being used, the type may not be compatible
9861 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009862 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009863
9864 // Add the new return attributes.
9865 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009866 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009867
9868 AI = CS.arg_begin();
9869 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9870 const Type *ParamTy = FT->getParamType(i);
9871 if ((*AI)->getType() == ParamTy) {
9872 Args.push_back(*AI);
9873 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009874 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009875 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009876 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009877 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009878 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009879
9880 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009881 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009882 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009883 }
9884
9885 // If the function takes more arguments than the call was taking, add them
9886 // now...
9887 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9888 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9889
9890 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009891 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009892 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009893 cerr << "WARNING: While resolving call to function '"
9894 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009895 } else {
9896 // Add all of the arguments in their promoted form to the arg list...
9897 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9898 const Type *PTy = getPromotedType((*AI)->getType());
9899 if (PTy != (*AI)->getType()) {
9900 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009901 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9902 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009903 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009904 InsertNewInstBefore(Cast, *Caller);
9905 Args.push_back(Cast);
9906 } else {
9907 Args.push_back(*AI);
9908 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009909
Duncan Sandse1e520f2008-01-13 08:02:44 +00009910 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009911 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009912 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009913 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009914 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009915 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009916
Devang Patel19c87462008-09-26 22:53:05 +00009917 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9918 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9919
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009920 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009921 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009922
Devang Patel05988662008-09-25 21:00:45 +00009923 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009924
Chris Lattner9fe38862003-06-19 17:00:31 +00009925 Instruction *NC;
9926 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009927 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009928 Args.begin(), Args.end(),
9929 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009930 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009931 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009932 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009933 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9934 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009935 CallInst *CI = cast<CallInst>(Caller);
9936 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009937 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009938 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009939 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009940 }
9941
Chris Lattner6934a042007-02-11 01:23:03 +00009942 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009943 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009944 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009945 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009946 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009947 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009948 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009949
9950 // If this is an invoke instruction, we should insert it after the first
9951 // non-phi, instruction in the normal successor block.
9952 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009953 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009954 InsertNewInstBefore(NC, *I);
9955 } else {
9956 // Otherwise, it's a call, just insert cast right after the call instr
9957 InsertNewInstBefore(NC, *Caller);
9958 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009959 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009960 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009961 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009962 }
9963 }
9964
9965 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9966 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009967 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009968 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009969 return true;
9970}
9971
Duncan Sandscdb6d922007-09-17 10:26:40 +00009972// transformCallThroughTrampoline - Turn a call to a function created by the
9973// init_trampoline intrinsic into a direct call to the underlying function.
9974//
9975Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9976 Value *Callee = CS.getCalledValue();
9977 const PointerType *PTy = cast<PointerType>(Callee->getType());
9978 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009979 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009980
9981 // If the call already has the 'nest' attribute somewhere then give up -
9982 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009983 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009984 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009985
9986 IntrinsicInst *Tramp =
9987 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9988
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009989 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009990 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9991 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9992
Devang Patel05988662008-09-25 21:00:45 +00009993 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009994 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009995 unsigned NestIdx = 1;
9996 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009997 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009998
9999 // Look for a parameter marked with the 'nest' attribute.
10000 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10001 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010002 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010003 // Record the parameter type and any other attributes.
10004 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010005 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010006 break;
10007 }
10008
10009 if (NestTy) {
10010 Instruction *Caller = CS.getInstruction();
10011 std::vector<Value*> NewArgs;
10012 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10013
Devang Patel05988662008-09-25 21:00:45 +000010014 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010015 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010016
Duncan Sandscdb6d922007-09-17 10:26:40 +000010017 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010018 // mean appending it. Likewise for attributes.
10019
Devang Patel19c87462008-09-26 22:53:05 +000010020 // Add any result attributes.
10021 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010022 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010023
Duncan Sandscdb6d922007-09-17 10:26:40 +000010024 {
10025 unsigned Idx = 1;
10026 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10027 do {
10028 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010029 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010030 Value *NestVal = Tramp->getOperand(3);
10031 if (NestVal->getType() != NestTy)
10032 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10033 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010034 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010035 }
10036
10037 if (I == E)
10038 break;
10039
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010040 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010041 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010042 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010043 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010044 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010045
10046 ++Idx, ++I;
10047 } while (1);
10048 }
10049
Devang Patel19c87462008-09-26 22:53:05 +000010050 // Add any function attributes.
10051 if (Attributes Attr = Attrs.getFnAttributes())
10052 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10053
Duncan Sandscdb6d922007-09-17 10:26:40 +000010054 // The trampoline may have been bitcast to a bogus type (FTy).
10055 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010056 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010057
Duncan Sandscdb6d922007-09-17 10:26:40 +000010058 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010059 NewTypes.reserve(FTy->getNumParams()+1);
10060
Duncan Sandscdb6d922007-09-17 10:26:40 +000010061 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010062 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010063 {
10064 unsigned Idx = 1;
10065 FunctionType::param_iterator I = FTy->param_begin(),
10066 E = FTy->param_end();
10067
10068 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010069 if (Idx == NestIdx)
10070 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010071 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010072
10073 if (I == E)
10074 break;
10075
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010076 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010077 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010078
10079 ++Idx, ++I;
10080 } while (1);
10081 }
10082
10083 // Replace the trampoline call with a direct call. Let the generic
10084 // code sort out any function type mismatches.
10085 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010086 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010087 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10088 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010089 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010090
10091 Instruction *NewCaller;
10092 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010093 NewCaller = InvokeInst::Create(NewCallee,
10094 II->getNormalDest(), II->getUnwindDest(),
10095 NewArgs.begin(), NewArgs.end(),
10096 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010097 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010098 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010099 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010100 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10101 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010102 if (cast<CallInst>(Caller)->isTailCall())
10103 cast<CallInst>(NewCaller)->setTailCall();
10104 cast<CallInst>(NewCaller)->
10105 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010106 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010107 }
10108 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10109 Caller->replaceAllUsesWith(NewCaller);
10110 Caller->eraseFromParent();
10111 RemoveFromWorkList(Caller);
10112 return 0;
10113 }
10114 }
10115
10116 // Replace the trampoline call with a direct call. Since there is no 'nest'
10117 // parameter, there is no need to adjust the argument list. Let the generic
10118 // code sort out any function type mismatches.
10119 Constant *NewCallee =
10120 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10121 CS.setCalledFunction(NewCallee);
10122 return CS.getInstruction();
10123}
10124
Chris Lattner7da52b22006-11-01 04:51:18 +000010125/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10126/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10127/// and a single binop.
10128Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10129 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010130 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010131 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010132 Value *LHSVal = FirstInst->getOperand(0);
10133 Value *RHSVal = FirstInst->getOperand(1);
10134
10135 const Type *LHSType = LHSVal->getType();
10136 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010137
10138 // Scan to see if all operands are the same opcode, all have one use, and all
10139 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010140 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010141 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010142 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010143 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010144 // types or GEP's with different index types.
10145 I->getOperand(0)->getType() != LHSType ||
10146 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010147 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010148
10149 // If they are CmpInst instructions, check their predicates
10150 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10151 if (cast<CmpInst>(I)->getPredicate() !=
10152 cast<CmpInst>(FirstInst)->getPredicate())
10153 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010154
10155 // Keep track of which operand needs a phi node.
10156 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10157 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010158 }
10159
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010160 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010161
Chris Lattner7da52b22006-11-01 04:51:18 +000010162 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010163 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010164 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010165 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010166 NewLHS = PHINode::Create(LHSType,
10167 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010168 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10169 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010170 InsertNewInstBefore(NewLHS, PN);
10171 LHSVal = NewLHS;
10172 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010173
10174 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010175 NewRHS = PHINode::Create(RHSType,
10176 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010177 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10178 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010179 InsertNewInstBefore(NewRHS, PN);
10180 RHSVal = NewRHS;
10181 }
10182
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010183 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010184 if (NewLHS || NewRHS) {
10185 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10186 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10187 if (NewLHS) {
10188 Value *NewInLHS = InInst->getOperand(0);
10189 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10190 }
10191 if (NewRHS) {
10192 Value *NewInRHS = InInst->getOperand(1);
10193 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10194 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010195 }
10196 }
10197
Chris Lattner7da52b22006-11-01 04:51:18 +000010198 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010199 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010200 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10201 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10202 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010203}
10204
Chris Lattner05f18922008-12-01 02:34:36 +000010205Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10206 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10207
10208 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10209 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010210 // This is true if all GEP bases are allocas and if all indices into them are
10211 // constants.
10212 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010213
10214 // Scan to see if all operands are the same opcode, all have one use, and all
10215 // kill their operands (i.e. the operands have one use).
10216 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10217 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10218 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10219 GEP->getNumOperands() != FirstInst->getNumOperands())
10220 return 0;
10221
Chris Lattner36d3e322009-02-21 00:46:50 +000010222 // Keep track of whether or not all GEPs are of alloca pointers.
10223 if (AllBasePointersAreAllocas &&
10224 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10225 !GEP->hasAllConstantIndices()))
10226 AllBasePointersAreAllocas = false;
10227
Chris Lattner05f18922008-12-01 02:34:36 +000010228 // Compare the operand lists.
10229 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10230 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10231 continue;
10232
10233 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10234 // if one of the PHIs has a constant for the index. The index may be
10235 // substantially cheaper to compute for the constants, so making it a
10236 // variable index could pessimize the path. This also handles the case
10237 // for struct indices, which must always be constant.
10238 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10239 isa<ConstantInt>(GEP->getOperand(op)))
10240 return 0;
10241
10242 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10243 return 0;
10244 FixedOperands[op] = 0; // Needs a PHI.
10245 }
10246 }
10247
Chris Lattner36d3e322009-02-21 00:46:50 +000010248 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010249 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010250 // offset calculation, but all the predecessors will have to materialize the
10251 // stack address into a register anyway. We'd actually rather *clone* the
10252 // load up into the predecessors so that we have a load of a gep of an alloca,
10253 // which can usually all be folded into the load.
10254 if (AllBasePointersAreAllocas)
10255 return 0;
10256
Chris Lattner05f18922008-12-01 02:34:36 +000010257 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10258 // that is variable.
10259 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10260
10261 bool HasAnyPHIs = false;
10262 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10263 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10264 Value *FirstOp = FirstInst->getOperand(i);
10265 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10266 FirstOp->getName()+".pn");
10267 InsertNewInstBefore(NewPN, PN);
10268
10269 NewPN->reserveOperandSpace(e);
10270 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10271 OperandPhis[i] = NewPN;
10272 FixedOperands[i] = NewPN;
10273 HasAnyPHIs = true;
10274 }
10275
10276
10277 // Add all operands to the new PHIs.
10278 if (HasAnyPHIs) {
10279 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10280 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10281 BasicBlock *InBB = PN.getIncomingBlock(i);
10282
10283 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10284 if (PHINode *OpPhi = OperandPhis[op])
10285 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10286 }
10287 }
10288
10289 Value *Base = FixedOperands[0];
10290 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10291 FixedOperands.end());
10292}
10293
10294
Chris Lattner21550882009-02-23 05:56:17 +000010295/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10296/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010297/// obvious the value of the load is not changed from the point of the load to
10298/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010299///
10300/// Finally, it is safe, but not profitable, to sink a load targetting a
10301/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10302/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010303static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010304 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10305
10306 for (++BBI; BBI != E; ++BBI)
10307 if (BBI->mayWriteToMemory())
10308 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010309
10310 // Check for non-address taken alloca. If not address-taken already, it isn't
10311 // profitable to do this xform.
10312 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10313 bool isAddressTaken = false;
10314 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10315 UI != E; ++UI) {
10316 if (isa<LoadInst>(UI)) continue;
10317 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10318 // If storing TO the alloca, then the address isn't taken.
10319 if (SI->getOperand(1) == AI) continue;
10320 }
10321 isAddressTaken = true;
10322 break;
10323 }
10324
Chris Lattner36d3e322009-02-21 00:46:50 +000010325 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010326 return false;
10327 }
10328
Chris Lattner36d3e322009-02-21 00:46:50 +000010329 // If this load is a load from a GEP with a constant offset from an alloca,
10330 // then we don't want to sink it. In its present form, it will be
10331 // load [constant stack offset]. Sinking it will cause us to have to
10332 // materialize the stack addresses in each predecessor in a register only to
10333 // do a shared load from register in the successor.
10334 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10335 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10336 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10337 return false;
10338
Chris Lattner76c73142006-11-01 07:13:54 +000010339 return true;
10340}
10341
Chris Lattner9fe38862003-06-19 17:00:31 +000010342
Chris Lattnerbac32862004-11-14 19:13:23 +000010343// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10344// operator and they all are only used by the PHI, PHI together their
10345// inputs, and do the operation once, to the result of the PHI.
10346Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10347 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10348
10349 // Scan the instruction, looking for input operations that can be folded away.
10350 // If all input operands to the phi are the same instruction (e.g. a cast from
10351 // the same type or "+42") we can pull the operation through the PHI, reducing
10352 // code size and simplifying code.
10353 Constant *ConstantOp = 0;
10354 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010355 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010356 if (isa<CastInst>(FirstInst)) {
10357 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010358 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010359 // Can fold binop, compare or shift here if the RHS is a constant,
10360 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010361 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010362 if (ConstantOp == 0)
10363 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010364 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10365 isVolatile = LI->isVolatile();
10366 // We can't sink the load if the loaded value could be modified between the
10367 // load and the PHI.
10368 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010369 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010370 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010371
10372 // If the PHI is of volatile loads and the load block has multiple
10373 // successors, sinking it would remove a load of the volatile value from
10374 // the path through the other successor.
10375 if (isVolatile &&
10376 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10377 return 0;
10378
Chris Lattner9c080502006-11-01 07:43:41 +000010379 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010380 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010381 } else {
10382 return 0; // Cannot fold this operation.
10383 }
10384
10385 // Check to see if all arguments are the same operation.
10386 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10387 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10388 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010389 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010390 return 0;
10391 if (CastSrcTy) {
10392 if (I->getOperand(0)->getType() != CastSrcTy)
10393 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010394 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010395 // We can't sink the load if the loaded value could be modified between
10396 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010397 if (LI->isVolatile() != isVolatile ||
10398 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010399 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010400 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010401
Chris Lattner71042962008-07-08 17:18:32 +000010402 // If the PHI is of volatile loads and the load block has multiple
10403 // successors, sinking it would remove a load of the volatile value from
10404 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010405 if (isVolatile &&
10406 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10407 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010408
Chris Lattnerbac32862004-11-14 19:13:23 +000010409 } else if (I->getOperand(1) != ConstantOp) {
10410 return 0;
10411 }
10412 }
10413
10414 // Okay, they are all the same operation. Create a new PHI node of the
10415 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010416 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10417 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010418 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010419
10420 Value *InVal = FirstInst->getOperand(0);
10421 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010422
10423 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010424 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10425 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10426 if (NewInVal != InVal)
10427 InVal = 0;
10428 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10429 }
10430
10431 Value *PhiVal;
10432 if (InVal) {
10433 // The new PHI unions all of the same values together. This is really
10434 // common, so we handle it intelligently here for compile-time speed.
10435 PhiVal = InVal;
10436 delete NewPN;
10437 } else {
10438 InsertNewInstBefore(NewPN, PN);
10439 PhiVal = NewPN;
10440 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010441
Chris Lattnerbac32862004-11-14 19:13:23 +000010442 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010443 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010444 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010445 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010446 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010447 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010448 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010449 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010450 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10451
10452 // If this was a volatile load that we are merging, make sure to loop through
10453 // and mark all the input loads as non-volatile. If we don't do this, we will
10454 // insert a new volatile load and the old ones will not be deletable.
10455 if (isVolatile)
10456 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10457 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10458
10459 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010460}
Chris Lattnera1be5662002-05-02 17:06:02 +000010461
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010462/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10463/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010464static bool DeadPHICycle(PHINode *PN,
10465 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010466 if (PN->use_empty()) return true;
10467 if (!PN->hasOneUse()) return false;
10468
10469 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010470 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010471 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010472
10473 // Don't scan crazily complex things.
10474 if (PotentiallyDeadPHIs.size() == 16)
10475 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010476
10477 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10478 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010479
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010480 return false;
10481}
10482
Chris Lattnercf5008a2007-11-06 21:52:06 +000010483/// PHIsEqualValue - Return true if this phi node is always equal to
10484/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10485/// z = some value; x = phi (y, z); y = phi (x, z)
10486static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10487 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10488 // See if we already saw this PHI node.
10489 if (!ValueEqualPHIs.insert(PN))
10490 return true;
10491
10492 // Don't scan crazily complex things.
10493 if (ValueEqualPHIs.size() == 16)
10494 return false;
10495
10496 // Scan the operands to see if they are either phi nodes or are equal to
10497 // the value.
10498 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10499 Value *Op = PN->getIncomingValue(i);
10500 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10501 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10502 return false;
10503 } else if (Op != NonPhiInVal)
10504 return false;
10505 }
10506
10507 return true;
10508}
10509
10510
Chris Lattner473945d2002-05-06 18:06:38 +000010511// PHINode simplification
10512//
Chris Lattner7e708292002-06-25 16:13:24 +000010513Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010514 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010515 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010516
Owen Anderson7e057142006-07-10 22:03:18 +000010517 if (Value *V = PN.hasConstantValue())
10518 return ReplaceInstUsesWith(PN, V);
10519
Owen Anderson7e057142006-07-10 22:03:18 +000010520 // If all PHI operands are the same operation, pull them through the PHI,
10521 // reducing code size.
10522 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010523 isa<Instruction>(PN.getIncomingValue(1)) &&
10524 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10525 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10526 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10527 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010528 PN.getIncomingValue(0)->hasOneUse())
10529 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10530 return Result;
10531
10532 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10533 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10534 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010535 if (PN.hasOneUse()) {
10536 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10537 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010538 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010539 PotentiallyDeadPHIs.insert(&PN);
10540 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10541 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10542 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010543
10544 // If this phi has a single use, and if that use just computes a value for
10545 // the next iteration of a loop, delete the phi. This occurs with unused
10546 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10547 // common case here is good because the only other things that catch this
10548 // are induction variable analysis (sometimes) and ADCE, which is only run
10549 // late.
10550 if (PHIUser->hasOneUse() &&
10551 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10552 PHIUser->use_back() == &PN) {
10553 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10554 }
10555 }
Owen Anderson7e057142006-07-10 22:03:18 +000010556
Chris Lattnercf5008a2007-11-06 21:52:06 +000010557 // We sometimes end up with phi cycles that non-obviously end up being the
10558 // same value, for example:
10559 // z = some value; x = phi (y, z); y = phi (x, z)
10560 // where the phi nodes don't necessarily need to be in the same block. Do a
10561 // quick check to see if the PHI node only contains a single non-phi value, if
10562 // so, scan to see if the phi cycle is actually equal to that value.
10563 {
10564 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10565 // Scan for the first non-phi operand.
10566 while (InValNo != NumOperandVals &&
10567 isa<PHINode>(PN.getIncomingValue(InValNo)))
10568 ++InValNo;
10569
10570 if (InValNo != NumOperandVals) {
10571 Value *NonPhiInVal = PN.getOperand(InValNo);
10572
10573 // Scan the rest of the operands to see if there are any conflicts, if so
10574 // there is no need to recursively scan other phis.
10575 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10576 Value *OpVal = PN.getIncomingValue(InValNo);
10577 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10578 break;
10579 }
10580
10581 // If we scanned over all operands, then we have one unique value plus
10582 // phi values. Scan PHI nodes to see if they all merge in each other or
10583 // the value.
10584 if (InValNo == NumOperandVals) {
10585 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10586 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10587 return ReplaceInstUsesWith(PN, NonPhiInVal);
10588 }
10589 }
10590 }
Chris Lattner60921c92003-12-19 05:58:40 +000010591 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010592}
10593
Reid Spencer17212df2006-12-12 09:18:51 +000010594static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10595 Instruction *InsertPoint,
10596 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010597 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10598 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010599 // We must cast correctly to the pointer type. Ensure that we
10600 // sign extend the integer value if it is smaller as this is
10601 // used for address computation.
10602 Instruction::CastOps opcode =
10603 (VTySize < PtrSize ? Instruction::SExt :
10604 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10605 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010606}
10607
Chris Lattnera1be5662002-05-02 17:06:02 +000010608
Chris Lattner7e708292002-06-25 16:13:24 +000010609Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010610 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010611 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010612 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010613 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010614 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010615
Chris Lattnere87597f2004-10-16 18:11:37 +000010616 if (isa<UndefValue>(GEP.getOperand(0)))
10617 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10618
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010619 bool HasZeroPointerIndex = false;
10620 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10621 HasZeroPointerIndex = C->isNullValue();
10622
10623 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010624 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010625
Chris Lattner28977af2004-04-05 01:30:19 +000010626 // Eliminate unneeded casts for indices.
10627 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010628
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010629 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010630 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10631 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010632 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010633 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010634 if (CI->getOpcode() == Instruction::ZExt ||
10635 CI->getOpcode() == Instruction::SExt) {
10636 const Type *SrcTy = CI->getOperand(0)->getType();
10637 // We can eliminate a cast from i32 to i64 iff the target
10638 // is a 32-bit pointer target.
10639 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10640 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010641 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010642 }
10643 }
10644 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010645 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010646 // to what we need. If narrower, sign-extend it to what we need.
10647 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010648 // insert it. This explicit cast can make subsequent optimizations more
10649 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010650 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010651 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010652 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010653 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010654 MadeChange = true;
10655 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010656 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10657 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010658 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010659 MadeChange = true;
10660 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010661 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10662 if (Constant *C = dyn_cast<Constant>(Op)) {
10663 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10664 MadeChange = true;
10665 } else {
10666 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10667 GEP);
10668 *i = Op;
10669 MadeChange = true;
10670 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010671 }
Chris Lattner28977af2004-04-05 01:30:19 +000010672 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010673 }
Chris Lattner28977af2004-04-05 01:30:19 +000010674 if (MadeChange) return &GEP;
10675
Chris Lattner90ac28c2002-08-02 19:29:35 +000010676 // Combine Indices - If the source pointer to this getelementptr instruction
10677 // is a getelementptr instruction, combine the indices of the two
10678 // getelementptr instructions into a single instruction.
10679 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010680 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010681 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010682 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010683
10684 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010685 // Note that if our source is a gep chain itself that we wait for that
10686 // chain to be resolved before we perform this transformation. This
10687 // avoids us creating a TON of code in some cases.
10688 //
10689 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10690 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10691 return 0; // Wait until our source is folded to completion.
10692
Chris Lattner72588fc2007-02-15 22:48:32 +000010693 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010694
10695 // Find out whether the last index in the source GEP is a sequential idx.
10696 bool EndsWithSequential = false;
10697 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10698 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010699 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010700
Chris Lattner90ac28c2002-08-02 19:29:35 +000010701 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010702 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010703 // Replace: gep (gep %P, long B), long A, ...
10704 // With: T = long A+B; gep %P, T, ...
10705 //
Chris Lattner620ce142004-05-07 22:09:22 +000010706 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010707 if (SO1 == Constant::getNullValue(SO1->getType())) {
10708 Sum = GO1;
10709 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10710 Sum = SO1;
10711 } else {
10712 // If they aren't the same type, convert both to an integer of the
10713 // target's pointer size.
10714 if (SO1->getType() != GO1->getType()) {
10715 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010716 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010717 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010718 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010719 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010720 unsigned PS = TD->getPointerSizeInBits();
10721 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010722 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010723 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010724
Duncan Sands514ab342007-11-01 20:53:16 +000010725 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010726 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010727 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010728 } else {
10729 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010730 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10731 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010732 }
10733 }
10734 }
Chris Lattner620ce142004-05-07 22:09:22 +000010735 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10736 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10737 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010738 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010739 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010740 }
Chris Lattner28977af2004-04-05 01:30:19 +000010741 }
Chris Lattner620ce142004-05-07 22:09:22 +000010742
10743 // Recycle the GEP we already have if possible.
10744 if (SrcGEPOperands.size() == 2) {
10745 GEP.setOperand(0, SrcGEPOperands[0]);
10746 GEP.setOperand(1, Sum);
10747 return &GEP;
10748 } else {
10749 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10750 SrcGEPOperands.end()-1);
10751 Indices.push_back(Sum);
10752 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10753 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010754 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010755 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010756 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010757 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010758 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10759 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010760 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10761 }
10762
10763 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010764 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10765 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010766
Chris Lattner620ce142004-05-07 22:09:22 +000010767 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010768 // GEP of global variable. If all of the indices for this GEP are
10769 // constants, we can promote this to a constexpr instead of an instruction.
10770
10771 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010772 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010773 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10774 for (; I != E && isa<Constant>(*I); ++I)
10775 Indices.push_back(cast<Constant>(*I));
10776
10777 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010778 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10779 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010780
10781 // Replace all uses of the GEP with the new constexpr...
10782 return ReplaceInstUsesWith(GEP, CE);
10783 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010784 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010785 if (!isa<PointerType>(X->getType())) {
10786 // Not interesting. Source pointer must be a cast from pointer.
10787 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010788 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10789 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010790 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010791 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10792 // into : GEP i8* X, ...
10793 //
Chris Lattnereed48272005-09-13 00:40:14 +000010794 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010795 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10796 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010797 if (const ArrayType *CATy =
10798 dyn_cast<ArrayType>(CPTy->getElementType())) {
10799 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10800 if (CATy->getElementType() == XTy->getElementType()) {
10801 // -> GEP i8* X, ...
10802 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10803 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10804 GEP.getName());
10805 } else if (const ArrayType *XATy =
10806 dyn_cast<ArrayType>(XTy->getElementType())) {
10807 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010808 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010809 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010810 // At this point, we know that the cast source type is a pointer
10811 // to an array of the same type as the destination pointer
10812 // array. Because the array type is never stepped over (there
10813 // is a leading zero) we can fold the cast into this GEP.
10814 GEP.setOperand(0, X);
10815 return &GEP;
10816 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010817 }
10818 }
Chris Lattnereed48272005-09-13 00:40:14 +000010819 } else if (GEP.getNumOperands() == 2) {
10820 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010821 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10822 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010823 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10824 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10825 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010826 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10827 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010828 Value *Idx[2];
10829 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10830 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010831 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010832 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010833 // V and GEP are both pointer types --> BitCast
10834 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010835 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010836
10837 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010838 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010839 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010840 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010841
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010842 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010843 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010844 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010845
10846 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10847 // allow either a mul, shift, or constant here.
10848 Value *NewIdx = 0;
10849 ConstantInt *Scale = 0;
10850 if (ArrayEltSize == 1) {
10851 NewIdx = GEP.getOperand(1);
10852 Scale = ConstantInt::get(NewIdx->getType(), 1);
10853 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010854 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010855 Scale = CI;
10856 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10857 if (Inst->getOpcode() == Instruction::Shl &&
10858 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010859 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10860 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10861 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010862 NewIdx = Inst->getOperand(0);
10863 } else if (Inst->getOpcode() == Instruction::Mul &&
10864 isa<ConstantInt>(Inst->getOperand(1))) {
10865 Scale = cast<ConstantInt>(Inst->getOperand(1));
10866 NewIdx = Inst->getOperand(0);
10867 }
10868 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010869
Chris Lattner7835cdd2005-09-13 18:36:04 +000010870 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010871 // out, perform the transformation. Note, we don't know whether Scale is
10872 // signed or not. We'll use unsigned version of division/modulo
10873 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000010874 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010875 Scale->getZExtValue() % ArrayEltSize == 0) {
10876 Scale = ConstantInt::get(Scale->getType(),
10877 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010878 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010879 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010880 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010881 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010882 NewIdx = InsertNewInstBefore(Sc, GEP);
10883 }
10884
10885 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010886 Value *Idx[2];
10887 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10888 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010889 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010890 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010891 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10892 // The NewGEP must be pointer typed, so must the old one -> BitCast
10893 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010894 }
10895 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010896 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010897 }
Chris Lattner58407792009-01-09 04:53:57 +000010898
Chris Lattner46cd5a12009-01-09 05:44:56 +000010899 /// See if we can simplify:
10900 /// X = bitcast A to B*
10901 /// Y = gep X, <...constant indices...>
10902 /// into a gep of the original struct. This is important for SROA and alias
10903 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010904 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010905 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10906 // Determine how much the GEP moves the pointer. We are guaranteed to get
10907 // a constant back from EmitGEPOffset.
10908 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10909 int64_t Offset = OffsetV->getSExtValue();
10910
10911 // If this GEP instruction doesn't move the pointer, just replace the GEP
10912 // with a bitcast of the real input to the dest type.
10913 if (Offset == 0) {
10914 // If the bitcast is of an allocation, and the allocation will be
10915 // converted to match the type of the cast, don't touch this.
10916 if (isa<AllocationInst>(BCI->getOperand(0))) {
10917 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10918 if (Instruction *I = visitBitCast(*BCI)) {
10919 if (I != BCI) {
10920 I->takeName(BCI);
10921 BCI->getParent()->getInstList().insert(BCI, I);
10922 ReplaceInstUsesWith(*BCI, I);
10923 }
10924 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010925 }
Chris Lattner58407792009-01-09 04:53:57 +000010926 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010927 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010928 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010929
10930 // Otherwise, if the offset is non-zero, we need to find out if there is a
10931 // field at Offset in 'A's type. If so, we can pull the cast through the
10932 // GEP.
10933 SmallVector<Value*, 8> NewIndices;
10934 const Type *InTy =
10935 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10936 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10937 Instruction *NGEP =
10938 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10939 NewIndices.end());
10940 if (NGEP->getType() == GEP.getType()) return NGEP;
10941 InsertNewInstBefore(NGEP, GEP);
10942 NGEP->takeName(&GEP);
10943 return new BitCastInst(NGEP, GEP.getType());
10944 }
Chris Lattner58407792009-01-09 04:53:57 +000010945 }
10946 }
10947
Chris Lattner8a2a3112001-12-14 16:52:21 +000010948 return 0;
10949}
10950
Chris Lattner0864acf2002-11-04 16:18:53 +000010951Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10952 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010953 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010954 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10955 const Type *NewTy =
10956 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010957 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010958
10959 // Create and insert the replacement instruction...
10960 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010961 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010962 else {
10963 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010964 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010965 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010966
10967 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010968
Chris Lattner0864acf2002-11-04 16:18:53 +000010969 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000010970 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000010971 //
10972 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000010973 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000010974
10975 // Now that I is pointing to the first non-allocation-inst in the block,
10976 // insert our getelementptr instruction...
10977 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010978 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010979 Value *Idx[2];
10980 Idx[0] = NullIdx;
10981 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010982 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10983 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010984
10985 // Now make everything use the getelementptr instead of the original
10986 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010987 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010988 } else if (isa<UndefValue>(AI.getArraySize())) {
10989 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010990 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010991 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010992
Dan Gohman6893cd72009-01-13 20:18:38 +000010993 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10994 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000010995 // Note that we only do this for alloca's, because malloc should allocate
10996 // and return a unique pointer, even for a zero byte allocation.
Dan Gohman6893cd72009-01-13 20:18:38 +000010997 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10998 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10999
11000 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11001 if (AI.getAlignment() == 0)
11002 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11003 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011004
Chris Lattner0864acf2002-11-04 16:18:53 +000011005 return 0;
11006}
11007
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011008Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11009 Value *Op = FI.getOperand(0);
11010
Chris Lattner17be6352004-10-18 02:59:09 +000011011 // free undef -> unreachable.
11012 if (isa<UndefValue>(Op)) {
11013 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011014 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011015 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011016 return EraseInstFromFunction(FI);
11017 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011018
Chris Lattner6160e852004-02-28 04:57:37 +000011019 // If we have 'free null' delete the instruction. This can happen in stl code
11020 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011021 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011022 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011023
11024 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11025 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11026 FI.setOperand(0, CI->getOperand(0));
11027 return &FI;
11028 }
11029
11030 // Change free (gep X, 0,0,0,0) into free(X)
11031 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11032 if (GEPI->hasAllZeroIndices()) {
11033 AddToWorkList(GEPI);
11034 FI.setOperand(0, GEPI->getOperand(0));
11035 return &FI;
11036 }
11037 }
11038
11039 // Change free(malloc) into nothing, if the malloc has a single use.
11040 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11041 if (MI->hasOneUse()) {
11042 EraseInstFromFunction(FI);
11043 return EraseInstFromFunction(*MI);
11044 }
Chris Lattner6160e852004-02-28 04:57:37 +000011045
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011046 return 0;
11047}
11048
11049
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011050/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011051static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011052 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011053 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011054 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011055
Devang Patel99db6ad2007-10-18 19:52:32 +000011056 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11057 // Instead of loading constant c string, use corresponding integer value
11058 // directly if string length is small enough.
Bill Wendling0582ae92009-03-13 04:39:26 +000011059 std::string Str;
11060 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11061 unsigned len = Str.length();
Devang Patel99db6ad2007-10-18 19:52:32 +000011062 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11063 unsigned numBits = Ty->getPrimitiveSizeInBits();
11064 // Replace LI with immediate integer store.
11065 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000011066 APInt StrVal(numBits, 0);
11067 APInt SingleChar(numBits, 0);
11068 if (TD->isLittleEndian()) {
11069 for (signed i = len-1; i >= 0; i--) {
Nick Lewycky2ec0dbf2009-02-21 20:50:42 +000011070 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling587c01d2008-02-26 10:53:30 +000011071 StrVal = (StrVal << 8) | SingleChar;
11072 }
11073 } else {
11074 for (unsigned i = 0; i < len; i++) {
Nick Lewycky2ec0dbf2009-02-21 20:50:42 +000011075 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling587c01d2008-02-26 10:53:30 +000011076 StrVal = (StrVal << 8) | SingleChar;
11077 }
11078 // Append NULL at the end.
11079 SingleChar = 0;
11080 StrVal = (StrVal << 8) | SingleChar;
11081 }
11082 Value *NL = ConstantInt::get(StrVal);
11083 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000011084 }
11085 }
11086 }
11087
Mon P Wang6753f952009-02-07 22:19:29 +000011088 const PointerType *DestTy = cast<PointerType>(CI->getType());
11089 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011090 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011091
11092 // If the address spaces don't match, don't eliminate the cast.
11093 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11094 return 0;
11095
Chris Lattnerb89e0712004-07-13 01:49:43 +000011096 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011097
Reid Spencer42230162007-01-22 05:51:25 +000011098 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011099 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011100 // If the source is an array, the code below will not succeed. Check to
11101 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11102 // constants.
11103 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11104 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11105 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011106 Value *Idxs[2];
11107 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11108 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011109 SrcTy = cast<PointerType>(CastOp->getType());
11110 SrcPTy = SrcTy->getElementType();
11111 }
11112
Reid Spencer42230162007-01-22 05:51:25 +000011113 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011114 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011115 // Do not allow turning this into a load of an integer, which is then
11116 // casted to a pointer, this pessimizes pointer analysis a lot.
11117 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011118 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11119 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011120
Chris Lattnerf9527852005-01-31 04:50:46 +000011121 // Okay, we are casting from one integer or pointer type to another of
11122 // the same size. Instead of casting the pointer before the load, cast
11123 // the result of the loaded value.
11124 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11125 CI->getName(),
11126 LI.isVolatile()),LI);
11127 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011128 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011129 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011130 }
11131 }
11132 return 0;
11133}
11134
Chris Lattnerc10aced2004-09-19 18:43:46 +000011135/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011136/// from this value cannot trap. If it is not obviously safe to load from the
11137/// specified pointer, we do a quick local scan of the basic block containing
11138/// ScanFrom, to determine if the address is already accessed.
11139static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011140 // If it is an alloca it is always safe to load from.
11141 if (isa<AllocaInst>(V)) return true;
11142
Duncan Sands46318cd2007-09-19 10:25:38 +000011143 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011144 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011145 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011146 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011147
11148 // Otherwise, be a little bit agressive by scanning the local block where we
11149 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011150 // from/to. If so, the previous load or store would have already trapped,
11151 // so there is no harm doing an extra load (also, CSE will later eliminate
11152 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011153 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11154
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011155 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011156 --BBI;
11157
Chris Lattner2de3fec2008-06-20 05:12:56 +000011158 // If we see a free or a call (which might do a free) the pointer could be
11159 // marked invalid.
Dale Johannesend1c135c2009-03-13 19:23:20 +000011160 if (isa<FreeInst>(BBI) ||
11161 (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
Chris Lattner2de3fec2008-06-20 05:12:56 +000011162 return false;
11163
Chris Lattner8a375202004-09-19 19:18:10 +000011164 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11165 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011166 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011167 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011168 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011169
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011170 }
Chris Lattner8a375202004-09-19 19:18:10 +000011171 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011172}
11173
Chris Lattner833b8a42003-06-26 05:06:25 +000011174Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11175 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011176
Dan Gohman9941f742007-07-20 16:34:21 +000011177 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011178 unsigned KnownAlign =
11179 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011180 if (KnownAlign >
11181 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11182 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011183 LI.setAlignment(KnownAlign);
11184
Chris Lattner37366c12005-05-01 04:24:53 +000011185 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011186 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011187 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011188 return Res;
11189
11190 // None of the following transforms are legal for volatile loads.
11191 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011192
Dan Gohman2276a7b2008-10-15 23:19:35 +000011193 // Do really simple store-to-load forwarding and load CSE, to catch cases
11194 // where there are several consequtive memory accesses to the same location,
11195 // separated by a few arithmetic operations.
11196 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011197 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11198 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011199
Christopher Lambb15147e2007-12-29 07:56:53 +000011200 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11201 const Value *GEPI0 = GEPI->getOperand(0);
11202 // TODO: Consider a target hook for valid address spaces for this xform.
11203 if (isa<ConstantPointerNull>(GEPI0) &&
11204 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011205 // Insert a new store to null instruction before the load to indicate
11206 // that this code is not reachable. We do this instead of inserting
11207 // an unreachable instruction directly because we cannot modify the
11208 // CFG.
11209 new StoreInst(UndefValue::get(LI.getType()),
11210 Constant::getNullValue(Op->getType()), &LI);
11211 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11212 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011213 }
Chris Lattner37366c12005-05-01 04:24:53 +000011214
Chris Lattnere87597f2004-10-16 18:11:37 +000011215 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011216 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011217 // TODO: Consider a target hook for valid address spaces for this xform.
11218 if (isa<UndefValue>(C) || (C->isNullValue() &&
11219 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011220 // Insert a new store to null instruction before the load to indicate that
11221 // this code is not reachable. We do this instead of inserting an
11222 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011223 new StoreInst(UndefValue::get(LI.getType()),
11224 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011225 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011226 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011227
Chris Lattnere87597f2004-10-16 18:11:37 +000011228 // Instcombine load (constant global) into the value loaded.
11229 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sandsab6b2262009-03-20 21:53:29 +000011230 if (GV->isConstant() && !GV->isDeclaration() && !GV->mayBeOverridden())
Chris Lattnere87597f2004-10-16 18:11:37 +000011231 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011232
Chris Lattnere87597f2004-10-16 18:11:37 +000011233 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011234 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011235 if (CE->getOpcode() == Instruction::GetElementPtr) {
11236 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sandsab6b2262009-03-20 21:53:29 +000011237 if (GV->isConstant() && !GV->isDeclaration() &&
11238 !GV->mayBeOverridden())
Chris Lattner363f2a22005-09-26 05:28:06 +000011239 if (Constant *V =
11240 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011241 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011242 if (CE->getOperand(0)->isNullValue()) {
11243 // Insert a new store to null instruction before the load to indicate
11244 // that this code is not reachable. We do this instead of inserting
11245 // an unreachable instruction directly because we cannot modify the
11246 // CFG.
11247 new StoreInst(UndefValue::get(LI.getType()),
11248 Constant::getNullValue(Op->getType()), &LI);
11249 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11250 }
11251
Reid Spencer3da59db2006-11-27 01:05:10 +000011252 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011253 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011254 return Res;
11255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011256 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011257 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011258
11259 // If this load comes from anywhere in a constant global, and if the global
11260 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011261 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sandsab6b2262009-03-20 21:53:29 +000011262 if (GV->isConstant() && GV->hasInitializer() && !GV->mayBeOverridden()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011263 if (GV->getInitializer()->isNullValue())
11264 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11265 else if (isa<UndefValue>(GV->getInitializer()))
11266 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11267 }
11268 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011269
Chris Lattner37366c12005-05-01 04:24:53 +000011270 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011271 // Change select and PHI nodes to select values instead of addresses: this
11272 // helps alias analysis out a lot, allows many others simplifications, and
11273 // exposes redundancy in the code.
11274 //
11275 // Note that we cannot do the transformation unless we know that the
11276 // introduced loads cannot trap! Something like this is valid as long as
11277 // the condition is always false: load (select bool %C, int* null, int* %G),
11278 // but it would not be valid if we transformed it to load from null
11279 // unconditionally.
11280 //
11281 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11282 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011283 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11284 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011285 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011286 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011287 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011288 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011289 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011290 }
11291
Chris Lattner684fe212004-09-23 15:46:00 +000011292 // load (select (cond, null, P)) -> load P
11293 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11294 if (C->isNullValue()) {
11295 LI.setOperand(0, SI->getOperand(2));
11296 return &LI;
11297 }
11298
11299 // load (select (cond, P, null)) -> load P
11300 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11301 if (C->isNullValue()) {
11302 LI.setOperand(0, SI->getOperand(1));
11303 return &LI;
11304 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011305 }
11306 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011307 return 0;
11308}
11309
Reid Spencer55af2b52007-01-19 21:20:31 +000011310/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011311/// when possible. This makes it generally easy to do alias analysis and/or
11312/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011313static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11314 User *CI = cast<User>(SI.getOperand(1));
11315 Value *CastOp = CI->getOperand(0);
11316
11317 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011318 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11319 if (SrcTy == 0) return 0;
11320
11321 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011322
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011323 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11324 return 0;
11325
Chris Lattner3914f722009-01-24 01:00:13 +000011326 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11327 /// to its first element. This allows us to handle things like:
11328 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11329 /// on 32-bit hosts.
11330 SmallVector<Value*, 4> NewGEPIndices;
11331
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011332 // If the source is an array, the code below will not succeed. Check to
11333 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11334 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011335 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11336 // Index through pointer.
11337 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11338 NewGEPIndices.push_back(Zero);
11339
11340 while (1) {
11341 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011342 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011343 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011344 NewGEPIndices.push_back(Zero);
11345 SrcPTy = STy->getElementType(0);
11346 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11347 NewGEPIndices.push_back(Zero);
11348 SrcPTy = ATy->getElementType();
11349 } else {
11350 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011351 }
Chris Lattner3914f722009-01-24 01:00:13 +000011352 }
11353
11354 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11355 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011356
11357 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11358 return 0;
11359
Chris Lattner71759c42009-01-16 20:12:52 +000011360 // If the pointers point into different address spaces or if they point to
11361 // values with different sizes, we can't do the transformation.
11362 if (SrcTy->getAddressSpace() !=
11363 cast<PointerType>(CI->getType())->getAddressSpace() ||
11364 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011365 IC.getTargetData().getTypeSizeInBits(DestPTy))
11366 return 0;
11367
11368 // Okay, we are casting from one integer or pointer type to another of
11369 // the same size. Instead of casting the pointer before
11370 // the store, cast the value to be stored.
11371 Value *NewCast;
11372 Value *SIOp0 = SI.getOperand(0);
11373 Instruction::CastOps opcode = Instruction::BitCast;
11374 const Type* CastSrcTy = SIOp0->getType();
11375 const Type* CastDstTy = SrcPTy;
11376 if (isa<PointerType>(CastDstTy)) {
11377 if (CastSrcTy->isInteger())
11378 opcode = Instruction::IntToPtr;
11379 } else if (isa<IntegerType>(CastDstTy)) {
11380 if (isa<PointerType>(SIOp0->getType()))
11381 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011382 }
Chris Lattner3914f722009-01-24 01:00:13 +000011383
11384 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11385 // emit a GEP to index into its first field.
11386 if (!NewGEPIndices.empty()) {
11387 if (Constant *C = dyn_cast<Constant>(CastOp))
11388 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11389 NewGEPIndices.size());
11390 else
11391 CastOp = IC.InsertNewInstBefore(
11392 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11393 NewGEPIndices.end()), SI);
11394 }
11395
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011396 if (Constant *C = dyn_cast<Constant>(SIOp0))
11397 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11398 else
11399 NewCast = IC.InsertNewInstBefore(
11400 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11401 SI);
11402 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011403}
11404
Chris Lattner4aebaee2008-11-27 08:56:30 +000011405/// equivalentAddressValues - Test if A and B will obviously have the same
11406/// value. This includes recognizing that %t0 and %t1 will have the same
11407/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011408/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011409/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011410/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011411/// %t2 = load i32* %t1
11412///
11413static bool equivalentAddressValues(Value *A, Value *B) {
11414 // Test if the values are trivially equivalent.
11415 if (A == B) return true;
11416
11417 // Test if the values come form identical arithmetic instructions.
11418 if (isa<BinaryOperator>(A) ||
11419 isa<CastInst>(A) ||
11420 isa<PHINode>(A) ||
11421 isa<GetElementPtrInst>(A))
11422 if (Instruction *BI = dyn_cast<Instruction>(B))
11423 if (cast<Instruction>(A)->isIdenticalTo(BI))
11424 return true;
11425
11426 // Otherwise they may not be equivalent.
11427 return false;
11428}
11429
Dale Johannesen4945c652009-03-03 21:26:39 +000011430// If this instruction has two uses, one of which is a llvm.dbg.declare,
11431// return the llvm.dbg.declare.
11432DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11433 if (!V->hasNUses(2))
11434 return 0;
11435 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11436 UI != E; ++UI) {
11437 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11438 return DI;
11439 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11440 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11441 return DI;
11442 }
11443 }
11444 return 0;
11445}
11446
Chris Lattner2f503e62005-01-31 05:36:43 +000011447Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11448 Value *Val = SI.getOperand(0);
11449 Value *Ptr = SI.getOperand(1);
11450
11451 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011452 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011453 ++NumCombined;
11454 return 0;
11455 }
Chris Lattner836692d2007-01-15 06:51:56 +000011456
11457 // If the RHS is an alloca with a single use, zapify the store, making the
11458 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011459 // If the RHS is an alloca with a two uses, the other one being a
11460 // llvm.dbg.declare, zapify the store and the declare, making the
11461 // alloca dead. We must do this to prevent declare's from affecting
11462 // codegen.
11463 if (!SI.isVolatile()) {
11464 if (Ptr->hasOneUse()) {
11465 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011466 EraseInstFromFunction(SI);
11467 ++NumCombined;
11468 return 0;
11469 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011470 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11471 if (isa<AllocaInst>(GEP->getOperand(0))) {
11472 if (GEP->getOperand(0)->hasOneUse()) {
11473 EraseInstFromFunction(SI);
11474 ++NumCombined;
11475 return 0;
11476 }
11477 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11478 EraseInstFromFunction(*DI);
11479 EraseInstFromFunction(SI);
11480 ++NumCombined;
11481 return 0;
11482 }
11483 }
11484 }
11485 }
11486 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11487 EraseInstFromFunction(*DI);
11488 EraseInstFromFunction(SI);
11489 ++NumCombined;
11490 return 0;
11491 }
Chris Lattner836692d2007-01-15 06:51:56 +000011492 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011493
Dan Gohman9941f742007-07-20 16:34:21 +000011494 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011495 unsigned KnownAlign =
11496 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011497 if (KnownAlign >
11498 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11499 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011500 SI.setAlignment(KnownAlign);
11501
Dale Johannesenacb51a32009-03-03 01:43:03 +000011502 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011503 // stores to the same location, separated by a few arithmetic operations. This
11504 // situation often occurs with bitfield accesses.
11505 BasicBlock::iterator BBI = &SI;
11506 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11507 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011508 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011509 // Don't count debug info directives, lest they affect codegen,
11510 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11511 // It is necessary for correctness to skip those that feed into a
11512 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011513 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011514 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011515 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011516 continue;
11517 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011518
11519 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11520 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011521 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11522 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011523 ++NumDeadStore;
11524 ++BBI;
11525 EraseInstFromFunction(*PrevSI);
11526 continue;
11527 }
11528 break;
11529 }
11530
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011531 // If this is a load, we have to stop. However, if the loaded value is from
11532 // the pointer we're loading and is producing the pointer we're storing,
11533 // then *this* store is dead (X = load P; store X -> P).
11534 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011535 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11536 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011537 EraseInstFromFunction(SI);
11538 ++NumCombined;
11539 return 0;
11540 }
11541 // Otherwise, this is a load from some other location. Stores before it
11542 // may not be dead.
11543 break;
11544 }
11545
Chris Lattner9ca96412006-02-08 03:25:32 +000011546 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011547 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011548 break;
11549 }
11550
11551
11552 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011553
11554 // store X, null -> turns into 'unreachable' in SimplifyCFG
11555 if (isa<ConstantPointerNull>(Ptr)) {
11556 if (!isa<UndefValue>(Val)) {
11557 SI.setOperand(0, UndefValue::get(Val->getType()));
11558 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011559 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011560 ++NumCombined;
11561 }
11562 return 0; // Do not modify these!
11563 }
11564
11565 // store undef, Ptr -> noop
11566 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011567 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011568 ++NumCombined;
11569 return 0;
11570 }
11571
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011572 // If the pointer destination is a cast, see if we can fold the cast into the
11573 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011574 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011575 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11576 return Res;
11577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011578 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011579 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11580 return Res;
11581
Chris Lattner408902b2005-09-12 23:23:25 +000011582
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011583 // If this store is the last instruction in the basic block (possibly
11584 // excepting debug info instructions and the pointer bitcasts that feed
11585 // into them), and if the block ends with an unconditional branch, try
11586 // to move it to the successor block.
11587 BBI = &SI;
11588 do {
11589 ++BBI;
11590 } while (isa<DbgInfoIntrinsic>(BBI) ||
11591 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011592 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011593 if (BI->isUnconditional())
11594 if (SimplifyStoreAtEndOfBlock(SI))
11595 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011596
Chris Lattner2f503e62005-01-31 05:36:43 +000011597 return 0;
11598}
11599
Chris Lattner3284d1f2007-04-15 00:07:55 +000011600/// SimplifyStoreAtEndOfBlock - Turn things like:
11601/// if () { *P = v1; } else { *P = v2 }
11602/// into a phi node with a store in the successor.
11603///
Chris Lattner31755a02007-04-15 01:02:18 +000011604/// Simplify things like:
11605/// *P = v1; if () { *P = v2; }
11606/// into a phi node with a store in the successor.
11607///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011608bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11609 BasicBlock *StoreBB = SI.getParent();
11610
11611 // Check to see if the successor block has exactly two incoming edges. If
11612 // so, see if the other predecessor contains a store to the same location.
11613 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011614 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011615
11616 // Determine whether Dest has exactly two predecessors and, if so, compute
11617 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011618 pred_iterator PI = pred_begin(DestBB);
11619 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011620 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011621 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011622 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011623 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011624 return false;
11625
11626 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011627 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011628 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011629 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011630 }
Chris Lattner31755a02007-04-15 01:02:18 +000011631 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011632 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011633
11634 // Bail out if all the relevant blocks aren't distinct (this can happen,
11635 // for example, if SI is in an infinite loop)
11636 if (StoreBB == DestBB || OtherBB == DestBB)
11637 return false;
11638
Chris Lattner31755a02007-04-15 01:02:18 +000011639 // Verify that the other block ends in a branch and is not otherwise empty.
11640 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011641 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011642 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011643 return false;
11644
Chris Lattner31755a02007-04-15 01:02:18 +000011645 // If the other block ends in an unconditional branch, check for the 'if then
11646 // else' case. there is an instruction before the branch.
11647 StoreInst *OtherStore = 0;
11648 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011649 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011650 // Skip over debugging info.
11651 while (isa<DbgInfoIntrinsic>(BBI) ||
11652 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11653 if (BBI==OtherBB->begin())
11654 return false;
11655 --BBI;
11656 }
11657 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011658 OtherStore = dyn_cast<StoreInst>(BBI);
11659 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11660 return false;
11661 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011662 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011663 // destinations is StoreBB, then we have the if/then case.
11664 if (OtherBr->getSuccessor(0) != StoreBB &&
11665 OtherBr->getSuccessor(1) != StoreBB)
11666 return false;
11667
11668 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011669 // if/then triangle. See if there is a store to the same ptr as SI that
11670 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011671 for (;; --BBI) {
11672 // Check to see if we find the matching store.
11673 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11674 if (OtherStore->getOperand(1) != SI.getOperand(1))
11675 return false;
11676 break;
11677 }
Eli Friedman6903a242008-06-13 22:02:12 +000011678 // If we find something that may be using or overwriting the stored
11679 // value, or if we run out of instructions, we can't do the xform.
11680 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011681 BBI == OtherBB->begin())
11682 return false;
11683 }
11684
11685 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011686 // make sure nothing reads or overwrites the stored value in
11687 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011688 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11689 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011690 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011691 return false;
11692 }
11693 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011694
Chris Lattner31755a02007-04-15 01:02:18 +000011695 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011696 Value *MergedVal = OtherStore->getOperand(0);
11697 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011698 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011699 PN->reserveOperandSpace(2);
11700 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011701 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11702 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011703 }
11704
11705 // Advance to a place where it is safe to insert the new store and
11706 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011707 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011708 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11709 OtherStore->isVolatile()), *BBI);
11710
11711 // Nuke the old stores.
11712 EraseInstFromFunction(SI);
11713 EraseInstFromFunction(*OtherStore);
11714 ++NumCombined;
11715 return true;
11716}
11717
Chris Lattner2f503e62005-01-31 05:36:43 +000011718
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011719Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11720 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011721 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011722 BasicBlock *TrueDest;
11723 BasicBlock *FalseDest;
11724 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11725 !isa<Constant>(X)) {
11726 // Swap Destinations and condition...
11727 BI.setCondition(X);
11728 BI.setSuccessor(0, FalseDest);
11729 BI.setSuccessor(1, TrueDest);
11730 return &BI;
11731 }
11732
Reid Spencere4d87aa2006-12-23 06:05:41 +000011733 // Cannonicalize fcmp_one -> fcmp_oeq
11734 FCmpInst::Predicate FPred; Value *Y;
11735 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11736 TrueDest, FalseDest)))
11737 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11738 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11739 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011740 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011741 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11742 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011743 // Swap Destinations and condition...
11744 BI.setCondition(NewSCC);
11745 BI.setSuccessor(0, FalseDest);
11746 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011747 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011748 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011749 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011750 return &BI;
11751 }
11752
11753 // Cannonicalize icmp_ne -> icmp_eq
11754 ICmpInst::Predicate IPred;
11755 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11756 TrueDest, FalseDest)))
11757 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11758 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11759 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11760 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011761 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011762 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11763 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011764 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011765 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011766 BI.setSuccessor(0, FalseDest);
11767 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011768 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011769 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011770 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011771 return &BI;
11772 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011773
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011774 return 0;
11775}
Chris Lattner0864acf2002-11-04 16:18:53 +000011776
Chris Lattner46238a62004-07-03 00:26:11 +000011777Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11778 Value *Cond = SI.getCondition();
11779 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11780 if (I->getOpcode() == Instruction::Add)
11781 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11782 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11783 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011784 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011785 AddRHS));
11786 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011787 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011788 return &SI;
11789 }
11790 }
11791 return 0;
11792}
11793
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011794Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011795 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011796
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011797 if (!EV.hasIndices())
11798 return ReplaceInstUsesWith(EV, Agg);
11799
11800 if (Constant *C = dyn_cast<Constant>(Agg)) {
11801 if (isa<UndefValue>(C))
11802 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11803
11804 if (isa<ConstantAggregateZero>(C))
11805 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11806
11807 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11808 // Extract the element indexed by the first index out of the constant
11809 Value *V = C->getOperand(*EV.idx_begin());
11810 if (EV.getNumIndices() > 1)
11811 // Extract the remaining indices out of the constant indexed by the
11812 // first index
11813 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11814 else
11815 return ReplaceInstUsesWith(EV, V);
11816 }
11817 return 0; // Can't handle other constants
11818 }
11819 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11820 // We're extracting from an insertvalue instruction, compare the indices
11821 const unsigned *exti, *exte, *insi, *inse;
11822 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11823 exte = EV.idx_end(), inse = IV->idx_end();
11824 exti != exte && insi != inse;
11825 ++exti, ++insi) {
11826 if (*insi != *exti)
11827 // The insert and extract both reference distinctly different elements.
11828 // This means the extract is not influenced by the insert, and we can
11829 // replace the aggregate operand of the extract with the aggregate
11830 // operand of the insert. i.e., replace
11831 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11832 // %E = extractvalue { i32, { i32 } } %I, 0
11833 // with
11834 // %E = extractvalue { i32, { i32 } } %A, 0
11835 return ExtractValueInst::Create(IV->getAggregateOperand(),
11836 EV.idx_begin(), EV.idx_end());
11837 }
11838 if (exti == exte && insi == inse)
11839 // Both iterators are at the end: Index lists are identical. Replace
11840 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11841 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11842 // with "i32 42"
11843 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11844 if (exti == exte) {
11845 // The extract list is a prefix of the insert list. i.e. replace
11846 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11847 // %E = extractvalue { i32, { i32 } } %I, 1
11848 // with
11849 // %X = extractvalue { i32, { i32 } } %A, 1
11850 // %E = insertvalue { i32 } %X, i32 42, 0
11851 // by switching the order of the insert and extract (though the
11852 // insertvalue should be left in, since it may have other uses).
11853 Value *NewEV = InsertNewInstBefore(
11854 ExtractValueInst::Create(IV->getAggregateOperand(),
11855 EV.idx_begin(), EV.idx_end()),
11856 EV);
11857 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11858 insi, inse);
11859 }
11860 if (insi == inse)
11861 // The insert list is a prefix of the extract list
11862 // We can simply remove the common indices from the extract and make it
11863 // operate on the inserted value instead of the insertvalue result.
11864 // i.e., replace
11865 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11866 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11867 // with
11868 // %E extractvalue { i32 } { i32 42 }, 0
11869 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11870 exti, exte);
11871 }
11872 // Can't simplify extracts from other values. Note that nested extracts are
11873 // already simplified implicitely by the above (extract ( extract (insert) )
11874 // will be translated into extract ( insert ( extract ) ) first and then just
11875 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011876 return 0;
11877}
11878
Chris Lattner220b0cf2006-03-05 00:22:33 +000011879/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11880/// is to leave as a vector operation.
11881static bool CheapToScalarize(Value *V, bool isConstant) {
11882 if (isa<ConstantAggregateZero>(V))
11883 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011884 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011885 if (isConstant) return true;
11886 // If all elts are the same, we can extract.
11887 Constant *Op0 = C->getOperand(0);
11888 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11889 if (C->getOperand(i) != Op0)
11890 return false;
11891 return true;
11892 }
11893 Instruction *I = dyn_cast<Instruction>(V);
11894 if (!I) return false;
11895
11896 // Insert element gets simplified to the inserted element or is deleted if
11897 // this is constant idx extract element and its a constant idx insertelt.
11898 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11899 isa<ConstantInt>(I->getOperand(2)))
11900 return true;
11901 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11902 return true;
11903 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11904 if (BO->hasOneUse() &&
11905 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11906 CheapToScalarize(BO->getOperand(1), isConstant)))
11907 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011908 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11909 if (CI->hasOneUse() &&
11910 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11911 CheapToScalarize(CI->getOperand(1), isConstant)))
11912 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011913
11914 return false;
11915}
11916
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011917/// Read and decode a shufflevector mask.
11918///
11919/// It turns undef elements into values that are larger than the number of
11920/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011921static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11922 unsigned NElts = SVI->getType()->getNumElements();
11923 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11924 return std::vector<unsigned>(NElts, 0);
11925 if (isa<UndefValue>(SVI->getOperand(2)))
11926 return std::vector<unsigned>(NElts, 2*NElts);
11927
11928 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011929 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011930 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11931 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011932 Result.push_back(NElts*2); // undef -> 8
11933 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011934 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011935 return Result;
11936}
11937
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011938/// FindScalarElement - Given a vector and an element number, see if the scalar
11939/// value is already around as a register, for example if it were inserted then
11940/// extracted from the vector.
11941static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011942 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11943 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011944 unsigned Width = PTy->getNumElements();
11945 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011946 return UndefValue::get(PTy->getElementType());
11947
11948 if (isa<UndefValue>(V))
11949 return UndefValue::get(PTy->getElementType());
11950 else if (isa<ConstantAggregateZero>(V))
11951 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011952 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011953 return CP->getOperand(EltNo);
11954 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11955 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011956 if (!isa<ConstantInt>(III->getOperand(2)))
11957 return 0;
11958 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011959
11960 // If this is an insert to the element we are looking for, return the
11961 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011962 if (EltNo == IIElt)
11963 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011964
11965 // Otherwise, the insertelement doesn't modify the value, recurse on its
11966 // vector input.
11967 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011968 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011969 unsigned LHSWidth =
11970 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011971 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011972 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011973 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011974 else if (InEl < LHSWidth*2)
11975 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011976 else
11977 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011978 }
11979
11980 // Otherwise, we don't know.
11981 return 0;
11982}
11983
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011984Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011985 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011986 if (isa<UndefValue>(EI.getOperand(0)))
11987 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11988
Dan Gohman07a96762007-07-16 14:29:03 +000011989 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011990 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11991 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11992
Reid Spencer9d6565a2007-02-15 02:26:10 +000011993 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011994 // If vector val is constant with all elements the same, replace EI with
11995 // that element. When the elements are not identical, we cannot replace yet
11996 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011997 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011998 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011999 if (C->getOperand(i) != op0) {
12000 op0 = 0;
12001 break;
12002 }
12003 if (op0)
12004 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012005 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012006
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012007 // If extracting a specified index from the vector, see if we can recursively
12008 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012009 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012010 unsigned IndexVal = IdxC->getZExtValue();
12011 unsigned VectorWidth =
12012 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12013
12014 // If this is extracting an invalid index, turn this into undef, to avoid
12015 // crashing the code below.
12016 if (IndexVal >= VectorWidth)
12017 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12018
Chris Lattner867b99f2006-10-05 06:55:50 +000012019 // This instruction only demands the single element from the input vector.
12020 // If the input vector has a single use, simplify it based on this use
12021 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012022 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012023 APInt UndefElts(VectorWidth, 0);
12024 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012025 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012026 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012027 EI.setOperand(0, V);
12028 return &EI;
12029 }
12030 }
12031
Reid Spencerb83eb642006-10-20 07:07:24 +000012032 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012033 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012034
12035 // If the this extractelement is directly using a bitcast from a vector of
12036 // the same number of elements, see if we can find the source element from
12037 // it. In this case, we will end up needing to bitcast the scalars.
12038 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12039 if (const VectorType *VT =
12040 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12041 if (VT->getNumElements() == VectorWidth)
12042 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12043 return new BitCastInst(Elt, EI.getType());
12044 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012045 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012046
Chris Lattner73fa49d2006-05-25 22:53:38 +000012047 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012048 if (I->hasOneUse()) {
12049 // Push extractelement into predecessor operation if legal and
12050 // profitable to do so
12051 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012052 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12053 if (CheapToScalarize(BO, isConstantElt)) {
12054 ExtractElementInst *newEI0 =
12055 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12056 EI.getName()+".lhs");
12057 ExtractElementInst *newEI1 =
12058 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12059 EI.getName()+".rhs");
12060 InsertNewInstBefore(newEI0, EI);
12061 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012062 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012063 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012064 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012065 unsigned AS =
12066 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012067 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12068 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012069 GetElementPtrInst *GEP =
12070 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012071 InsertNewInstBefore(GEP, EI);
12072 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012073 }
12074 }
12075 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12076 // Extracting the inserted element?
12077 if (IE->getOperand(2) == EI.getOperand(1))
12078 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12079 // If the inserted and extracted elements are constants, they must not
12080 // be the same value, extract from the pre-inserted value instead.
12081 if (isa<Constant>(IE->getOperand(2)) &&
12082 isa<Constant>(EI.getOperand(1))) {
12083 AddUsesToWorkList(EI);
12084 EI.setOperand(0, IE->getOperand(0));
12085 return &EI;
12086 }
12087 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12088 // If this is extracting an element from a shufflevector, figure out where
12089 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012090 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12091 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012092 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012093 unsigned LHSWidth =
12094 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12095
12096 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012097 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012098 else if (SrcIdx < LHSWidth*2) {
12099 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012100 Src = SVI->getOperand(1);
12101 } else {
12102 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012103 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012104 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012105 }
12106 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012107 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012108 return 0;
12109}
12110
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012111/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12112/// elements from either LHS or RHS, return the shuffle mask and true.
12113/// Otherwise, return false.
12114static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12115 std::vector<Constant*> &Mask) {
12116 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12117 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012118 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012119
12120 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012121 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012122 return true;
12123 } else if (V == LHS) {
12124 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012125 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012126 return true;
12127 } else if (V == RHS) {
12128 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012129 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012130 return true;
12131 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12132 // If this is an insert of an extract from some other vector, include it.
12133 Value *VecOp = IEI->getOperand(0);
12134 Value *ScalarOp = IEI->getOperand(1);
12135 Value *IdxOp = IEI->getOperand(2);
12136
Chris Lattnerd929f062006-04-27 21:14:21 +000012137 if (!isa<ConstantInt>(IdxOp))
12138 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012139 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012140
12141 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12142 // Okay, we can handle this if the vector we are insertinting into is
12143 // transitively ok.
12144 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12145 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012146 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012147 return true;
12148 }
12149 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12150 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012151 EI->getOperand(0)->getType() == V->getType()) {
12152 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012153 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012154
12155 // This must be extracting from either LHS or RHS.
12156 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12157 // Okay, we can handle this if the vector we are insertinting into is
12158 // transitively ok.
12159 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12160 // If so, update the mask to reflect the inserted value.
12161 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012162 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012163 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012164 } else {
12165 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012166 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012167 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012168
12169 }
12170 return true;
12171 }
12172 }
12173 }
12174 }
12175 }
12176 // TODO: Handle shufflevector here!
12177
12178 return false;
12179}
12180
12181/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12182/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12183/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012184static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012185 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012186 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012187 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012188 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012189 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012190
12191 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012192 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012193 return V;
12194 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012195 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012196 return V;
12197 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12198 // If this is an insert of an extract from some other vector, include it.
12199 Value *VecOp = IEI->getOperand(0);
12200 Value *ScalarOp = IEI->getOperand(1);
12201 Value *IdxOp = IEI->getOperand(2);
12202
12203 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12204 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12205 EI->getOperand(0)->getType() == V->getType()) {
12206 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012207 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12208 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012209
12210 // Either the extracted from or inserted into vector must be RHSVec,
12211 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012212 if (EI->getOperand(0) == RHS || RHS == 0) {
12213 RHS = EI->getOperand(0);
12214 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012215 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012216 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012217 return V;
12218 }
12219
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012220 if (VecOp == RHS) {
12221 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012222 // Everything but the extracted element is replaced with the RHS.
12223 for (unsigned i = 0; i != NumElts; ++i) {
12224 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012225 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012226 }
12227 return V;
12228 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012229
12230 // If this insertelement is a chain that comes from exactly these two
12231 // vectors, return the vector and the effective shuffle.
12232 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12233 return EI->getOperand(0);
12234
Chris Lattnerefb47352006-04-15 01:39:45 +000012235 }
12236 }
12237 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012238 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012239
12240 // Otherwise, can't do anything fancy. Return an identity vector.
12241 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012242 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012243 return V;
12244}
12245
12246Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12247 Value *VecOp = IE.getOperand(0);
12248 Value *ScalarOp = IE.getOperand(1);
12249 Value *IdxOp = IE.getOperand(2);
12250
Chris Lattner599ded12007-04-09 01:11:16 +000012251 // Inserting an undef or into an undefined place, remove this.
12252 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12253 ReplaceInstUsesWith(IE, VecOp);
12254
Chris Lattnerefb47352006-04-15 01:39:45 +000012255 // If the inserted element was extracted from some other vector, and if the
12256 // indexes are constant, try to turn this into a shufflevector operation.
12257 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12258 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12259 EI->getOperand(0)->getType() == IE.getType()) {
12260 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012261 unsigned ExtractedIdx =
12262 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012263 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012264
12265 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12266 return ReplaceInstUsesWith(IE, VecOp);
12267
12268 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12269 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12270
12271 // If we are extracting a value from a vector, then inserting it right
12272 // back into the same place, just use the input vector.
12273 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12274 return ReplaceInstUsesWith(IE, VecOp);
12275
12276 // We could theoretically do this for ANY input. However, doing so could
12277 // turn chains of insertelement instructions into a chain of shufflevector
12278 // instructions, and right now we do not merge shufflevectors. As such,
12279 // only do this in a situation where it is clear that there is benefit.
12280 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12281 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12282 // the values of VecOp, except then one read from EIOp0.
12283 // Build a new shuffle mask.
12284 std::vector<Constant*> Mask;
12285 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012286 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012287 else {
12288 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012289 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012290 NumVectorElts));
12291 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012292 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012293 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012294 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012295 }
12296
12297 // If this insertelement isn't used by some other insertelement, turn it
12298 // (and any insertelements it points to), into one big shuffle.
12299 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12300 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012301 Value *RHS = 0;
12302 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12303 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12304 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012305 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012306 }
12307 }
12308 }
12309
12310 return 0;
12311}
12312
12313
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012314Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12315 Value *LHS = SVI.getOperand(0);
12316 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012317 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012318
12319 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012320
Chris Lattner867b99f2006-10-05 06:55:50 +000012321 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012322 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012323 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012324
Dan Gohman488fbfc2008-09-09 18:11:14 +000012325 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012326
12327 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12328 return 0;
12329
Evan Cheng388df622009-02-03 10:05:09 +000012330 APInt UndefElts(VWidth, 0);
12331 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12332 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012333 LHS = SVI.getOperand(0);
12334 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012335 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012336 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012337
Chris Lattner863bcff2006-05-25 23:48:38 +000012338 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12339 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12340 if (LHS == RHS || isa<UndefValue>(LHS)) {
12341 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012342 // shuffle(undef,undef,mask) -> undef.
12343 return ReplaceInstUsesWith(SVI, LHS);
12344 }
12345
Chris Lattner863bcff2006-05-25 23:48:38 +000012346 // Remap any references to RHS to use LHS.
12347 std::vector<Constant*> Elts;
12348 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012349 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012350 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012351 else {
12352 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012353 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012354 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012355 Elts.push_back(UndefValue::get(Type::Int32Ty));
12356 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012357 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012358 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12359 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012360 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012361 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012362 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012363 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012364 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012365 LHS = SVI.getOperand(0);
12366 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012367 MadeChange = true;
12368 }
12369
Chris Lattner7b2e27922006-05-26 00:29:06 +000012370 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012371 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012372
Chris Lattner863bcff2006-05-25 23:48:38 +000012373 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12374 if (Mask[i] >= e*2) continue; // Ignore undef values.
12375 // Is this an identity shuffle of the LHS value?
12376 isLHSID &= (Mask[i] == i);
12377
12378 // Is this an identity shuffle of the RHS value?
12379 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012380 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012381
Chris Lattner863bcff2006-05-25 23:48:38 +000012382 // Eliminate identity shuffles.
12383 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12384 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012385
Chris Lattner7b2e27922006-05-26 00:29:06 +000012386 // If the LHS is a shufflevector itself, see if we can combine it with this
12387 // one without producing an unusual shuffle. Here we are really conservative:
12388 // we are absolutely afraid of producing a shuffle mask not in the input
12389 // program, because the code gen may not be smart enough to turn a merged
12390 // shuffle into two specific shuffles: it may produce worse code. As such,
12391 // we only merge two shuffles if the result is one of the two input shuffle
12392 // masks. In this case, merging the shuffles just removes one instruction,
12393 // which we know is safe. This is good for things like turning:
12394 // (splat(splat)) -> splat.
12395 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12396 if (isa<UndefValue>(RHS)) {
12397 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12398
12399 std::vector<unsigned> NewMask;
12400 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12401 if (Mask[i] >= 2*e)
12402 NewMask.push_back(2*e);
12403 else
12404 NewMask.push_back(LHSMask[Mask[i]]);
12405
12406 // If the result mask is equal to the src shuffle or this shuffle mask, do
12407 // the replacement.
12408 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012409 unsigned LHSInNElts =
12410 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012411 std::vector<Constant*> Elts;
12412 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012413 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012414 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012415 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012416 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012417 }
12418 }
12419 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12420 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012421 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012422 }
12423 }
12424 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012425
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012426 return MadeChange ? &SVI : 0;
12427}
12428
12429
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012430
Chris Lattnerea1c4542004-12-08 23:43:58 +000012431
12432/// TryToSinkInstruction - Try to move the specified instruction from its
12433/// current block into the beginning of DestBlock, which can only happen if it's
12434/// safe to move the instruction past all of the instructions between it and the
12435/// end of its block.
12436static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12437 assert(I->hasOneUse() && "Invariants didn't hold!");
12438
Chris Lattner108e9022005-10-27 17:13:11 +000012439 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012440 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12441 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012442
Chris Lattnerea1c4542004-12-08 23:43:58 +000012443 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012444 if (isa<AllocaInst>(I) && I->getParent() ==
12445 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012446 return false;
12447
Chris Lattner96a52a62004-12-09 07:14:34 +000012448 // We can only sink load instructions if there is nothing between the load and
12449 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012450 if (I->mayReadFromMemory()) {
12451 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012452 Scan != E; ++Scan)
12453 if (Scan->mayWriteToMemory())
12454 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012455 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012456
Dan Gohman02dea8b2008-05-23 21:05:58 +000012457 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012458
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012459 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012460 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012461 ++NumSunkInst;
12462 return true;
12463}
12464
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012465
12466/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12467/// all reachable code to the worklist.
12468///
12469/// This has a couple of tricks to make the code faster and more powerful. In
12470/// particular, we constant fold and DCE instructions as we go, to avoid adding
12471/// them to the worklist (this significantly speeds up instcombine on code where
12472/// many instructions are dead or constant). Additionally, if we find a branch
12473/// whose condition is a known constant, we only visit the reachable successors.
12474///
12475static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012476 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012477 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012478 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012479 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012480 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012481
Chris Lattner2c7718a2007-03-23 19:17:18 +000012482 while (!Worklist.empty()) {
12483 BB = Worklist.back();
12484 Worklist.pop_back();
12485
12486 // We have now visited this block! If we've already been here, ignore it.
12487 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012488
12489 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012490 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12491 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012492
Chris Lattner2c7718a2007-03-23 19:17:18 +000012493 // DCE instruction if trivially dead.
12494 if (isInstructionTriviallyDead(Inst)) {
12495 ++NumDeadInst;
12496 DOUT << "IC: DCE: " << *Inst;
12497 Inst->eraseFromParent();
12498 continue;
12499 }
12500
12501 // ConstantProp instruction if trivially constant.
12502 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12503 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12504 Inst->replaceAllUsesWith(C);
12505 ++NumConstProp;
12506 Inst->eraseFromParent();
12507 continue;
12508 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012509
Devang Patel7fe1dec2008-11-19 18:56:50 +000012510 // If there are two consecutive llvm.dbg.stoppoint calls then
12511 // it is likely that the optimizer deleted code in between these
12512 // two intrinsics.
12513 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12514 if (DBI_Next) {
12515 if (DBI_Prev
12516 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12517 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12518 IC.RemoveFromWorkList(DBI_Prev);
12519 DBI_Prev->eraseFromParent();
12520 }
12521 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012522 } else {
12523 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012524 }
12525
Chris Lattner2c7718a2007-03-23 19:17:18 +000012526 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012527 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012528
12529 // Recursively visit successors. If this is a branch or switch on a
12530 // constant, only visit the reachable successor.
12531 TerminatorInst *TI = BB->getTerminator();
12532 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12533 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12534 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012535 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012536 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012537 continue;
12538 }
12539 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12540 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12541 // See if this is an explicit destination.
12542 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12543 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012544 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012545 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012546 continue;
12547 }
12548
12549 // Otherwise it is the default destination.
12550 Worklist.push_back(SI->getSuccessor(0));
12551 continue;
12552 }
12553 }
12554
12555 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12556 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012557 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012558}
12559
Chris Lattnerec9c3582007-03-03 02:04:50 +000012560bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012561 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012562 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012563
12564 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12565 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012566
Chris Lattnerb3d59702005-07-07 20:40:38 +000012567 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012568 // Do a depth-first traversal of the function, populate the worklist with
12569 // the reachable instructions. Ignore blocks that are not reachable. Keep
12570 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012571 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012572 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012573
Chris Lattnerb3d59702005-07-07 20:40:38 +000012574 // Do a quick scan over the function. If we find any blocks that are
12575 // unreachable, remove any instructions inside of them. This prevents
12576 // the instcombine code from having to deal with some bad special cases.
12577 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12578 if (!Visited.count(BB)) {
12579 Instruction *Term = BB->getTerminator();
12580 while (Term != BB->begin()) { // Remove instrs bottom-up
12581 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012582
Bill Wendlingb7427032006-11-26 09:46:52 +000012583 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012584 // A debug intrinsic shouldn't force another iteration if we weren't
12585 // going to do one without it.
12586 if (!isa<DbgInfoIntrinsic>(I)) {
12587 ++NumDeadInst;
12588 Changed = true;
12589 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012590 if (!I->use_empty())
12591 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12592 I->eraseFromParent();
12593 }
12594 }
12595 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012596
Chris Lattnerdbab3862007-03-02 21:28:56 +000012597 while (!Worklist.empty()) {
12598 Instruction *I = RemoveOneFromWorkList();
12599 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012600
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012601 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012602 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012603 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012604 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012605 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012606 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012607
Bill Wendlingb7427032006-11-26 09:46:52 +000012608 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012609
12610 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012611 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012612 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012613 continue;
12614 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012615
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012616 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012617 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012618 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012619
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012620 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012621 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012622 ReplaceInstUsesWith(*I, C);
12623
Chris Lattner62b14df2002-09-02 04:59:56 +000012624 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012625 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012626 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012627 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012628 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012629 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012630
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012631 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12632 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012633 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12634 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012635 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012636 if (NewC != CE) {
12637 i->set(NewC);
12638 Changed = true;
12639 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012640 }
12641
Chris Lattnerea1c4542004-12-08 23:43:58 +000012642 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012643 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012644 BasicBlock *BB = I->getParent();
12645 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12646 if (UserParent != BB) {
12647 bool UserIsSuccessor = false;
12648 // See if the user is one of our successors.
12649 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12650 if (*SI == UserParent) {
12651 UserIsSuccessor = true;
12652 break;
12653 }
12654
12655 // If the user is one of our immediate successors, and if that successor
12656 // only has us as a predecessors (we'd have to split the critical edge
12657 // otherwise), we can keep going.
12658 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12659 next(pred_begin(UserParent)) == pred_end(UserParent))
12660 // Okay, the CFG is simple enough, try to sink this instruction.
12661 Changed |= TryToSinkInstruction(I, UserParent);
12662 }
12663 }
12664
Chris Lattner8a2a3112001-12-14 16:52:21 +000012665 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012666#ifndef NDEBUG
12667 std::string OrigI;
12668#endif
12669 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012670 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012671 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012672 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012673 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012674 DOUT << "IC: Old = " << *I
12675 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012676
Chris Lattnerf523d062004-06-09 05:08:07 +000012677 // Everything uses the new instruction now.
12678 I->replaceAllUsesWith(Result);
12679
12680 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012681 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012682 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012683
Chris Lattner6934a042007-02-11 01:23:03 +000012684 // Move the name to the new instruction first.
12685 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012686
12687 // Insert the new instruction into the basic block...
12688 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012689 BasicBlock::iterator InsertPos = I;
12690
12691 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12692 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12693 ++InsertPos;
12694
12695 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012696
Chris Lattner00d51312004-05-01 23:27:23 +000012697 // Make sure that we reprocess all operands now that we reduced their
12698 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012699 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012700
Chris Lattnerf523d062004-06-09 05:08:07 +000012701 // Instructions can end up on the worklist more than once. Make sure
12702 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012703 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012704
12705 // Erase the old instruction.
12706 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012707 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012708#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012709 DOUT << "IC: Mod = " << OrigI
12710 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012711#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012712
Chris Lattner90ac28c2002-08-02 19:29:35 +000012713 // If the instruction was modified, it's possible that it is now dead.
12714 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012715 if (isInstructionTriviallyDead(I)) {
12716 // Make sure we process all operands now that we are reducing their
12717 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012718 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012719
Chris Lattner00d51312004-05-01 23:27:23 +000012720 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012721 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012722 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012723 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012724 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012725 AddToWorkList(I);
12726 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012727 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012728 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012729 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012730 }
12731 }
12732
Chris Lattnerec9c3582007-03-03 02:04:50 +000012733 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012734
12735 // Do an explicit clear, this shrinks the map if needed.
12736 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012737 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012738}
12739
Chris Lattnerec9c3582007-03-03 02:04:50 +000012740
12741bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012742 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12743
Chris Lattnerec9c3582007-03-03 02:04:50 +000012744 bool EverMadeChange = false;
12745
12746 // Iterate while there is work to do.
12747 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012748 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012749 EverMadeChange = true;
12750 return EverMadeChange;
12751}
12752
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012753FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012754 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012755}