blob: adab875f953c7218cbf737a677ae7a669206a988 [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);
Chris Lattnera0e69692009-03-24 18:35:40 +0000221 Instruction *visitPtrToInt(PtrToIntInst &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);
Evan Chengde621922009-03-31 20:42:45 +0000226 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000227 Instruction *visitSelectInst(SelectInst &SI);
228 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000229 Instruction *visitCallInst(CallInst &CI);
230 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000231 Instruction *visitPHINode(PHINode &PN);
232 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000233 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000234 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000235 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000236 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000237 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000238 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000239 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000240 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000241 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000242 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000243
244 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000245 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000246
Chris Lattner9fe38862003-06-19 17:00:31 +0000247 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000248 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000249 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000250 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000251 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
252 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000253 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000254 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
255
Chris Lattner9fe38862003-06-19 17:00:31 +0000256
Chris Lattner28977af2004-04-05 01:30:19 +0000257 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000258 // InsertNewInstBefore - insert an instruction New before instruction Old
259 // in the program. Add the new instruction to the worklist.
260 //
Chris Lattner955f3312004-09-28 21:48:02 +0000261 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000262 assert(New && New->getParent() == 0 &&
263 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000264 BasicBlock *BB = Old.getParent();
265 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000266 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000267 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000268 }
269
Chris Lattner0c967662004-09-24 15:21:34 +0000270 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
271 /// This also adds the cast to the worklist. Finally, this returns the
272 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000273 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
274 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000275 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000276
Chris Lattnere2ed0572006-04-06 19:19:17 +0000277 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000278 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000279
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000280 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000281 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000282 return C;
283 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000284
285 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
286 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
287 }
288
Chris Lattner0c967662004-09-24 15:21:34 +0000289
Chris Lattner8b170942002-08-09 23:47:40 +0000290 // ReplaceInstUsesWith - This method is to be used when an instruction is
291 // found to be dead, replacable with another preexisting expression. Here
292 // we add all uses of I to the worklist, replace all uses of I with the new
293 // value, then return I, so that the inst combiner will know that I was
294 // modified.
295 //
296 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000297 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000298 if (&I != V) {
299 I.replaceAllUsesWith(V);
300 return &I;
301 } else {
302 // If we are replacing the instruction with itself, this must be in a
303 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000304 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000305 return &I;
306 }
Chris Lattner8b170942002-08-09 23:47:40 +0000307 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308
309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000316 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000317 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 return 0; // Don't do anything with FI
319 }
Chris Lattner173234a2008-06-02 01:18:21 +0000320
321 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
322 APInt &KnownOne, unsigned Depth = 0) const {
323 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
324 }
325
326 bool MaskedValueIsZero(Value *V, const APInt &Mask,
327 unsigned Depth = 0) const {
328 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
329 }
330 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
331 return llvm::ComputeNumSignBits(Op, TD, Depth);
332 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000333
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000334 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000338 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000339
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
Chris Lattner886ab6c2009-01-31 08:15:18 +0000344 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
345 /// based on the demanded bits.
346 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth);
349 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000350 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000351 unsigned Depth=0);
352
353 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
354 /// SimplifyDemandedBits knows about. See if the instruction has any
355 /// properties that allow us to simplify its operands.
356 bool SimplifyDemandedInstructionBits(Instruction &Inst);
357
Evan Cheng388df622009-02-03 10:05:09 +0000358 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
359 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000360
Chris Lattner4e998b22004-09-29 05:07:12 +0000361 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
362 // PHI node as operand #0, see if we can fold the instruction into the PHI
363 // (which is only possible if all operands to the PHI are constants).
364 Instruction *FoldOpIntoPhi(Instruction &I);
365
Chris Lattnerbac32862004-11-14 19:13:23 +0000366 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
367 // operator and they all are only used by the PHI, PHI together their
368 // inputs, and do the operation once, to the result of the PHI.
369 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000370 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000371 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
372
Chris Lattner7da52b22006-11-01 04:51:18 +0000373
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000374 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
375 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000376
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000377 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000378 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000379 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000380 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000381 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000382 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000383 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000384 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000385 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000386
Chris Lattnerafe91a52006-06-15 19:07:26 +0000387
Reid Spencerc55b2432006-12-13 18:21:21 +0000388 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389
Dan Gohmaneee962e2008-04-10 18:43:06 +0000390 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000391 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000392 unsigned GetOrEnforceKnownAlignment(Value *V,
393 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000394
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000395 };
396}
397
Dan Gohman844731a2008-05-13 00:00:25 +0000398char InstCombiner::ID = 0;
399static RegisterPass<InstCombiner>
400X("instcombine", "Combine redundant instructions");
401
Chris Lattner4f98c562003-03-10 21:43:22 +0000402// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000403// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000404static unsigned getComplexity(Value *V) {
405 if (isa<Instruction>(V)) {
406 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000407 return 3;
408 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000409 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000410 if (isa<Argument>(V)) return 3;
411 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000412}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000413
Chris Lattnerc8802d22003-03-11 00:12:48 +0000414// isOnlyUse - Return true if this instruction will be deleted if we stop using
415// it.
416static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000417 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000418}
419
Chris Lattner4cb170c2004-02-23 06:38:22 +0000420// getPromotedType - Return the specified type promoted as it would be to pass
421// though a va_arg area...
422static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000423 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
424 if (ITy->getBitWidth() < 32)
425 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000426 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000427 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000428}
429
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000430/// getBitCastOperand - If the specified operand is a CastInst, a constant
431/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
432/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000433static Value *getBitCastOperand(Value *V) {
434 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000435 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000436 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000437 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
438 // GetElementPtrInst?
439 if (GEP->hasAllZeroIndices())
440 return GEP->getOperand(0);
441 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000442 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000444 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000445 else if (CE->getOpcode() == Instruction::GetElementPtr) {
446 // GetElementPtr ConstantExp?
447 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
448 I != E; ++I) {
449 ConstantInt *CI = dyn_cast<ConstantInt>(I);
450 if (!CI || !CI->isZero())
451 // Any non-zero indices? Not cast-like.
452 return 0;
453 }
454 // All-zero indices? This is just like casting.
455 return CE->getOperand(0);
456 }
457 }
Chris Lattnereed48272005-09-13 00:40:14 +0000458 return 0;
459}
460
Reid Spencer3da59db2006-11-27 01:05:10 +0000461/// This function is a wrapper around CastInst::isEliminableCastPair. It
462/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000463static Instruction::CastOps
464isEliminableCastPair(
465 const CastInst *CI, ///< The first cast instruction
466 unsigned opcode, ///< The opcode of the second cast instruction
467 const Type *DstTy, ///< The target type for the second cast instruction
468 TargetData *TD ///< The target data for pointer size
469) {
470
471 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
472 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Reid Spencer3da59db2006-11-27 01:05:10 +0000474 // Get the opcodes of the two Cast instructions
475 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
476 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000477
Chris Lattnera0e69692009-03-24 18:35:40 +0000478 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
479 DstTy, TD->getIntPtrType());
480
481 // We don't want to form an inttoptr or ptrtoint that converts to an integer
482 // type that differs from the pointer size.
483 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
484 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
485 Res = 0;
486
487 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000488}
489
490/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
491/// in any code being generated. It does not require codegen if V is simple
492/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000493static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
494 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000495 if (V->getType() == Ty || isa<Constant>(V)) return false;
496
Chris Lattner01575b72006-05-25 23:24:33 +0000497 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000498 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000499 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000500 return false;
501 return true;
502}
503
Chris Lattner4f98c562003-03-10 21:43:22 +0000504// SimplifyCommutative - This performs a few simplifications for commutative
505// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000506//
Chris Lattner4f98c562003-03-10 21:43:22 +0000507// 1. Order operands such that they are listed from right (least complex) to
508// left (most complex). This puts constants before unary operators before
509// binary operators.
510//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
512// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000513//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000514bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 bool Changed = false;
516 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
517 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000518
Chris Lattner4f98c562003-03-10 21:43:22 +0000519 if (!I.isAssociative()) return Changed;
520 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000524 Constant *Folded = ConstantExpr::get(I.getOpcode(),
525 cast<Constant>(I.getOperand(1)),
526 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000527 I.setOperand(0, Op->getOperand(0));
528 I.setOperand(1, Folded);
529 return true;
530 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532 isOnlyUse(Op) && isOnlyUse(Op1)) {
533 Constant *C1 = cast<Constant>(Op->getOperand(1));
534 Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000537 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000538 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000539 Op1->getOperand(0),
540 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000541 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000542 I.setOperand(0, New);
543 I.setOperand(1, Folded);
544 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000545 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000547 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000548}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000549
Reid Spencere4d87aa2006-12-23 06:05:41 +0000550/// SimplifyCompare - For a CmpInst this function just orders the operands
551/// so that theyare listed from right (least complex) to left (most complex).
552/// This puts constants before unary operators before binary operators.
553bool InstCombiner::SimplifyCompare(CmpInst &I) {
554 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
555 return false;
556 I.swapOperands();
557 // Compare instructions are not associative so there's nothing else we can do.
558 return true;
559}
560
Chris Lattner8d969642003-03-10 23:06:50 +0000561// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
562// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000563//
Chris Lattner8d969642003-03-10 23:06:50 +0000564static inline Value *dyn_castNegVal(Value *V) {
565 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000566 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000567
Chris Lattner0ce85802004-12-14 20:08:06 +0000568 // Constants can be considered to be negated values if they can be folded.
569 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
570 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000571
572 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
573 if (C->getType()->getElementType()->isInteger())
574 return ConstantExpr::getNeg(C);
575
Chris Lattner8d969642003-03-10 23:06:50 +0000576 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000577}
578
Chris Lattner8d969642003-03-10 23:06:50 +0000579static inline Value *dyn_castNotVal(Value *V) {
580 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000581 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000582
583 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000584 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000585 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000586 return 0;
587}
588
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589// dyn_castFoldableMul - If this value is a multiply that can be folded into
590// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000591// non-constant operand of the multiply, and set CST to point to the multiplier.
592// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000593//
Chris Lattner50af16a2004-11-13 19:50:12 +0000594static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000595 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000597 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000598 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000599 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000600 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000601 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000602 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000603 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000604 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000605 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000606 return I->getOperand(0);
607 }
608 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000609 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000610}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000611
Chris Lattner574da9b2005-01-13 20:14:25 +0000612/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
613/// expression, return it.
614static User *dyn_castGetElementPtr(Value *V) {
615 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
616 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
617 if (CE->getOpcode() == Instruction::GetElementPtr)
618 return cast<User>(V);
619 return false;
620}
621
Dan Gohmaneee962e2008-04-10 18:43:06 +0000622/// getOpcode - If this is an Instruction or a ConstantExpr, return the
623/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000624static unsigned getOpcode(const Value *V) {
625 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000626 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000627 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000628 return CE->getOpcode();
629 // Use UserOp1 to mean there's no opcode.
630 return Instruction::UserOp1;
631}
632
Reid Spencer7177c3a2007-03-25 05:33:51 +0000633/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000634static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000635 APInt Val(C->getValue());
636 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000637}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000638/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000639static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000640 APInt Val(C->getValue());
641 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642}
643/// Add - Add two ConstantInts together
644static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() + C2->getValue());
646}
647/// And - Bitwise AND two ConstantInts together
648static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() & C2->getValue());
650}
651/// Subtract - Subtract one ConstantInt from another
652static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
653 return ConstantInt::get(C1->getValue() - C2->getValue());
654}
655/// Multiply - Multiply two ConstantInts together
656static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
657 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000658}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000659/// MultiplyOverflows - True if the multiply can not be expressed in an int
660/// this size.
661static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
662 uint32_t W = C1->getBitWidth();
663 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
664 if (sign) {
665 LHSExt.sext(W * 2);
666 RHSExt.sext(W * 2);
667 } else {
668 LHSExt.zext(W * 2);
669 RHSExt.zext(W * 2);
670 }
671
672 APInt MulExt = LHSExt * RHSExt;
673
674 if (sign) {
675 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
676 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
677 return MulExt.slt(Min) || MulExt.sgt(Max);
678 } else
679 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
680}
Chris Lattner955f3312004-09-28 21:48:02 +0000681
Reid Spencere7816b52007-03-08 01:52:58 +0000682
Chris Lattner255d8912006-02-11 09:31:47 +0000683/// ShrinkDemandedConstant - Check to see if the specified operand of the
684/// specified instruction is a constant integer. If so, check to see if there
685/// are any bits set in the constant that are not demanded. If so, shrink the
686/// constant and return true.
687static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000688 APInt Demanded) {
689 assert(I && "No instruction?");
690 assert(OpNo < I->getNumOperands() && "Operand index too large");
691
692 // If the operand is not a constant integer, nothing to do.
693 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
694 if (!OpC) return false;
695
696 // If there are no bits set that aren't demanded, nothing to do.
697 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
698 if ((~Demanded & OpC->getValue()) == 0)
699 return false;
700
701 // This instruction is producing bits that are not demanded. Shrink the RHS.
702 Demanded &= OpC->getValue();
703 I->setOperand(OpNo, ConstantInt::get(Demanded));
704 return true;
705}
706
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000707// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
708// set of known zero and one bits, compute the maximum and minimum values that
709// could have the specified known zero and known one bits, returning them in
710// min/max.
711static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000712 const APInt& KnownZero,
713 const APInt& KnownOne,
714 APInt& Min, APInt& Max) {
715 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
716 assert(KnownZero.getBitWidth() == BitWidth &&
717 KnownOne.getBitWidth() == BitWidth &&
718 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
719 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000720 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723 // bit if it is unknown.
724 Min = KnownOne;
725 Max = KnownOne|UnknownBits;
726
Zhou Sheng4acf1552007-03-28 05:15:57 +0000727 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000728 Min.set(BitWidth-1);
729 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000730 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000731}
732
733// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734// a set of known zero and one bits, compute the maximum and minimum values that
735// could have the specified known zero and known one bits, returning them in
736// min/max.
737static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000738 const APInt &KnownZero,
739 const APInt &KnownOne,
740 APInt &Min, APInt &Max) {
741 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000742 assert(KnownZero.getBitWidth() == BitWidth &&
743 KnownOne.getBitWidth() == BitWidth &&
744 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
745 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000746 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000747
748 // The minimum value is when the unknown bits are all zeros.
749 Min = KnownOne;
750 // The maximum value is when the unknown bits are all ones.
751 Max = KnownOne|UnknownBits;
752}
Chris Lattner255d8912006-02-11 09:31:47 +0000753
Chris Lattner886ab6c2009-01-31 08:15:18 +0000754/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
755/// SimplifyDemandedBits knows about. See if the instruction has any
756/// properties that allow us to simplify its operands.
757bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
758 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
759 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
760 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
761
762 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
763 KnownZero, KnownOne, 0);
764 if (V == 0) return false;
765 if (V == &Inst) return true;
766 ReplaceInstUsesWith(Inst, V);
767 return true;
768}
769
770/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
771/// specified instruction operand if possible, updating it in place. It returns
772/// true if it made any change and false otherwise.
773bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
774 APInt &KnownZero, APInt &KnownOne,
775 unsigned Depth) {
776 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
777 KnownZero, KnownOne, Depth);
778 if (NewVal == 0) return false;
779 U.set(NewVal);
780 return true;
781}
782
783
784/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
785/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000786/// that only the bits set in DemandedMask of the result of V are ever used
787/// downstream. Consequently, depending on the mask and V, it may be possible
788/// to replace V with a constant or one of its operands. In such cases, this
789/// function does the replacement and returns true. In all other cases, it
790/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000791/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000792/// to be zero in the expression. These are provided to potentially allow the
793/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
794/// the expression. KnownOne and KnownZero always follow the invariant that
795/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
796/// the bits in KnownOne and KnownZero may only be accurate for those bits set
797/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
798/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000799///
800/// This returns null if it did not change anything and it permits no
801/// simplification. This returns V itself if it did some simplification of V's
802/// operands based on the information about what bits are demanded. This returns
803/// some other non-null value if it found out that V is equal to another value
804/// in the context where the specified bits are demanded, but not for all users.
805Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
806 APInt &KnownZero, APInt &KnownOne,
807 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000808 assert(V != 0 && "Null pointer of Value???");
809 assert(Depth <= 6 && "Limit Search Depth");
810 uint32_t BitWidth = DemandedMask.getBitWidth();
811 const IntegerType *VTy = cast<IntegerType>(V->getType());
812 assert(VTy->getBitWidth() == BitWidth &&
813 KnownZero.getBitWidth() == BitWidth &&
814 KnownOne.getBitWidth() == BitWidth &&
815 "Value *V, DemandedMask, KnownZero and KnownOne \
816 must have same BitWidth");
817 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
818 // We know all of the bits for a constant!
819 KnownOne = CI->getValue() & DemandedMask;
820 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000821 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 }
823
Chris Lattner08d2cc72009-01-31 07:26:06 +0000824 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000825 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 if (DemandedMask == 0) { // Not demanding any bits from V.
827 if (isa<UndefValue>(V))
828 return 0;
829 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000830 }
831
Chris Lattner4598c942009-01-31 08:24:16 +0000832 if (Depth == 6) // Limit search depth.
833 return 0;
834
Reid Spencer8cb68342007-03-12 17:25:59 +0000835 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000836 if (!I) return 0; // Only analyze instructions.
Chris Lattner4598c942009-01-31 08:24:16 +0000837
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000838 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
839 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
840
Chris Lattner4598c942009-01-31 08:24:16 +0000841 // If there are multiple uses of this value and we aren't at the root, then
842 // we can't do any simplifications of the operands, because DemandedMask
843 // only reflects the bits demanded by *one* of the users.
844 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000845 // Despite the fact that we can't simplify this instruction in all User's
846 // context, we can at least compute the knownzero/knownone bits, and we can
847 // do simplifications that apply to *just* the one user if we know that
848 // this instruction has a simpler value in that context.
849 if (I->getOpcode() == Instruction::And) {
850 // If either the LHS or the RHS are Zero, the result is zero.
851 ComputeMaskedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1);
853 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
854 LHSKnownZero, LHSKnownOne, Depth+1);
855
856 // If all of the demanded bits are known 1 on one side, return the other.
857 // These bits cannot contribute to the result of the 'and' in this
858 // context.
859 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
860 (DemandedMask & ~LHSKnownZero))
861 return I->getOperand(0);
862 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
863 (DemandedMask & ~RHSKnownZero))
864 return I->getOperand(1);
865
866 // If all of the demanded bits in the inputs are known zeros, return zero.
867 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
868 return Constant::getNullValue(VTy);
869
870 } else if (I->getOpcode() == Instruction::Or) {
871 // We can simplify (X|Y) -> X or Y in the user's context if we know that
872 // only bits from X or Y are demanded.
873
874 // If either the LHS or the RHS are One, the result is One.
875 ComputeMaskedBits(I->getOperand(1), DemandedMask,
876 RHSKnownZero, RHSKnownOne, Depth+1);
877 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
878 LHSKnownZero, LHSKnownOne, Depth+1);
879
880 // If all of the demanded bits are known zero on one side, return the
881 // other. These bits cannot contribute to the result of the 'or' in this
882 // context.
883 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
884 (DemandedMask & ~LHSKnownOne))
885 return I->getOperand(0);
886 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
887 (DemandedMask & ~RHSKnownOne))
888 return I->getOperand(1);
889
890 // If all of the potentially set bits on one side are known to be set on
891 // the other side, just use the 'other' side.
892 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
893 (DemandedMask & (~RHSKnownZero)))
894 return I->getOperand(0);
895 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
896 (DemandedMask & (~LHSKnownZero)))
897 return I->getOperand(1);
898 }
899
Chris Lattner4598c942009-01-31 08:24:16 +0000900 // Compute the KnownZero/KnownOne bits to simplify things downstream.
901 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
902 return 0;
903 }
904
905 // If this is the root being simplified, allow it to have multiple uses,
906 // just set the DemandedMask to all bits so that we can try to simplify the
907 // operands. This allows visitTruncInst (for example) to simplify the
908 // operand of a trunc without duplicating all the logic below.
909 if (Depth == 0 && !V->hasOneUse())
910 DemandedMask = APInt::getAllOnesValue(BitWidth);
911
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000913 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000914 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000915 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000916 case Instruction::And:
917 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000918 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
919 RHSKnownZero, RHSKnownOne, Depth+1) ||
920 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922 return I;
923 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
924 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and'.
928 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
929 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000930 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
932 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // If all of the demanded bits in the inputs are known zeros, return zero.
936 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000937 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000938
939 // If the RHS is a constant, see if we can simplify it.
940 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000942
943 // Output known-1 bits are only known if set in both the LHS & RHS.
944 RHSKnownOne &= LHSKnownOne;
945 // Output known-0 are known to be clear if zero in either the LHS | RHS.
946 RHSKnownZero |= LHSKnownZero;
947 break;
948 case Instruction::Or:
949 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1) ||
952 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I;
955 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
956 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the demanded bits are known zero on one side, return the other.
959 // These bits cannot contribute to the result of the 'or'.
960 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
961 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
964 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If all of the potentially set bits on one side are known to be set on
968 // the other side, just use the 'other' side.
969 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
970 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
973 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000975
976 // If the RHS is a constant, see if we can simplify it.
977 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000979
980 // Output known-0 bits are only known if clear in both the LHS & RHS.
981 RHSKnownZero &= LHSKnownZero;
982 // Output known-1 are known to be set if set in either the LHS | RHS.
983 RHSKnownOne |= LHSKnownOne;
984 break;
985 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
987 RHSKnownZero, RHSKnownOne, Depth+1) ||
988 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I;
991 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
992 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000993
994 // If all of the demanded bits are known zero on one side, return the other.
995 // These bits cannot contribute to the result of the 'xor'.
996 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1002 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1003 (RHSKnownOne & LHSKnownOne);
1004 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1005 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1006 (RHSKnownOne & LHSKnownZero);
1007
1008 // If all of the demanded bits are known to be zero on one side or the
1009 // other, turn this into an *inclusive* or.
1010 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1011 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1012 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001013 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001016 }
1017
1018 // If all of the demanded bits on one side are known, and all of the set
1019 // bits on that side are also known to be set on the other side, turn this
1020 // into an AND, as we know the bits will be cleared.
1021 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1022 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1023 // all known
1024 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1025 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1026 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001027 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 }
1030 }
1031
1032 // If the RHS is a constant, see if we can simplify it.
1033 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1034 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001036
1037 RHSKnownZero = KnownZeroOut;
1038 RHSKnownOne = KnownOneOut;
1039 break;
1040 }
1041 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001045 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001046 return I;
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
1050 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1052 ShrinkDemandedConstant(I, 2, DemandedMask))
1053 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001054
1055 // Only known if known in both the LHS and RHS.
1056 RHSKnownOne &= LHSKnownOne;
1057 RHSKnownZero &= LHSKnownZero;
1058 break;
1059 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001061 DemandedMask.zext(truncBf);
1062 RHSKnownZero.zext(truncBf);
1063 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001065 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001066 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 DemandedMask.trunc(BitWidth);
1068 RHSKnownZero.trunc(BitWidth);
1069 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001070 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001071 break;
1072 }
1073 case Instruction::BitCast:
1074 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 return false; // vector->int or fp->int?
1076 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001077 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
1079 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001080 break;
1081 case Instruction::ZExt: {
1082 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001084
Zhou Shengd48653a2007-03-29 04:45:55 +00001085 DemandedMask.trunc(SrcBitWidth);
1086 RHSKnownZero.trunc(SrcBitWidth);
1087 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001089 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001091 DemandedMask.zext(BitWidth);
1092 RHSKnownZero.zext(BitWidth);
1093 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001094 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001095 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001096 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 break;
1098 }
1099 case Instruction::SExt: {
1100 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001101 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001102
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001104 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001105
Zhou Sheng01542f32007-03-29 02:26:30 +00001106 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 // If any of the sign extended bits are demanded, we know that the sign
1108 // bit is demanded.
1109 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001110 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
Zhou Shengd48653a2007-03-29 04:45:55 +00001112 InputDemandedBits.trunc(SrcBitWidth);
1113 RHSKnownZero.trunc(SrcBitWidth);
1114 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001116 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001118 InputDemandedBits.zext(BitWidth);
1119 RHSKnownZero.zext(BitWidth);
1120 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001122
1123 // If the sign bit of the input is known set or clear, then we know the
1124 // top bits of the result.
1125
1126 // If the input sign bit is known zero, or if the NewBits are not demanded
1127 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001128 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1131 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001132 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001133 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 }
1135 break;
1136 }
1137 case Instruction::Add: {
1138 // Figure out what the input bits are. If the top bits of the and result
1139 // are not demanded, then the add doesn't demand them from its input
1140 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001141 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001142
1143 // If there is a constant on the RHS, there are a variety of xformations
1144 // we can do.
1145 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1146 // If null, this should be simplified elsewhere. Some of the xforms here
1147 // won't work if the RHS is zero.
1148 if (RHS->isZero())
1149 break;
1150
1151 // If the top bit of the output is demanded, demand everything from the
1152 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001153 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001159
1160 // If the RHS of the add has bits set that can't affect the input, reduce
1161 // the constant.
1162 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001164
1165 // Avoid excess work.
1166 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1167 break;
1168
1169 // Turn it into OR if input bits are zero.
1170 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1171 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001172 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 }
1176
1177 // We can say something about the output known-zero and known-one bits,
1178 // depending on potential carries from the input constant and the
1179 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1180 // bits set and the RHS constant is 0x01001, then we know we have a known
1181 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1182
1183 // To compute this, we first compute the potential carry bits. These are
1184 // the bits which may be modified. I'm not aware of a better way to do
1185 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001187 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001188
1189 // Now that we know which bits have carries, compute the known-1/0 sets.
1190
1191 // Bits are known one if they are known zero in one operand and one in the
1192 // other, and there is no input carry.
1193 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1194 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1195
1196 // Bits are known zero if they are known zero in both operands and there
1197 // is no input carry.
1198 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1199 } else {
1200 // If the high-bits of this ADD are not demanded, then it does not demand
1201 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001202 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 // Right fill the mask of bits for this ADD to demand the most
1204 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001205 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001206 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1207 LHSKnownZero, LHSKnownOne, Depth+1) ||
1208 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001210 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001211 }
1212 }
1213 break;
1214 }
1215 case Instruction::Sub:
1216 // If the high-bits of this SUB are not demanded, then it does not demand
1217 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001219 // Right fill the mask of bits for this SUB to demand the most
1220 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001221 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001222 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001223 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1224 LHSKnownZero, LHSKnownOne, Depth+1) ||
1225 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001229 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1230 // the known zeros and ones.
1231 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 break;
1233 case Instruction::Shl:
1234 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001235 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001236 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 return I;
1240 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 RHSKnownZero <<= ShiftAmt;
1242 RHSKnownOne <<= ShiftAmt;
1243 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001244 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001245 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 }
1247 break;
1248 case Instruction::LShr:
1249 // For a logical shift right
1250 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001251 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001252
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001254 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001257 return I;
1258 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1260 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001261 if (ShiftAmt) {
1262 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001263 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001264 RHSKnownZero |= HighBits; // high bits known zero.
1265 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 }
1267 break;
1268 case Instruction::AShr:
1269 // If this is an arithmetic shift right and only the low-bit is set, we can
1270 // always convert this into a logical shr, even if the shift amount is
1271 // variable. The low bit of the shift cannot be an input sign bit unless
1272 // the shift amount is >= the size of the datatype, which is undefined.
1273 if (DemandedMask == 1) {
1274 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001275 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001277 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001279
1280 // If the sign bit is the only bit demanded by this ashr, then there is no
1281 // need to do it, the shift doesn't change the high bit.
1282 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
1285 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001286 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001290 // If any of the "high bits" are demanded, we should set the sign bit as
1291 // demanded.
1292 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1293 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I;
1297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001299 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1301 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1302
1303 // Handle the sign bits.
1304 APInt SignBit(APInt::getSignBit(BitWidth));
1305 // Adjust to where it is now in the mask.
1306 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1307
1308 // If the input sign bit is known to be zero, or if none of the top bits
1309 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001310 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 (HighBits & ~DemandedMask) == HighBits) {
1312 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001313 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001315 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1317 RHSKnownOne |= HighBits;
1318 }
1319 }
1320 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001321 case Instruction::SRem:
1322 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001323 APInt RA = Rem->getValue().abs();
1324 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001325 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001326 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001327
Nick Lewycky8e394322008-11-02 02:41:50 +00001328 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001329 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001330 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001331 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001333
1334 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1335 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001336
1337 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001338
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001340 }
1341 }
1342 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001343 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001344 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1345 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1347 KnownZero2, KnownOne2, Depth+1) ||
1348 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001349 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001351
Chris Lattner455e9ab2009-01-21 18:09:24 +00001352 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001353 Leaders = std::max(Leaders,
1354 KnownZero2.countLeadingOnes());
1355 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001356 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001357 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001358 case Instruction::Call:
1359 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1360 switch (II->getIntrinsicID()) {
1361 default: break;
1362 case Intrinsic::bswap: {
1363 // If the only bits demanded come from one byte of the bswap result,
1364 // just shift the input byte into position to eliminate the bswap.
1365 unsigned NLZ = DemandedMask.countLeadingZeros();
1366 unsigned NTZ = DemandedMask.countTrailingZeros();
1367
1368 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1369 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1370 // have 14 leading zeros, round to 8.
1371 NLZ &= ~7;
1372 NTZ &= ~7;
1373 // If we need exactly one byte, we can do this transformation.
1374 if (BitWidth-NLZ-NTZ == 8) {
1375 unsigned ResultBit = NTZ;
1376 unsigned InputBit = BitWidth-NTZ-8;
1377
1378 // Replace this with either a left or right shift to get the byte into
1379 // the right place.
1380 Instruction *NewVal;
1381 if (InputBit > ResultBit)
1382 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1383 ConstantInt::get(I->getType(), InputBit-ResultBit));
1384 else
1385 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1386 ConstantInt::get(I->getType(), ResultBit-InputBit));
1387 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001388 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001389 }
1390
1391 // TODO: Could compute known zero/one bits based on the input.
1392 break;
1393 }
1394 }
1395 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001396 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001397 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001398 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001399
1400 // If the client is only demanding bits that we know, return the known
1401 // constant.
1402 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001403 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 return false;
1405}
1406
Chris Lattner867b99f2006-10-05 06:55:50 +00001407
Mon P Wangaeb06d22008-11-10 04:46:22 +00001408/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001409/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001410/// actually used by the caller. This method analyzes which elements of the
1411/// operand are undef and returns that information in UndefElts.
1412///
1413/// If the information about demanded elements can be used to simplify the
1414/// operation, the operation is simplified, then the resultant value is
1415/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001416Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1417 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001418 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001419 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001420 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001421 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001422
1423 if (isa<UndefValue>(V)) {
1424 // If the entire vector is undefined, just return this info.
1425 UndefElts = EltMask;
1426 return 0;
1427 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1428 UndefElts = EltMask;
1429 return UndefValue::get(V->getType());
1430 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001431
Chris Lattner867b99f2006-10-05 06:55:50 +00001432 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001433 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1434 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 Constant *Undef = UndefValue::get(EltTy);
1436
1437 std::vector<Constant*> Elts;
1438 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001439 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001440 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001441 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001442 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1443 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001444 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001445 } else { // Otherwise, defined.
1446 Elts.push_back(CP->getOperand(i));
1447 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001448
Chris Lattner867b99f2006-10-05 06:55:50 +00001449 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001450 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 return NewCP != CP ? NewCP : 0;
1452 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001455
1456 // Check if this is identity. If so, return 0 since we are not simplifying
1457 // anything.
1458 if (DemandedElts == ((1ULL << VWidth) -1))
1459 return 0;
1460
Reid Spencer9d6565a2007-02-15 02:26:10 +00001461 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 Constant *Zero = Constant::getNullValue(EltTy);
1463 Constant *Undef = UndefValue::get(EltTy);
1464 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001465 for (unsigned i = 0; i != VWidth; ++i) {
1466 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1467 Elts.push_back(Elt);
1468 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001470 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 }
1472
Dan Gohman488fbfc2008-09-09 18:11:14 +00001473 // Limit search depth.
1474 if (Depth == 10)
1475 return false;
1476
1477 // If multiple users are using the root value, procede with
1478 // simplification conservatively assuming that all elements
1479 // are needed.
1480 if (!V->hasOneUse()) {
1481 // Quit if we find multiple users of a non-root value though.
1482 // They'll be handled when it's their turn to be visited by
1483 // the main instcombine process.
1484 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 // TODO: Just compute the UndefElts information recursively.
1486 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001487
1488 // Conservatively assume that all elements are needed.
1489 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 }
1491
1492 Instruction *I = dyn_cast<Instruction>(V);
1493 if (!I) return false; // Only analyze instructions.
1494
1495 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001496 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 Value *TmpV;
1498 switch (I->getOpcode()) {
1499 default: break;
1500
1501 case Instruction::InsertElement: {
1502 // If this is a variable index, we don't know which element it overwrites.
1503 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001504 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 if (Idx == 0) {
1506 // Note that we can't propagate undef elt info, because we don't know
1507 // which elt is getting updated.
1508 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1509 UndefElts2, Depth+1);
1510 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511 break;
1512 }
1513
1514 // If this is inserting an element that isn't demanded, remove this
1515 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001516 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001517 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 return AddSoonDeadInstToWorklist(*I, 0);
1519
1520 // Otherwise, the element inserted overwrites whatever was there, so the
1521 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001522 APInt DemandedElts2 = DemandedElts;
1523 DemandedElts2.clear(IdxNo);
1524 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 UndefElts, Depth+1);
1526 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1527
1528 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001529 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001530 break;
1531 }
1532 case Instruction::ShuffleVector: {
1533 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001534 uint64_t LHSVWidth =
1535 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001536 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001537 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001538 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001539 unsigned MaskVal = Shuffle->getMaskValue(i);
1540 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001541 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001542 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001543 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001544 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001545 else
Evan Cheng388df622009-02-03 10:05:09 +00001546 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001547 }
1548 }
1549 }
1550
Nate Begeman7b254672009-02-11 22:36:25 +00001551 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001552 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001553 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1555
Nate Begeman7b254672009-02-11 22:36:25 +00001556 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1558 UndefElts3, Depth+1);
1559 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1560
1561 bool NewUndefElts = false;
1562 for (unsigned i = 0; i < VWidth; i++) {
1563 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001564 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001565 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001566 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001567 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001568 NewUndefElts = true;
1569 UndefElts.set(i);
1570 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001572 if (UndefElts3[MaskVal - LHSVWidth]) {
1573 NewUndefElts = true;
1574 UndefElts.set(i);
1575 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 }
1577 }
1578
1579 if (NewUndefElts) {
1580 // Add additional discovered undefs.
1581 std::vector<Constant*> Elts;
1582 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001583 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001584 Elts.push_back(UndefValue::get(Type::Int32Ty));
1585 else
1586 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1587 Shuffle->getMaskValue(i)));
1588 }
1589 I->setOperand(2, ConstantVector::get(Elts));
1590 MadeChange = true;
1591 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001592 break;
1593 }
Chris Lattner69878332007-04-14 22:29:23 +00001594 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001595 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001596 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1597 if (!VTy) break;
1598 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001599 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001600 unsigned Ratio;
1601
1602 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001603 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001604 // elements as are demanded of us.
1605 Ratio = 1;
1606 InputDemandedElts = DemandedElts;
1607 } else if (VWidth > InVWidth) {
1608 // Untested so far.
1609 break;
1610
1611 // If there are more elements in the result than there are in the source,
1612 // then an input element is live if any of the corresponding output
1613 // elements are live.
1614 Ratio = VWidth/InVWidth;
1615 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001616 if (DemandedElts[OutIdx])
1617 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001618 }
1619 } else {
1620 // Untested so far.
1621 break;
1622
1623 // If there are more elements in the source than there are in the result,
1624 // then an input element is live if the corresponding output element is
1625 // live.
1626 Ratio = InVWidth/VWidth;
1627 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001628 if (DemandedElts[InIdx/Ratio])
1629 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001630 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001631
Chris Lattner69878332007-04-14 22:29:23 +00001632 // div/rem demand all inputs, because they don't want divide by zero.
1633 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1634 UndefElts2, Depth+1);
1635 if (TmpV) {
1636 I->setOperand(0, TmpV);
1637 MadeChange = true;
1638 }
1639
1640 UndefElts = UndefElts2;
1641 if (VWidth > InVWidth) {
1642 assert(0 && "Unimp");
1643 // If there are more elements in the result than there are in the source,
1644 // then an output element is undef if the corresponding input element is
1645 // undef.
1646 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001647 if (UndefElts2[OutIdx/Ratio])
1648 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001649 } else if (VWidth < InVWidth) {
1650 assert(0 && "Unimp");
1651 // If there are more elements in the source than there are in the result,
1652 // then a result element is undef if all of the corresponding input
1653 // elements are undef.
1654 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1655 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001656 if (!UndefElts2[InIdx]) // Not undef?
1657 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001658 }
1659 break;
1660 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001661 case Instruction::And:
1662 case Instruction::Or:
1663 case Instruction::Xor:
1664 case Instruction::Add:
1665 case Instruction::Sub:
1666 case Instruction::Mul:
1667 // div/rem demand all inputs, because they don't want divide by zero.
1668 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1669 UndefElts, Depth+1);
1670 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1671 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1672 UndefElts2, Depth+1);
1673 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1674
1675 // Output elements are undefined if both are undefined. Consider things
1676 // like undef&0. The result is known zero, not undef.
1677 UndefElts &= UndefElts2;
1678 break;
1679
1680 case Instruction::Call: {
1681 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1682 if (!II) break;
1683 switch (II->getIntrinsicID()) {
1684 default: break;
1685
1686 // Binary vector operations that work column-wise. A dest element is a
1687 // function of the corresponding input elements from the two inputs.
1688 case Intrinsic::x86_sse_sub_ss:
1689 case Intrinsic::x86_sse_mul_ss:
1690 case Intrinsic::x86_sse_min_ss:
1691 case Intrinsic::x86_sse_max_ss:
1692 case Intrinsic::x86_sse2_sub_sd:
1693 case Intrinsic::x86_sse2_mul_sd:
1694 case Intrinsic::x86_sse2_min_sd:
1695 case Intrinsic::x86_sse2_max_sd:
1696 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1697 UndefElts, Depth+1);
1698 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1699 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1700 UndefElts2, Depth+1);
1701 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1702
1703 // If only the low elt is demanded and this is a scalarizable intrinsic,
1704 // scalarize it now.
1705 if (DemandedElts == 1) {
1706 switch (II->getIntrinsicID()) {
1707 default: break;
1708 case Intrinsic::x86_sse_sub_ss:
1709 case Intrinsic::x86_sse_mul_ss:
1710 case Intrinsic::x86_sse2_sub_sd:
1711 case Intrinsic::x86_sse2_mul_sd:
1712 // TODO: Lower MIN/MAX/ABS/etc
1713 Value *LHS = II->getOperand(1);
1714 Value *RHS = II->getOperand(2);
1715 // Extract the element as scalars.
1716 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1717 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1718
1719 switch (II->getIntrinsicID()) {
1720 default: assert(0 && "Case stmts out of sync!");
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001723 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001724 II->getName()), *II);
1725 break;
1726 case Intrinsic::x86_sse_mul_ss:
1727 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001728 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001729 II->getName()), *II);
1730 break;
1731 }
1732
1733 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001734 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1735 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001736 InsertNewInstBefore(New, *II);
1737 AddSoonDeadInstToWorklist(*II, 0);
1738 return New;
1739 }
1740 }
1741
1742 // Output elements are undefined if both are undefined. Consider things
1743 // like undef&0. The result is known zero, not undef.
1744 UndefElts &= UndefElts2;
1745 break;
1746 }
1747 break;
1748 }
1749 }
1750 return MadeChange ? I : 0;
1751}
1752
Dan Gohman45b4e482008-05-19 22:14:15 +00001753
Chris Lattner564a7272003-08-13 19:01:45 +00001754/// AssociativeOpt - Perform an optimization on an associative operator. This
1755/// function is designed to check a chain of associative operators for a
1756/// potential to apply a certain optimization. Since the optimization may be
1757/// applicable if the expression was reassociated, this checks the chain, then
1758/// reassociates the expression as necessary to expose the optimization
1759/// opportunity. This makes use of a special Functor, which must define
1760/// 'shouldApply' and 'apply' methods.
1761///
1762template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001763static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001764 unsigned Opcode = Root.getOpcode();
1765 Value *LHS = Root.getOperand(0);
1766
1767 // Quick check, see if the immediate LHS matches...
1768 if (F.shouldApply(LHS))
1769 return F.apply(Root);
1770
1771 // Otherwise, if the LHS is not of the same opcode as the root, return.
1772 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001773 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001774 // Should we apply this transform to the RHS?
1775 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1776
1777 // If not to the RHS, check to see if we should apply to the LHS...
1778 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1779 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1780 ShouldApply = true;
1781 }
1782
1783 // If the functor wants to apply the optimization to the RHS of LHSI,
1784 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1785 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001786 // Now all of the instructions are in the current basic block, go ahead
1787 // and perform the reassociation.
1788 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1789
1790 // First move the selected RHS to the LHS of the root...
1791 Root.setOperand(0, LHSI->getOperand(1));
1792
1793 // Make what used to be the LHS of the root be the user of the root...
1794 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001795 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001796 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1797 return 0;
1798 }
Chris Lattner65725312004-04-16 18:08:07 +00001799 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001800 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001801 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001802 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001803 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001804
1805 // Now propagate the ExtraOperand down the chain of instructions until we
1806 // get to LHSI.
1807 while (TmpLHSI != LHSI) {
1808 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001809 // Move the instruction to immediately before the chain we are
1810 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001811 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001812 ARI = NextLHSI;
1813
Chris Lattner564a7272003-08-13 19:01:45 +00001814 Value *NextOp = NextLHSI->getOperand(1);
1815 NextLHSI->setOperand(1, ExtraOperand);
1816 TmpLHSI = NextLHSI;
1817 ExtraOperand = NextOp;
1818 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001819
Chris Lattner564a7272003-08-13 19:01:45 +00001820 // Now that the instructions are reassociated, have the functor perform
1821 // the transformation...
1822 return F.apply(Root);
1823 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001824
Chris Lattner564a7272003-08-13 19:01:45 +00001825 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1826 }
1827 return 0;
1828}
1829
Dan Gohman844731a2008-05-13 00:00:25 +00001830namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001831
Nick Lewycky02d639f2008-05-23 04:34:58 +00001832// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001833struct AddRHS {
1834 Value *RHS;
1835 AddRHS(Value *rhs) : RHS(rhs) {}
1836 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1837 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001838 return BinaryOperator::CreateShl(Add.getOperand(0),
1839 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001840 }
1841};
1842
1843// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1844// iff C1&C2 == 0
1845struct AddMaskingAnd {
1846 Constant *C2;
1847 AddMaskingAnd(Constant *c) : C2(c) {}
1848 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001849 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001850 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001851 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001852 }
1853 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001854 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001855 }
1856};
1857
Dan Gohman844731a2008-05-13 00:00:25 +00001858}
1859
Chris Lattner6e7ba452005-01-01 16:22:27 +00001860static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001861 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001862 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001863 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001864 }
1865
Chris Lattner2eefe512004-04-09 19:05:30 +00001866 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001867 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1868 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001869
Chris Lattner2eefe512004-04-09 19:05:30 +00001870 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1871 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001872 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1873 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001874 }
1875
1876 Value *Op0 = SO, *Op1 = ConstOperand;
1877 if (!ConstIsRHS)
1878 std::swap(Op0, Op1);
1879 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001880 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001881 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001882 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001883 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001884 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001885 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001886 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001887 abort();
1888 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001889 return IC->InsertNewInstBefore(New, I);
1890}
1891
1892// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1893// constant as the other operand, try to fold the binary operator into the
1894// select arguments. This also works for Cast instructions, which obviously do
1895// not have a second operand.
1896static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1897 InstCombiner *IC) {
1898 // Don't modify shared select instructions
1899 if (!SI->hasOneUse()) return 0;
1900 Value *TV = SI->getOperand(1);
1901 Value *FV = SI->getOperand(2);
1902
1903 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001904 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001905 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001906
Chris Lattner6e7ba452005-01-01 16:22:27 +00001907 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1908 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1909
Gabor Greif051a9502008-04-06 20:25:17 +00001910 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1911 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 }
1913 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001914}
1915
Chris Lattner4e998b22004-09-29 05:07:12 +00001916
1917/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1918/// node as operand #0, see if we can fold the instruction into the PHI (which
1919/// is only possible if all operands to the PHI are constants).
1920Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1921 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001922 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001923 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001924
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001925 // Check to see if all of the operands of the PHI are constants. If there is
1926 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001927 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001928 BasicBlock *NonConstBB = 0;
1929 for (unsigned i = 0; i != NumPHIValues; ++i)
1930 if (!isa<Constant>(PN->getIncomingValue(i))) {
1931 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001932 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001933 NonConstBB = PN->getIncomingBlock(i);
1934
1935 // If the incoming non-constant value is in I's block, we have an infinite
1936 // loop.
1937 if (NonConstBB == I.getParent())
1938 return 0;
1939 }
1940
1941 // If there is exactly one non-constant value, we can insert a copy of the
1942 // operation in that block. However, if this is a critical edge, we would be
1943 // inserting the computation one some other paths (e.g. inside a loop). Only
1944 // do this if the pred block is unconditionally branching into the phi block.
1945 if (NonConstBB) {
1946 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1947 if (!BI || !BI->isUnconditional()) return 0;
1948 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001949
1950 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001951 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001952 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001953 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001954 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001955
1956 // Next, add all of the operands to the PHI.
1957 if (I.getNumOperands() == 2) {
1958 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001959 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001960 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001962 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1963 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1964 else
1965 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001966 } else {
1967 assert(PN->getIncomingBlock(i) == NonConstBB);
1968 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001969 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001970 PN->getIncomingValue(i), C, "phitmp",
1971 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001972 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001973 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001974 CI->getPredicate(),
1975 PN->getIncomingValue(i), C, "phitmp",
1976 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 else
1978 assert(0 && "Unknown binop!");
1979
Chris Lattnerdbab3862007-03-02 21:28:56 +00001980 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001981 }
1982 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001983 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001984 } else {
1985 CastInst *CI = cast<CastInst>(&I);
1986 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001987 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001988 Value *InV;
1989 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001990 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001991 } else {
1992 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001993 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001994 I.getType(), "phitmp",
1995 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001996 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 }
1998 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001999 }
2000 }
2001 return ReplaceInstUsesWith(I, NewPN);
2002}
2003
Chris Lattner2454a2e2008-01-29 06:52:45 +00002004
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002005/// WillNotOverflowSignedAdd - Return true if we can prove that:
2006/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2007/// This basically requires proving that the add in the original type would not
2008/// overflow to change the sign bit or have a carry out.
2009bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2010 // There are different heuristics we can use for this. Here are some simple
2011 // ones.
2012
2013 // Add has the property that adding any two 2's complement numbers can only
2014 // have one carry bit which can change a sign. As such, if LHS and RHS each
2015 // have at least two sign bits, we know that the addition of the two values will
2016 // sign extend fine.
2017 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2018 return true;
2019
2020
2021 // If one of the operands only has one non-zero bit, and if the other operand
2022 // has a known-zero bit in a more significant place than it (not including the
2023 // sign bit) the ripple may go up to and fill the zero, but won't change the
2024 // sign. For example, (X & ~4) + 1.
2025
2026 // TODO: Implement.
2027
2028 return false;
2029}
2030
Chris Lattner2454a2e2008-01-29 06:52:45 +00002031
Chris Lattner7e708292002-06-25 16:13:24 +00002032Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002033 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002034 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002035
Chris Lattner66331a42004-04-10 22:01:55 +00002036 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002037 // X + undef -> undef
2038 if (isa<UndefValue>(RHS))
2039 return ReplaceInstUsesWith(I, RHS);
2040
Chris Lattner66331a42004-04-10 22:01:55 +00002041 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002042 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002043 if (RHSC->isNullValue())
2044 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002045 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002046 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2047 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002048 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002049 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002050
Chris Lattner66331a42004-04-10 22:01:55 +00002051 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002052 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002053 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002054 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002055 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002056 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002057
2058 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2059 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002060 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2061 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002062
2063 // zext(i1) - 1 -> select i1, 0, -1
2064 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2065 if (CI->isAllOnesValue() &&
2066 ZI->getOperand(0)->getType() == Type::Int1Ty)
2067 return SelectInst::Create(ZI->getOperand(0),
2068 Constant::getNullValue(I.getType()),
2069 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002070 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002071
2072 if (isa<PHINode>(LHS))
2073 if (Instruction *NV = FoldOpIntoPhi(I))
2074 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002075
Chris Lattner4f637d42006-01-06 17:59:59 +00002076 ConstantInt *XorRHS = 0;
2077 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002078 if (isa<ConstantInt>(RHSC) &&
2079 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002080 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002081 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002082
Zhou Sheng4351c642007-04-02 08:20:41 +00002083 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002084 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2085 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002086 do {
2087 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002088 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2089 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002090 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2091 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002092 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002093 if (!MaskedValueIsZero(XorLHS,
2094 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002095 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002096 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002097 }
2098 }
2099 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002100 C0080Val = APIntOps::lshr(C0080Val, Size);
2101 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2102 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002103
Reid Spencer35c38852007-03-28 01:36:16 +00002104 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002105 // with funny bit widths then this switch statement should be removed. It
2106 // is just here to get the size of the "middle" type back up to something
2107 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002108 const Type *MiddleType = 0;
2109 switch (Size) {
2110 default: break;
2111 case 32: MiddleType = Type::Int32Ty; break;
2112 case 16: MiddleType = Type::Int16Ty; break;
2113 case 8: MiddleType = Type::Int8Ty; break;
2114 }
2115 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002116 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002117 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002118 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002119 }
2120 }
Chris Lattner66331a42004-04-10 22:01:55 +00002121 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002122
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002123 if (I.getType() == Type::Int1Ty)
2124 return BinaryOperator::CreateXor(LHS, RHS);
2125
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002126 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002127 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002128 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002129
2130 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2131 if (RHSI->getOpcode() == Instruction::Sub)
2132 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2133 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2134 }
2135 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2136 if (LHSI->getOpcode() == Instruction::Sub)
2137 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2138 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2139 }
Robert Bocchino71698282004-07-27 21:02:21 +00002140 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002141
Chris Lattner5c4afb92002-05-08 22:46:53 +00002142 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002143 // -A + -B --> -(A + B)
2144 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002145 if (LHS->getType()->isIntOrIntVector()) {
2146 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002147 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002148 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002149 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002150 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002151 }
2152
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002153 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002154 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002155
2156 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002157 if (!isa<Constant>(RHS))
2158 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002160
Misha Brukmanfd939082005-04-21 23:48:37 +00002161
Chris Lattner50af16a2004-11-13 19:50:12 +00002162 ConstantInt *C2;
2163 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2164 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002166
2167 // X*C1 + X*C2 --> X * (C1+C2)
2168 ConstantInt *C1;
2169 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002170 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002171 }
2172
2173 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002174 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002176
Chris Lattnere617c9e2007-01-05 02:17:46 +00002177 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002178 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2179 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002180
Chris Lattnerad3448c2003-02-18 19:57:07 +00002181
Chris Lattner564a7272003-08-13 19:01:45 +00002182 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002183 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002184 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2185 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002186
2187 // A+B --> A|B iff A and B have no bits set in common.
2188 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2189 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2190 APInt LHSKnownOne(IT->getBitWidth(), 0);
2191 APInt LHSKnownZero(IT->getBitWidth(), 0);
2192 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2193 if (LHSKnownZero != 0) {
2194 APInt RHSKnownOne(IT->getBitWidth(), 0);
2195 APInt RHSKnownZero(IT->getBitWidth(), 0);
2196 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2197
2198 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002199 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002200 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002201 }
2202 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002203
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002204 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002205 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002206 Value *W, *X, *Y, *Z;
2207 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2208 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2209 if (W != Y) {
2210 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002211 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002212 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002213 std::swap(W, X);
2214 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002215 std::swap(Y, Z);
2216 std::swap(W, X);
2217 }
2218 }
2219
2220 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002221 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002222 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002223 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002224 }
2225 }
2226 }
2227
Chris Lattner6b032052003-10-02 15:11:26 +00002228 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002229 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002230 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002231 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002232
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002233 // (X & FF00) + xx00 -> (X+xx00) & FF00
2234 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002235 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002236 if (Anded == CRHS) {
2237 // See if all bits from the first bit set in the Add RHS up are included
2238 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002239 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002240
2241 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002242 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002243
2244 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002245 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002246
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002247 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2248 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002249 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002250 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002251 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002252 }
2253 }
2254 }
2255
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002256 // Try to fold constant add into select arguments.
2257 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002258 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002259 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002260 }
2261
Reid Spencer1628cec2006-10-26 06:15:43 +00002262 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002263 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002264 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002265 CastInst *CI = dyn_cast<CastInst>(LHS);
2266 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002267 if (!CI) {
2268 CI = dyn_cast<CastInst>(RHS);
2269 Other = LHS;
2270 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002271 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002272 (CI->getType()->getPrimitiveSizeInBits() ==
2273 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002274 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002275 unsigned AS =
2276 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002277 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2278 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002279 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002280 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002281 }
2282 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283
Chris Lattner42790482007-12-20 01:56:58 +00002284 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002285 {
2286 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288 if (!SI) {
2289 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002290 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291 }
Chris Lattner42790482007-12-20 01:56:58 +00002292 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002293 Value *TV = SI->getTrueValue();
2294 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002295 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002296
2297 // Can we fold the add into the argument of the select?
2298 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002299 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2300 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002301 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002302 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2303 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002304 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002305 }
2306 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002307
2308 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2309 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2310 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2311 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002312
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002313 // Check for (add (sext x), y), see if we can merge this into an
2314 // integer add followed by a sext.
2315 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2316 // (add (sext x), cst) --> (sext (add x, cst'))
2317 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2318 Constant *CI =
2319 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2320 if (LHSConv->hasOneUse() &&
2321 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2322 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2323 // Insert the new, smaller add.
2324 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2325 CI, "addconv");
2326 InsertNewInstBefore(NewAdd, I);
2327 return new SExtInst(NewAdd, I.getType());
2328 }
2329 }
2330
2331 // (add (sext x), (sext y)) --> (sext (add int x, y))
2332 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2333 // Only do this if x/y have the same type, if at last one of them has a
2334 // single use (so we don't increase the number of sexts), and if the
2335 // integer add will not overflow.
2336 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2337 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2338 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2339 RHSConv->getOperand(0))) {
2340 // Insert the new integer add.
2341 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2342 RHSConv->getOperand(0),
2343 "addconv");
2344 InsertNewInstBefore(NewAdd, I);
2345 return new SExtInst(NewAdd, I.getType());
2346 }
2347 }
2348 }
2349
2350 // Check for (add double (sitofp x), y), see if we can merge this into an
2351 // integer add followed by a promotion.
2352 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2353 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2354 // ... if the constant fits in the integer value. This is useful for things
2355 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2356 // requires a constant pool load, and generally allows the add to be better
2357 // instcombined.
2358 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2359 Constant *CI =
2360 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2361 if (LHSConv->hasOneUse() &&
2362 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2363 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364 // Insert the new integer add.
2365 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2366 CI, "addconv");
2367 InsertNewInstBefore(NewAdd, I);
2368 return new SIToFPInst(NewAdd, I.getType());
2369 }
2370 }
2371
2372 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2373 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2374 // Only do this if x/y have the same type, if at last one of them has a
2375 // single use (so we don't increase the number of int->fp conversions),
2376 // and if the integer add will not overflow.
2377 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0))) {
2381 // Insert the new integer add.
2382 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2383 RHSConv->getOperand(0),
2384 "addconv");
2385 InsertNewInstBefore(NewAdd, I);
2386 return new SIToFPInst(NewAdd, I.getType());
2387 }
2388 }
2389 }
2390
Chris Lattner7e708292002-06-25 16:13:24 +00002391 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002392}
2393
Chris Lattner7e708292002-06-25 16:13:24 +00002394Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002396
Chris Lattnerd137ab42008-07-17 06:07:20 +00002397 if (Op0 == Op1 && // sub X, X -> 0
2398 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002399 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002400
Chris Lattner233f7dc2002-08-12 21:17:25 +00002401 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002402 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002403 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002404
Chris Lattnere87597f2004-10-16 18:11:37 +00002405 if (isa<UndefValue>(Op0))
2406 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2407 if (isa<UndefValue>(Op1))
2408 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2409
Chris Lattnerd65460f2003-11-05 01:06:05 +00002410 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2411 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002412 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002413 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002414
Chris Lattnerd65460f2003-11-05 01:06:05 +00002415 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002416 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002417 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002418 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002419
Chris Lattner76b7a062007-01-15 07:02:54 +00002420 // -(X >>u 31) -> (X >>s 31)
2421 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002422 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002423 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002424 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002425 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002426 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002427 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002428 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002429 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002430 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002431 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002432 }
2433 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002434 }
2435 else if (SI->getOpcode() == Instruction::AShr) {
2436 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2437 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002438 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002439 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002440 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002441 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002442 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002443 }
2444 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002445 }
2446 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002447 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002448
2449 // Try to fold constant sub into select arguments.
2450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002452 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002453 }
2454
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002455 if (I.getType() == Type::Int1Ty)
2456 return BinaryOperator::CreateXor(Op0, Op1);
2457
Chris Lattner43d84d62005-04-07 16:15:25 +00002458 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2459 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002460 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002461 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002463 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002464 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002465 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2466 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2467 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002468 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002469 Op1I->getOperand(0));
2470 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002471 }
2472
Chris Lattnerfd059242003-10-15 16:48:29 +00002473 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002474 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2475 // is not used by anyone else...
2476 //
Chris Lattner0517e722004-02-02 20:09:56 +00002477 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002478 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002479 // Swap the two operands of the subexpr...
2480 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2481 Op1I->setOperand(0, IIOp1);
2482 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002483
Chris Lattnera2881962003-02-18 19:28:33 +00002484 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002486 }
2487
2488 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2489 //
2490 if (Op1I->getOpcode() == Instruction::And &&
2491 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2492 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2493
Chris Lattnerf523d062004-06-09 05:08:07 +00002494 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002495 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2496 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002497 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002498
Reid Spencerac5209e2006-10-16 23:08:08 +00002499 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002500 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002501 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002502 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002503 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002505 ConstantExpr::getNeg(DivRHS));
2506
Chris Lattnerad3448c2003-02-18 19:57:07 +00002507 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002508 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002509 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002510 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002511 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002512 }
Chris Lattner40371712002-05-09 01:29:19 +00002513 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002514 }
Chris Lattnera2881962003-02-18 19:28:33 +00002515
Chris Lattner9919e3d2006-12-02 00:13:08 +00002516 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002517 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002518 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002519 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2520 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2521 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2522 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002523 } else if (Op0I->getOpcode() == Instruction::Sub) {
2524 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002525 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002526 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002527 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002528
Chris Lattner50af16a2004-11-13 19:50:12 +00002529 ConstantInt *C1;
2530 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002531 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002532 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002533
Chris Lattner50af16a2004-11-13 19:50:12 +00002534 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2535 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002537 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002538 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002539}
2540
Chris Lattnera0141b92007-07-15 20:42:37 +00002541/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2542/// comparison only checks the sign bit. If it only checks the sign bit, set
2543/// TrueIfSigned if the result of the comparison is true when the input value is
2544/// signed.
2545static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2546 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002547 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002548 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2549 TrueIfSigned = true;
2550 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002551 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2552 TrueIfSigned = true;
2553 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002554 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2555 TrueIfSigned = false;
2556 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002557 case ICmpInst::ICMP_UGT:
2558 // True if LHS u> RHS and RHS == high-bit-mask - 1
2559 TrueIfSigned = true;
2560 return RHS->getValue() ==
2561 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2562 case ICmpInst::ICMP_UGE:
2563 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2564 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002565 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002566 default:
2567 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002568 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002569}
2570
Chris Lattner7e708292002-06-25 16:13:24 +00002571Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002572 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002573 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002574
Chris Lattnere87597f2004-10-16 18:11:37 +00002575 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2577
Chris Lattner233f7dc2002-08-12 21:17:25 +00002578 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002579 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2580 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002581
2582 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002583 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002584 if (SI->getOpcode() == Instruction::Shl)
2585 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002586 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002587 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002588
Zhou Sheng843f07672007-04-19 05:39:12 +00002589 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002590 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2591 if (CI->equalsInt(1)) // X * 1 == X
2592 return ReplaceInstUsesWith(I, Op0);
2593 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002594 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002595
Zhou Sheng97b52c22007-03-29 01:57:21 +00002596 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002597 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002598 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002599 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002600 }
Robert Bocchino71698282004-07-27 21:02:21 +00002601 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002602 if (Op1F->isNullValue())
2603 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002604
Chris Lattnera2881962003-02-18 19:28:33 +00002605 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2606 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002607 if (Op1F->isExactlyValue(1.0))
2608 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2609 } else if (isa<VectorType>(Op1->getType())) {
2610 if (isa<ConstantAggregateZero>(Op1))
2611 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002612
2613 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2614 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2615 return BinaryOperator::CreateNeg(Op0, I.getName());
2616
2617 // As above, vector X*splat(1.0) -> X in all defined cases.
2618 if (Constant *Splat = Op1V->getSplatValue()) {
2619 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2620 if (F->isExactlyValue(1.0))
2621 return ReplaceInstUsesWith(I, Op0);
2622 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2623 if (CI->equalsInt(1))
2624 return ReplaceInstUsesWith(I, Op0);
2625 }
2626 }
Chris Lattnera2881962003-02-18 19:28:33 +00002627 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002628
2629 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2630 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002631 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002632 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002633 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002634 Op1, "tmp");
2635 InsertNewInstBefore(Add, I);
2636 Value *C1C2 = ConstantExpr::getMul(Op1,
2637 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002638 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002639
2640 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002641
2642 // Try to fold constant mul into select arguments.
2643 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002644 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002645 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002646
2647 if (isa<PHINode>(Op0))
2648 if (Instruction *NV = FoldOpIntoPhi(I))
2649 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002650 }
2651
Chris Lattnera4f445b2003-03-10 23:23:04 +00002652 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2653 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002654 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002655
Nick Lewycky0c730792008-11-21 07:33:58 +00002656 // (X / Y) * Y = X - (X % Y)
2657 // (X / Y) * -Y = (X % Y) - X
2658 {
2659 Value *Op1 = I.getOperand(1);
2660 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2661 if (!BO ||
2662 (BO->getOpcode() != Instruction::UDiv &&
2663 BO->getOpcode() != Instruction::SDiv)) {
2664 Op1 = Op0;
2665 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2666 }
2667 Value *Neg = dyn_castNegVal(Op1);
2668 if (BO && BO->hasOneUse() &&
2669 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2670 (BO->getOpcode() == Instruction::UDiv ||
2671 BO->getOpcode() == Instruction::SDiv)) {
2672 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2673
2674 Instruction *Rem;
2675 if (BO->getOpcode() == Instruction::UDiv)
2676 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2677 else
2678 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2679
2680 InsertNewInstBefore(Rem, I);
2681 Rem->takeName(BO);
2682
2683 if (Op1BO == Op1)
2684 return BinaryOperator::CreateSub(Op0BO, Rem);
2685 else
2686 return BinaryOperator::CreateSub(Rem, Op0BO);
2687 }
2688 }
2689
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002690 if (I.getType() == Type::Int1Ty)
2691 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2692
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002693 // If one of the operands of the multiply is a cast from a boolean value, then
2694 // we know the bool is either zero or one, so this is a 'masking' multiply.
2695 // See if we can simplify things based on how the boolean was originally
2696 // formed.
2697 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002698 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002699 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002700 BoolCast = CI;
2701 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002702 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002703 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002704 BoolCast = CI;
2705 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002706 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002707 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2708 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002709 bool TIS = false;
2710
Reid Spencere4d87aa2006-12-23 06:05:41 +00002711 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002712 // multiply into a shift/and combination.
2713 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002714 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2715 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002716 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002717 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002718 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002719 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002720 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002721 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002722 BoolCast->getOperand(0)->getName()+
2723 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002724
2725 // If the multiply type is not the same as the source type, sign extend
2726 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002727 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002728 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2729 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002730 Instruction::CastOps opcode =
2731 (SrcBits == DstBits ? Instruction::BitCast :
2732 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2733 V = InsertCastBefore(opcode, V, I.getType(), I);
2734 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002735
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002736 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002737 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002738 }
2739 }
2740 }
2741
Chris Lattner7e708292002-06-25 16:13:24 +00002742 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002743}
2744
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002745/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2746/// instruction.
2747bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2748 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2749
2750 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2751 int NonNullOperand = -1;
2752 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2753 if (ST->isNullValue())
2754 NonNullOperand = 2;
2755 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2756 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2757 if (ST->isNullValue())
2758 NonNullOperand = 1;
2759
2760 if (NonNullOperand == -1)
2761 return false;
2762
2763 Value *SelectCond = SI->getOperand(0);
2764
2765 // Change the div/rem to use 'Y' instead of the select.
2766 I.setOperand(1, SI->getOperand(NonNullOperand));
2767
2768 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2769 // problem. However, the select, or the condition of the select may have
2770 // multiple uses. Based on our knowledge that the operand must be non-zero,
2771 // propagate the known value for the select into other uses of it, and
2772 // propagate a known value of the condition into its other users.
2773
2774 // If the select and condition only have a single use, don't bother with this,
2775 // early exit.
2776 if (SI->use_empty() && SelectCond->hasOneUse())
2777 return true;
2778
2779 // Scan the current block backward, looking for other uses of SI.
2780 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2781
2782 while (BBI != BBFront) {
2783 --BBI;
2784 // If we found a call to a function, we can't assume it will return, so
2785 // information from below it cannot be propagated above it.
2786 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2787 break;
2788
2789 // Replace uses of the select or its condition with the known values.
2790 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2791 I != E; ++I) {
2792 if (*I == SI) {
2793 *I = SI->getOperand(NonNullOperand);
2794 AddToWorkList(BBI);
2795 } else if (*I == SelectCond) {
2796 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2797 ConstantInt::getFalse();
2798 AddToWorkList(BBI);
2799 }
2800 }
2801
2802 // If we past the instruction, quit looking for it.
2803 if (&*BBI == SI)
2804 SI = 0;
2805 if (&*BBI == SelectCond)
2806 SelectCond = 0;
2807
2808 // If we ran out of things to eliminate, break out of the loop.
2809 if (SelectCond == 0 && SI == 0)
2810 break;
2811
2812 }
2813 return true;
2814}
2815
2816
Reid Spencer1628cec2006-10-26 06:15:43 +00002817/// This function implements the transforms on div instructions that work
2818/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2819/// used by the visitors to those instructions.
2820/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002821Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002822 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002823
Chris Lattner50b2ca42008-02-19 06:12:18 +00002824 // undef / X -> 0 for integer.
2825 // undef / X -> undef for FP (the undef could be a snan).
2826 if (isa<UndefValue>(Op0)) {
2827 if (Op0->getType()->isFPOrFPVector())
2828 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002829 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002830 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002831
2832 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002833 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002834 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002835
Reid Spencer1628cec2006-10-26 06:15:43 +00002836 return 0;
2837}
Misha Brukmanfd939082005-04-21 23:48:37 +00002838
Reid Spencer1628cec2006-10-26 06:15:43 +00002839/// This function implements the transforms common to both integer division
2840/// instructions (udiv and sdiv). It is called by the visitors to those integer
2841/// division instructions.
2842/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002843Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002844 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2845
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002846 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002847 if (Op0 == Op1) {
2848 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2849 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2850 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2851 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2852 }
2853
2854 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2855 return ReplaceInstUsesWith(I, CI);
2856 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002857
Reid Spencer1628cec2006-10-26 06:15:43 +00002858 if (Instruction *Common = commonDivTransforms(I))
2859 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002860
2861 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2862 // This does not apply for fdiv.
2863 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2864 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002865
2866 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2867 // div X, 1 == X
2868 if (RHS->equalsInt(1))
2869 return ReplaceInstUsesWith(I, Op0);
2870
2871 // (X / C1) / C2 -> X / (C1*C2)
2872 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2873 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2874 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002875 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2877 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002878 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002879 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002880 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002881
Reid Spencerbca0e382007-03-23 20:05:17 +00002882 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002883 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2884 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2885 return R;
2886 if (isa<PHINode>(Op0))
2887 if (Instruction *NV = FoldOpIntoPhi(I))
2888 return NV;
2889 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002890 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002891
Chris Lattnera2881962003-02-18 19:28:33 +00002892 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002893 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002894 if (LHS->equalsInt(0))
2895 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2896
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002897 // It can't be division by zero, hence it must be division by one.
2898 if (I.getType() == Type::Int1Ty)
2899 return ReplaceInstUsesWith(I, Op0);
2900
Nick Lewycky895f0852008-11-27 20:21:08 +00002901 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2902 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2903 // div X, 1 == X
2904 if (X->isOne())
2905 return ReplaceInstUsesWith(I, Op0);
2906 }
2907
Reid Spencer1628cec2006-10-26 06:15:43 +00002908 return 0;
2909}
2910
2911Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2912 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2913
2914 // Handle the integer div common cases
2915 if (Instruction *Common = commonIDivTransforms(I))
2916 return Common;
2917
Reid Spencer1628cec2006-10-26 06:15:43 +00002918 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002919 // X udiv C^2 -> X >> C
2920 // Check to see if this is an unsigned division with an exact power of 2,
2921 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002922 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002923 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002924 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002925
2926 // X udiv C, where C >= signbit
2927 if (C->getValue().isNegative()) {
2928 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2929 I);
2930 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2931 ConstantInt::get(I.getType(), 1));
2932 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002933 }
2934
2935 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002936 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002937 if (RHSI->getOpcode() == Instruction::Shl &&
2938 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002939 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002940 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002942 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002943 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002944 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002945 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002946 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002947 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002948 }
2949 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002950 }
2951
Reid Spencer1628cec2006-10-26 06:15:43 +00002952 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2953 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002954 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002955 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002956 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002957 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002958 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002959 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002960 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002961 // Construct the "on true" case of the select
2962 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002963 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002964 Op0, TC, SI->getName()+".t");
2965 TSI = InsertNewInstBefore(TSI, I);
2966
2967 // Construct the "on false" case of the select
2968 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002969 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002970 Op0, FC, SI->getName()+".f");
2971 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002972
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002973 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002974 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002975 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002976 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002977 return 0;
2978}
2979
Reid Spencer1628cec2006-10-26 06:15:43 +00002980Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2982
2983 // Handle the integer div common cases
2984 if (Instruction *Common = commonIDivTransforms(I))
2985 return Common;
2986
2987 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2988 // sdiv X, -1 == -X
2989 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002990 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002991 }
2992
2993 // If the sign bits of both operands are zero (i.e. we can prove they are
2994 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002995 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002996 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002997 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002998 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002999 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003000 }
3001 }
3002
3003 return 0;
3004}
3005
3006Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3007 return commonDivTransforms(I);
3008}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003009
Reid Spencer0a783f72006-11-02 01:53:59 +00003010/// This function implements the transforms on rem instructions that work
3011/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3012/// is used by the visitors to those instructions.
3013/// @brief Transforms common to all three rem instructions
3014Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003016
Chris Lattner50b2ca42008-02-19 06:12:18 +00003017 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3018 if (I.getType()->isFPOrFPVector())
3019 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003020 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003021 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003022 if (isa<UndefValue>(Op1))
3023 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003024
3025 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003026 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3027 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003028
Reid Spencer0a783f72006-11-02 01:53:59 +00003029 return 0;
3030}
3031
3032/// This function implements the transforms common to both integer remainder
3033/// instructions (urem and srem). It is called by the visitors to those integer
3034/// remainder instructions.
3035/// @brief Common integer remainder transforms
3036Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039 if (Instruction *common = commonRemTransforms(I))
3040 return common;
3041
Dale Johannesened6af242009-01-21 00:35:19 +00003042 // 0 % X == 0 for integer, we don't need to preserve faults!
3043 if (Constant *LHS = dyn_cast<Constant>(Op0))
3044 if (LHS->isNullValue())
3045 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3046
Chris Lattner857e8cd2004-12-12 21:48:58 +00003047 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003048 // X % 0 == undef, we don't need to preserve faults!
3049 if (RHS->equalsInt(0))
3050 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3051
Chris Lattnera2881962003-02-18 19:28:33 +00003052 if (RHS->equalsInt(1)) // X % 1 == 0
3053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3054
Chris Lattner97943922006-02-28 05:49:21 +00003055 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3056 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3057 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3058 return R;
3059 } else if (isa<PHINode>(Op0I)) {
3060 if (Instruction *NV = FoldOpIntoPhi(I))
3061 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003062 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003063
3064 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003065 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003066 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003067 }
Chris Lattnera2881962003-02-18 19:28:33 +00003068 }
3069
Reid Spencer0a783f72006-11-02 01:53:59 +00003070 return 0;
3071}
3072
3073Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3074 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3075
3076 if (Instruction *common = commonIRemTransforms(I))
3077 return common;
3078
3079 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3080 // X urem C^2 -> X and C
3081 // Check to see if this is an unsigned remainder with an exact power of 2,
3082 // if so, convert to a bitwise and.
3083 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003084 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003086 }
3087
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003088 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003089 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3090 if (RHSI->getOpcode() == Instruction::Shl &&
3091 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003092 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003093 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003094 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003095 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003096 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003097 }
3098 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003099 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003100
Reid Spencer0a783f72006-11-02 01:53:59 +00003101 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3102 // where C1&C2 are powers of two.
3103 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3104 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3105 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3106 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003107 if ((STO->getValue().isPowerOf2()) &&
3108 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003109 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003110 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003111 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003112 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003113 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003114 }
3115 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003116 }
3117
Chris Lattner3f5b8772002-05-06 16:14:14 +00003118 return 0;
3119}
3120
Reid Spencer0a783f72006-11-02 01:53:59 +00003121Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3122 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3123
Dan Gohmancff55092007-11-05 23:16:33 +00003124 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003125 if (Instruction *common = commonIRemTransforms(I))
3126 return common;
3127
3128 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003129 if (!isa<Constant>(RHSNeg) ||
3130 (isa<ConstantInt>(RHSNeg) &&
3131 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003132 // X % -Y -> X % Y
3133 AddUsesToWorkList(I);
3134 I.setOperand(1, RHSNeg);
3135 return &I;
3136 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003137
Dan Gohmancff55092007-11-05 23:16:33 +00003138 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003139 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003140 if (I.getType()->isInteger()) {
3141 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3142 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3143 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003144 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003145 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003146 }
3147
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003148 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003149 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3150 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003151
Nick Lewycky9dce8732008-12-20 16:48:00 +00003152 bool hasNegative = false;
3153 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3154 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3155 if (RHS->getValue().isNegative())
3156 hasNegative = true;
3157
3158 if (hasNegative) {
3159 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003160 for (unsigned i = 0; i != VWidth; ++i) {
3161 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3162 if (RHS->getValue().isNegative())
3163 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3164 else
3165 Elts[i] = RHS;
3166 }
3167 }
3168
3169 Constant *NewRHSV = ConstantVector::get(Elts);
3170 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003171 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003172 I.setOperand(1, NewRHSV);
3173 return &I;
3174 }
3175 }
3176 }
3177
Reid Spencer0a783f72006-11-02 01:53:59 +00003178 return 0;
3179}
3180
3181Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003182 return commonRemTransforms(I);
3183}
3184
Chris Lattner457dd822004-06-09 07:59:58 +00003185// isOneBitSet - Return true if there is exactly one bit set in the specified
3186// constant.
3187static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003188 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003189}
3190
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003191// isHighOnes - Return true if the constant is of the form 1+0+.
3192// This is the same as lowones(~X).
3193static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003194 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003195}
3196
Reid Spencere4d87aa2006-12-23 06:05:41 +00003197/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003198/// are carefully arranged to allow folding of expressions such as:
3199///
3200/// (A < B) | (A > B) --> (A != B)
3201///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003202/// Note that this is only valid if the first and second predicates have the
3203/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003204///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003205/// Three bits are used to represent the condition, as follows:
3206/// 0 A > B
3207/// 1 A == B
3208/// 2 A < B
3209///
3210/// <=> Value Definition
3211/// 000 0 Always false
3212/// 001 1 A > B
3213/// 010 2 A == B
3214/// 011 3 A >= B
3215/// 100 4 A < B
3216/// 101 5 A != B
3217/// 110 6 A <= B
3218/// 111 7 Always true
3219///
3220static unsigned getICmpCode(const ICmpInst *ICI) {
3221 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003222 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003223 case ICmpInst::ICMP_UGT: return 1; // 001
3224 case ICmpInst::ICMP_SGT: return 1; // 001
3225 case ICmpInst::ICMP_EQ: return 2; // 010
3226 case ICmpInst::ICMP_UGE: return 3; // 011
3227 case ICmpInst::ICMP_SGE: return 3; // 011
3228 case ICmpInst::ICMP_ULT: return 4; // 100
3229 case ICmpInst::ICMP_SLT: return 4; // 100
3230 case ICmpInst::ICMP_NE: return 5; // 101
3231 case ICmpInst::ICMP_ULE: return 6; // 110
3232 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003233 // True -> 7
3234 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003235 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003236 return 0;
3237 }
3238}
3239
Evan Cheng8db90722008-10-14 17:15:11 +00003240/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3241/// predicate into a three bit mask. It also returns whether it is an ordered
3242/// predicate by reference.
3243static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3244 isOrdered = false;
3245 switch (CC) {
3246 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3247 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003248 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3249 case FCmpInst::FCMP_UGT: return 1; // 001
3250 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3251 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003252 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3253 case FCmpInst::FCMP_UGE: return 3; // 011
3254 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3255 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003256 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3257 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003258 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3259 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003260 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003261 default:
3262 // Not expecting FCMP_FALSE and FCMP_TRUE;
3263 assert(0 && "Unexpected FCmp predicate!");
3264 return 0;
3265 }
3266}
3267
Reid Spencere4d87aa2006-12-23 06:05:41 +00003268/// getICmpValue - This is the complement of getICmpCode, which turns an
3269/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003270/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003271/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003272static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3273 switch (code) {
3274 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003275 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003276 case 1:
3277 if (sign)
3278 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3279 else
3280 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3281 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3282 case 3:
3283 if (sign)
3284 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3285 else
3286 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3287 case 4:
3288 if (sign)
3289 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3290 else
3291 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3292 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3293 case 6:
3294 if (sign)
3295 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3296 else
3297 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003298 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003299 }
3300}
3301
Evan Cheng8db90722008-10-14 17:15:11 +00003302/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3303/// opcode and two operands into either a FCmp instruction. isordered is passed
3304/// in to determine which kind of predicate to use in the new fcmp instruction.
3305static Value *getFCmpValue(bool isordered, unsigned code,
3306 Value *LHS, Value *RHS) {
3307 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003308 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003309 case 0:
3310 if (isordered)
3311 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3312 else
3313 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3314 case 1:
3315 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003316 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3317 else
3318 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003319 case 2:
3320 if (isordered)
3321 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3322 else
3323 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003324 case 3:
3325 if (isordered)
3326 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3327 else
3328 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3329 case 4:
3330 if (isordered)
3331 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3332 else
3333 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3334 case 5:
3335 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003336 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3337 else
3338 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3339 case 6:
3340 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003341 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3342 else
3343 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003344 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003345 }
3346}
3347
Chris Lattnerb9553d62008-11-16 04:55:20 +00003348/// PredicatesFoldable - Return true if both predicates match sign or if at
3349/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003350static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3351 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003352 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3353 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003354}
3355
3356namespace {
3357// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3358struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003359 InstCombiner &IC;
3360 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003361 ICmpInst::Predicate pred;
3362 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3363 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3364 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003365 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3367 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003368 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3369 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003370 return false;
3371 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 Instruction *apply(Instruction &Log) const {
3373 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3374 if (ICI->getOperand(0) != LHS) {
3375 assert(ICI->getOperand(1) == LHS);
3376 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003377 }
3378
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003379 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003381 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003382 unsigned Code;
3383 switch (Log.getOpcode()) {
3384 case Instruction::And: Code = LHSCode & RHSCode; break;
3385 case Instruction::Or: Code = LHSCode | RHSCode; break;
3386 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003387 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003388 }
3389
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003390 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3391 ICmpInst::isSignedPredicate(ICI->getPredicate());
3392
3393 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003394 if (Instruction *I = dyn_cast<Instruction>(RV))
3395 return I;
3396 // Otherwise, it's a constant boolean value...
3397 return IC.ReplaceInstUsesWith(Log, RV);
3398 }
3399};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003400} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003401
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003402// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3403// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003404// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003405Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003406 ConstantInt *OpRHS,
3407 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003408 BinaryOperator &TheAnd) {
3409 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003410 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003411 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003412 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003413
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003414 switch (Op->getOpcode()) {
3415 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003416 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003417 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003419 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003420 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003421 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003422 }
3423 break;
3424 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003425 if (Together == AndRHS) // (X | C) & C --> C
3426 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003427
Chris Lattner6e7ba452005-01-01 16:22:27 +00003428 if (Op->hasOneUse() && Together != OpRHS) {
3429 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003430 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003431 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003432 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003433 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003434 }
3435 break;
3436 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003437 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003438 // Adding a one to a single bit bit-field should be turned into an XOR
3439 // of the bit. First thing to check is to see if this AND is with a
3440 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003441 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003442
3443 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003444 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003445 // Ok, at this point, we know that we are masking the result of the
3446 // ADD down to exactly one bit. If the constant we are adding has
3447 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003448 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003449
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003450 // Check to see if any bits below the one bit set in AndRHSV are set.
3451 if ((AddRHS & (AndRHSV-1)) == 0) {
3452 // If not, the only thing that can effect the output of the AND is
3453 // the bit specified by AndRHSV. If that bit is set, the effect of
3454 // the XOR is to toggle the bit. If it is clear, then the ADD has
3455 // no effect.
3456 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3457 TheAnd.setOperand(0, X);
3458 return &TheAnd;
3459 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003460 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003461 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003462 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003463 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003464 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003465 }
3466 }
3467 }
3468 }
3469 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003470
3471 case Instruction::Shl: {
3472 // We know that the AND will not produce any of the bits shifted in, so if
3473 // the anded constant includes them, clear them now!
3474 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003475 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003476 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003477 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3478 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003479
Zhou Sheng290bec52007-03-29 08:15:12 +00003480 if (CI->getValue() == ShlMask) {
3481 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003482 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3483 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003484 TheAnd.setOperand(1, CI);
3485 return &TheAnd;
3486 }
3487 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003488 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003489 case Instruction::LShr:
3490 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003491 // We know that the AND will not produce any of the bits shifted in, so if
3492 // the anded constant includes them, clear them now! This only applies to
3493 // unsigned shifts, because a signed shr may bring in set bits!
3494 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003495 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003496 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003497 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3498 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003499
Zhou Sheng290bec52007-03-29 08:15:12 +00003500 if (CI->getValue() == ShrMask) {
3501 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003502 return ReplaceInstUsesWith(TheAnd, Op);
3503 } else if (CI != AndRHS) {
3504 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3505 return &TheAnd;
3506 }
3507 break;
3508 }
3509 case Instruction::AShr:
3510 // Signed shr.
3511 // See if this is shifting in some sign extension, then masking it out
3512 // with an and.
3513 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003514 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003515 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003516 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3517 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003518 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003519 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003520 // Make the argument unsigned.
3521 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003522 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003523 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003524 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003525 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003526 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003527 }
3528 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003529 }
3530 return 0;
3531}
3532
Chris Lattner8b170942002-08-09 23:47:40 +00003533
Chris Lattnera96879a2004-09-29 17:40:11 +00003534/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3535/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003536/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3537/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003538/// insert new instructions.
3539Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003540 bool isSigned, bool Inside,
3541 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003542 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003543 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003544 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003545
Chris Lattnera96879a2004-09-29 17:40:11 +00003546 if (Inside) {
3547 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003548 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003549
Reid Spencere4d87aa2006-12-23 06:05:41 +00003550 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003551 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003552 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003553 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3554 return new ICmpInst(pred, V, Hi);
3555 }
3556
3557 // Emit V-Lo <u Hi-Lo
3558 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003559 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003560 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003561 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3562 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003563 }
3564
3565 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003567
Reid Spencere4e40032007-03-21 23:19:50 +00003568 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003569 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003570 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003571 ICmpInst::Predicate pred = (isSigned ?
3572 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3573 return new ICmpInst(pred, V, Hi);
3574 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003575
Reid Spencere4e40032007-03-21 23:19:50 +00003576 // Emit V-Lo >u Hi-1-Lo
3577 // Note that Hi has already had one subtracted from it, above.
3578 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003579 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003580 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003581 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3582 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003583}
3584
Chris Lattner7203e152005-09-18 07:22:02 +00003585// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3586// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3587// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3588// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003589static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003590 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003591 uint32_t BitWidth = Val->getType()->getBitWidth();
3592 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003593
3594 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003595 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003596 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003597 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003598 return true;
3599}
3600
Chris Lattner7203e152005-09-18 07:22:02 +00003601/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3602/// where isSub determines whether the operator is a sub. If we can fold one of
3603/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003604///
3605/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3606/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3607/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3608///
3609/// return (A +/- B).
3610///
3611Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003612 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003613 Instruction &I) {
3614 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3615 if (!LHSI || LHSI->getNumOperands() != 2 ||
3616 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3617
3618 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3619
3620 switch (LHSI->getOpcode()) {
3621 default: return 0;
3622 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003623 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003624 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003625 if ((Mask->getValue().countLeadingZeros() +
3626 Mask->getValue().countPopulation()) ==
3627 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003628 break;
3629
3630 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3631 // part, we don't need any explicit masks to take them out of A. If that
3632 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003633 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003634 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003635 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003636 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003637 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003638 break;
3639 }
3640 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003641 return 0;
3642 case Instruction::Or:
3643 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003644 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003645 if ((Mask->getValue().countLeadingZeros() +
3646 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003647 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003648 break;
3649 return 0;
3650 }
3651
3652 Instruction *New;
3653 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003654 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003655 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003656 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003657 return InsertNewInstBefore(New, I);
3658}
3659
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003660/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3661Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3662 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003663 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003664 ConstantInt *LHSCst, *RHSCst;
3665 ICmpInst::Predicate LHSCC, RHSCC;
3666
Chris Lattnerea065fb2008-11-16 05:10:52 +00003667 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003668 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003669 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003670 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003671
3672 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3673 // where C is a power of 2
3674 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3675 LHSCst->getValue().isPowerOf2()) {
3676 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3677 InsertNewInstBefore(NewOr, I);
3678 return new ICmpInst(LHSCC, NewOr, LHSCst);
3679 }
3680
3681 // From here on, we only handle:
3682 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3683 if (Val != Val2) return 0;
3684
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003685 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3686 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3687 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3688 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3689 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3690 return 0;
3691
3692 // We can't fold (ugt x, C) & (sgt x, C2).
3693 if (!PredicatesFoldable(LHSCC, RHSCC))
3694 return 0;
3695
3696 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003697 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003698 if (ICmpInst::isSignedPredicate(LHSCC) ||
3699 (ICmpInst::isEquality(LHSCC) &&
3700 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003701 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003702 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003703 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3704
3705 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003706 std::swap(LHS, RHS);
3707 std::swap(LHSCst, RHSCst);
3708 std::swap(LHSCC, RHSCC);
3709 }
3710
3711 // At this point, we know we have have two icmp instructions
3712 // comparing a value against two constants and and'ing the result
3713 // together. Because of the above check, we know that we only have
3714 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3715 // (from the FoldICmpLogical check above), that the two constants
3716 // are not equal and that the larger constant is on the RHS
3717 assert(LHSCst != RHSCst && "Compares not folded above?");
3718
3719 switch (LHSCC) {
3720 default: assert(0 && "Unknown integer condition code!");
3721 case ICmpInst::ICMP_EQ:
3722 switch (RHSCC) {
3723 default: assert(0 && "Unknown integer condition code!");
3724 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3725 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3726 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3727 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3728 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3729 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3730 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3731 return ReplaceInstUsesWith(I, LHS);
3732 }
3733 case ICmpInst::ICMP_NE:
3734 switch (RHSCC) {
3735 default: assert(0 && "Unknown integer condition code!");
3736 case ICmpInst::ICMP_ULT:
3737 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3738 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3739 break; // (X != 13 & X u< 15) -> no change
3740 case ICmpInst::ICMP_SLT:
3741 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3742 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3743 break; // (X != 13 & X s< 15) -> no change
3744 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3745 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3746 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3747 return ReplaceInstUsesWith(I, RHS);
3748 case ICmpInst::ICMP_NE:
3749 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3750 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3751 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3752 Val->getName()+".off");
3753 InsertNewInstBefore(Add, I);
3754 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3755 ConstantInt::get(Add->getType(), 1));
3756 }
3757 break; // (X != 13 & X != 15) -> no change
3758 }
3759 break;
3760 case ICmpInst::ICMP_ULT:
3761 switch (RHSCC) {
3762 default: assert(0 && "Unknown integer condition code!");
3763 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3764 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3765 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3766 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3767 break;
3768 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3769 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3770 return ReplaceInstUsesWith(I, LHS);
3771 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3772 break;
3773 }
3774 break;
3775 case ICmpInst::ICMP_SLT:
3776 switch (RHSCC) {
3777 default: assert(0 && "Unknown integer condition code!");
3778 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3779 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3780 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3781 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3782 break;
3783 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3784 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3785 return ReplaceInstUsesWith(I, LHS);
3786 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3787 break;
3788 }
3789 break;
3790 case ICmpInst::ICMP_UGT:
3791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
3793 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3794 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3795 return ReplaceInstUsesWith(I, RHS);
3796 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3797 break;
3798 case ICmpInst::ICMP_NE:
3799 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3800 return new ICmpInst(LHSCC, Val, RHSCst);
3801 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003802 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3804 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3805 break;
3806 }
3807 break;
3808 case ICmpInst::ICMP_SGT:
3809 switch (RHSCC) {
3810 default: assert(0 && "Unknown integer condition code!");
3811 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3812 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3813 return ReplaceInstUsesWith(I, RHS);
3814 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3815 break;
3816 case ICmpInst::ICMP_NE:
3817 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3818 return new ICmpInst(LHSCC, Val, RHSCst);
3819 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003820 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003821 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3822 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3823 break;
3824 }
3825 break;
3826 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003827
3828 return 0;
3829}
3830
3831
Chris Lattner7e708292002-06-25 16:13:24 +00003832Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003833 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003835
Chris Lattnere87597f2004-10-16 18:11:37 +00003836 if (isa<UndefValue>(Op1)) // X & undef -> 0
3837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3838
Chris Lattner6e7ba452005-01-01 16:22:27 +00003839 // and X, X = X
3840 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003841 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003842
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003843 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003844 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003845 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003846 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003847 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003848 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003849 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003850 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003851 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003852 } else if (isa<ConstantAggregateZero>(Op1)) {
3853 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003854 }
3855 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003856
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003857 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003858 const APInt& AndRHSMask = AndRHS->getValue();
3859 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003860
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003861 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003862 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003863 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003864 Value *Op0LHS = Op0I->getOperand(0);
3865 Value *Op0RHS = Op0I->getOperand(1);
3866 switch (Op0I->getOpcode()) {
3867 case Instruction::Xor:
3868 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003869 // If the mask is only needed on one incoming arm, push it up.
3870 if (Op0I->hasOneUse()) {
3871 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3872 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003873 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003874 Op0RHS->getName()+".masked");
3875 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003876 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003877 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003878 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003879 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003880 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3881 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003882 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003883 Op0LHS->getName()+".masked");
3884 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003885 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003886 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3887 }
3888 }
3889
Chris Lattner6e7ba452005-01-01 16:22:27 +00003890 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003891 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003892 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3893 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3894 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3895 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003896 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003897 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003898 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003899 break;
3900
3901 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003902 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3903 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3904 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3905 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003906 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003907
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003908 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3909 // has 1's for all bits that the subtraction with A might affect.
3910 if (Op0I->hasOneUse()) {
3911 uint32_t BitWidth = AndRHSMask.getBitWidth();
3912 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3913 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3914
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003915 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003916 if (!(A && A->isZero()) && // avoid infinite recursion.
3917 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003918 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3919 InsertNewInstBefore(NewNeg, I);
3920 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3921 }
3922 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003923 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003924
3925 case Instruction::Shl:
3926 case Instruction::LShr:
3927 // (1 << x) & 1 --> zext(x == 0)
3928 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003929 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003930 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3931 Constant::getNullValue(I.getType()));
3932 InsertNewInstBefore(NewICmp, I);
3933 return new ZExtInst(NewICmp, I.getType());
3934 }
3935 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003936 }
3937
Chris Lattner58403262003-07-23 19:25:52 +00003938 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003939 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003940 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003941 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003942 // If this is an integer truncation or change from signed-to-unsigned, and
3943 // if the source is an and/or with immediate, transform it. This
3944 // frequently occurs for bitfield accesses.
3945 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003946 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003947 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003948 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003949 if (CastOp->getOpcode() == Instruction::And) {
3950 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003951 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3952 // This will fold the two constants together, which may allow
3953 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003954 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003955 CastOp->getOperand(0), I.getType(),
3956 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003957 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003958 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003959 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003960 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003961 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003962 } else if (CastOp->getOpcode() == Instruction::Or) {
3963 // Change: and (cast (or X, C1) to T), C2
3964 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003965 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003966 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3967 return ReplaceInstUsesWith(I, AndRHS);
3968 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003969 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003970 }
Chris Lattner06782f82003-07-23 19:36:21 +00003971 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003972
3973 // Try to fold constant and into select arguments.
3974 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003975 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003976 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003977 if (isa<PHINode>(Op0))
3978 if (Instruction *NV = FoldOpIntoPhi(I))
3979 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003980 }
3981
Chris Lattner8d969642003-03-10 23:06:50 +00003982 Value *Op0NotVal = dyn_castNotVal(Op0);
3983 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003984
Chris Lattner5b62aa72004-06-18 06:07:51 +00003985 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3986 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3987
Misha Brukmancb6267b2004-07-30 12:50:08 +00003988 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003989 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003990 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003991 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003992 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003993 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003994 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003995
3996 {
Chris Lattner003b6202007-06-15 05:58:24 +00003997 Value *A = 0, *B = 0, *C = 0, *D = 0;
3998 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003999 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4000 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004001
4002 // (A|B) & ~(A&B) -> A^B
4003 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4004 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004005 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004006 }
4007 }
4008
4009 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004010 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4011 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004012
4013 // ~(A&B) & (A|B) -> A^B
4014 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4015 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004016 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004017 }
4018 }
Chris Lattner64daab52006-04-01 08:03:55 +00004019
4020 if (Op0->hasOneUse() &&
4021 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4022 if (A == Op1) { // (A^B)&A -> A&(A^B)
4023 I.swapOperands(); // Simplify below
4024 std::swap(Op0, Op1);
4025 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4026 cast<BinaryOperator>(Op0)->swapOperands();
4027 I.swapOperands(); // Simplify below
4028 std::swap(Op0, Op1);
4029 }
4030 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004031
Chris Lattner64daab52006-04-01 08:03:55 +00004032 if (Op1->hasOneUse() &&
4033 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4034 if (B == Op0) { // B&(A^B) -> B&(B^A)
4035 cast<BinaryOperator>(Op1)->swapOperands();
4036 std::swap(A, B);
4037 }
4038 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004039 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004040 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004041 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004042 }
4043 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004044
4045 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004046 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4047 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4048 return BinaryOperator::CreateAnd(A, Op1);
4049 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4050 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4051 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004052 }
4053
Reid Spencere4d87aa2006-12-23 06:05:41 +00004054 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4055 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4056 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004057 return R;
4058
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004059 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4060 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4061 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004062 }
4063
Chris Lattner6fc205f2006-05-05 06:39:07 +00004064 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004065 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4066 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4067 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4068 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004069 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004070 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004071 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4072 I.getType(), TD) &&
4073 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4074 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004075 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004076 Op1C->getOperand(0),
4077 I.getName());
4078 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004080 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004081 }
Chris Lattnere511b742006-11-14 07:46:50 +00004082
4083 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004084 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4085 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4086 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004087 SI0->getOperand(1) == SI1->getOperand(1) &&
4088 (SI0->hasOneUse() || SI1->hasOneUse())) {
4089 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004091 SI1->getOperand(0),
4092 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004094 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004095 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004096 }
4097
Evan Cheng8db90722008-10-14 17:15:11 +00004098 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004099 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4100 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4101 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004102 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4103 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004104 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4105 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4106 // If either of the constants are nans, then the whole thing returns
4107 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004108 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004109 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4110 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4111 RHS->getOperand(0));
4112 }
Evan Cheng8db90722008-10-14 17:15:11 +00004113 } else {
4114 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4115 FCmpInst::Predicate Op0CC, Op1CC;
4116 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4117 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004118 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4119 // Swap RHS operands to match LHS.
4120 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4121 std::swap(Op1LHS, Op1RHS);
4122 }
Evan Cheng8db90722008-10-14 17:15:11 +00004123 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4124 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4125 if (Op0CC == Op1CC)
4126 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4127 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4128 Op1CC == FCmpInst::FCMP_FALSE)
4129 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4130 else if (Op0CC == FCmpInst::FCMP_TRUE)
4131 return ReplaceInstUsesWith(I, Op1);
4132 else if (Op1CC == FCmpInst::FCMP_TRUE)
4133 return ReplaceInstUsesWith(I, Op0);
4134 bool Op0Ordered;
4135 bool Op1Ordered;
4136 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4137 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4138 if (Op1Pred == 0) {
4139 std::swap(Op0, Op1);
4140 std::swap(Op0Pred, Op1Pred);
4141 std::swap(Op0Ordered, Op1Ordered);
4142 }
4143 if (Op0Pred == 0) {
4144 // uno && ueq -> uno && (uno || eq) -> ueq
4145 // ord && olt -> ord && (ord && lt) -> olt
4146 if (Op0Ordered == Op1Ordered)
4147 return ReplaceInstUsesWith(I, Op1);
4148 // uno && oeq -> uno && (ord && eq) -> false
4149 // uno && ord -> false
4150 if (!Op0Ordered)
4151 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4152 // ord && ueq -> ord && (uno || eq) -> oeq
4153 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4154 Op0LHS, Op0RHS));
4155 }
4156 }
4157 }
4158 }
Chris Lattner99c65742007-10-24 05:38:08 +00004159 }
4160 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004161
Chris Lattner7e708292002-06-25 16:13:24 +00004162 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004163}
4164
Chris Lattner8c34cd22008-10-05 02:13:19 +00004165/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4166/// capable of providing pieces of a bswap. The subexpression provides pieces
4167/// of a bswap if it is proven that each of the non-zero bytes in the output of
4168/// the expression came from the corresponding "byte swapped" byte in some other
4169/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4170/// we know that the expression deposits the low byte of %X into the high byte
4171/// of the bswap result and that all other bytes are zero. This expression is
4172/// accepted, the high byte of ByteValues is set to X to indicate a correct
4173/// match.
4174///
4175/// This function returns true if the match was unsuccessful and false if so.
4176/// On entry to the function the "OverallLeftShift" is a signed integer value
4177/// indicating the number of bytes that the subexpression is later shifted. For
4178/// example, if the expression is later right shifted by 16 bits, the
4179/// OverallLeftShift value would be -2 on entry. This is used to specify which
4180/// byte of ByteValues is actually being set.
4181///
4182/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4183/// byte is masked to zero by a user. For example, in (X & 255), X will be
4184/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4185/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4186/// always in the local (OverallLeftShift) coordinate space.
4187///
4188static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4189 SmallVector<Value*, 8> &ByteValues) {
4190 if (Instruction *I = dyn_cast<Instruction>(V)) {
4191 // If this is an or instruction, it may be an inner node of the bswap.
4192 if (I->getOpcode() == Instruction::Or) {
4193 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4194 ByteValues) ||
4195 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4196 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004197 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004198
4199 // If this is a logical shift by a constant multiple of 8, recurse with
4200 // OverallLeftShift and ByteMask adjusted.
4201 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4202 unsigned ShAmt =
4203 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4204 // Ensure the shift amount is defined and of a byte value.
4205 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4206 return true;
4207
4208 unsigned ByteShift = ShAmt >> 3;
4209 if (I->getOpcode() == Instruction::Shl) {
4210 // X << 2 -> collect(X, +2)
4211 OverallLeftShift += ByteShift;
4212 ByteMask >>= ByteShift;
4213 } else {
4214 // X >>u 2 -> collect(X, -2)
4215 OverallLeftShift -= ByteShift;
4216 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004217 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004218 }
4219
4220 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4221 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4222
4223 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4224 ByteValues);
4225 }
4226
4227 // If this is a logical 'and' with a mask that clears bytes, clear the
4228 // corresponding bytes in ByteMask.
4229 if (I->getOpcode() == Instruction::And &&
4230 isa<ConstantInt>(I->getOperand(1))) {
4231 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4232 unsigned NumBytes = ByteValues.size();
4233 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4234 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4235
4236 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4237 // If this byte is masked out by a later operation, we don't care what
4238 // the and mask is.
4239 if ((ByteMask & (1 << i)) == 0)
4240 continue;
4241
4242 // If the AndMask is all zeros for this byte, clear the bit.
4243 APInt MaskB = AndMask & Byte;
4244 if (MaskB == 0) {
4245 ByteMask &= ~(1U << i);
4246 continue;
4247 }
4248
4249 // If the AndMask is not all ones for this byte, it's not a bytezap.
4250 if (MaskB != Byte)
4251 return true;
4252
4253 // Otherwise, this byte is kept.
4254 }
4255
4256 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4257 ByteValues);
4258 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004259 }
4260
Chris Lattner8c34cd22008-10-05 02:13:19 +00004261 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4262 // the input value to the bswap. Some observations: 1) if more than one byte
4263 // is demanded from this input, then it could not be successfully assembled
4264 // into a byteswap. At least one of the two bytes would not be aligned with
4265 // their ultimate destination.
4266 if (!isPowerOf2_32(ByteMask)) return true;
4267 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004268
Chris Lattner8c34cd22008-10-05 02:13:19 +00004269 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4270 // is demanded, it needs to go into byte 0 of the result. This means that the
4271 // byte needs to be shifted until it lands in the right byte bucket. The
4272 // shift amount depends on the position: if the byte is coming from the high
4273 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4274 // low part, it must be shifted left.
4275 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4276 if (InputByteNo < ByteValues.size()/2) {
4277 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4278 return true;
4279 } else {
4280 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4281 return true;
4282 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004283
4284 // If the destination byte value is already defined, the values are or'd
4285 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004286 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004287 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004288 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004289 return false;
4290}
4291
4292/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4293/// If so, insert the new bswap intrinsic and return it.
4294Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004295 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004296 if (!ITy || ITy->getBitWidth() % 16 ||
4297 // ByteMask only allows up to 32-byte values.
4298 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004299 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004300
4301 /// ByteValues - For each byte of the result, we keep track of which value
4302 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004303 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004304 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004305
4306 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004307 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4308 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004309 return 0;
4310
4311 // Check to see if all of the bytes come from the same value.
4312 Value *V = ByteValues[0];
4313 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4314
4315 // Check to make sure that all of the bytes come from the same value.
4316 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4317 if (ByteValues[i] != V)
4318 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004319 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004320 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004321 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004322 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004323}
4324
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004325/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4326/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4327/// we can simplify this expression to "cond ? C : D or B".
4328static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4329 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004330 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004331 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004332 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004333 return 0;
4334
Chris Lattnera6a474d2008-11-16 04:26:55 +00004335 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004336 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004337 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004338 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004339 return SelectInst::Create(Cond, C, B);
4340 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004341 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004342 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004343 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004344 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004345 return 0;
4346}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004347
Chris Lattner69d4ced2008-11-16 05:20:07 +00004348/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4349Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4350 ICmpInst *LHS, ICmpInst *RHS) {
4351 Value *Val, *Val2;
4352 ConstantInt *LHSCst, *RHSCst;
4353 ICmpInst::Predicate LHSCC, RHSCC;
4354
4355 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4356 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4357 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4358 return 0;
4359
4360 // From here on, we only handle:
4361 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4362 if (Val != Val2) return 0;
4363
4364 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4365 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4366 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4367 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4368 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4369 return 0;
4370
4371 // We can't fold (ugt x, C) | (sgt x, C2).
4372 if (!PredicatesFoldable(LHSCC, RHSCC))
4373 return 0;
4374
4375 // Ensure that the larger constant is on the RHS.
4376 bool ShouldSwap;
4377 if (ICmpInst::isSignedPredicate(LHSCC) ||
4378 (ICmpInst::isEquality(LHSCC) &&
4379 ICmpInst::isSignedPredicate(RHSCC)))
4380 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4381 else
4382 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4383
4384 if (ShouldSwap) {
4385 std::swap(LHS, RHS);
4386 std::swap(LHSCst, RHSCst);
4387 std::swap(LHSCC, RHSCC);
4388 }
4389
4390 // At this point, we know we have have two icmp instructions
4391 // comparing a value against two constants and or'ing the result
4392 // together. Because of the above check, we know that we only have
4393 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4394 // FoldICmpLogical check above), that the two constants are not
4395 // equal.
4396 assert(LHSCst != RHSCst && "Compares not folded above?");
4397
4398 switch (LHSCC) {
4399 default: assert(0 && "Unknown integer condition code!");
4400 case ICmpInst::ICMP_EQ:
4401 switch (RHSCC) {
4402 default: assert(0 && "Unknown integer condition code!");
4403 case ICmpInst::ICMP_EQ:
4404 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4405 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4406 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4407 Val->getName()+".off");
4408 InsertNewInstBefore(Add, I);
4409 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4410 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4411 }
4412 break; // (X == 13 | X == 15) -> no change
4413 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4414 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4415 break;
4416 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4417 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4418 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4419 return ReplaceInstUsesWith(I, RHS);
4420 }
4421 break;
4422 case ICmpInst::ICMP_NE:
4423 switch (RHSCC) {
4424 default: assert(0 && "Unknown integer condition code!");
4425 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4426 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4427 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4428 return ReplaceInstUsesWith(I, LHS);
4429 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4430 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4431 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4432 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4433 }
4434 break;
4435 case ICmpInst::ICMP_ULT:
4436 switch (RHSCC) {
4437 default: assert(0 && "Unknown integer condition code!");
4438 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4439 break;
4440 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4441 // If RHSCst is [us]MAXINT, it is always false. Not handling
4442 // this can cause overflow.
4443 if (RHSCst->isMaxValue(false))
4444 return ReplaceInstUsesWith(I, LHS);
4445 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4446 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4447 break;
4448 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4449 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4450 return ReplaceInstUsesWith(I, RHS);
4451 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4452 break;
4453 }
4454 break;
4455 case ICmpInst::ICMP_SLT:
4456 switch (RHSCC) {
4457 default: assert(0 && "Unknown integer condition code!");
4458 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4459 break;
4460 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4461 // If RHSCst is [us]MAXINT, it is always false. Not handling
4462 // this can cause overflow.
4463 if (RHSCst->isMaxValue(true))
4464 return ReplaceInstUsesWith(I, LHS);
4465 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4466 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4467 break;
4468 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4469 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4470 return ReplaceInstUsesWith(I, RHS);
4471 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4472 break;
4473 }
4474 break;
4475 case ICmpInst::ICMP_UGT:
4476 switch (RHSCC) {
4477 default: assert(0 && "Unknown integer condition code!");
4478 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4479 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4480 return ReplaceInstUsesWith(I, LHS);
4481 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4482 break;
4483 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4484 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4485 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4486 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4487 break;
4488 }
4489 break;
4490 case ICmpInst::ICMP_SGT:
4491 switch (RHSCC) {
4492 default: assert(0 && "Unknown integer condition code!");
4493 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4494 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4495 return ReplaceInstUsesWith(I, LHS);
4496 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4497 break;
4498 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4499 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4500 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4501 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4502 break;
4503 }
4504 break;
4505 }
4506 return 0;
4507}
4508
Bill Wendlinga698a472008-12-01 08:23:25 +00004509/// FoldOrWithConstants - This helper function folds:
4510///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004511/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004512///
4513/// into:
4514///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004515/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004516///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004517/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004518Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004519 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004520 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4521 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004522
Bill Wendling286a0542008-12-02 06:24:20 +00004523 Value *V1 = 0;
4524 ConstantInt *CI2 = 0;
4525 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004526
Bill Wendling29976b92008-12-02 06:18:11 +00004527 APInt Xor = CI1->getValue() ^ CI2->getValue();
4528 if (!Xor.isAllOnesValue()) return 0;
4529
Bill Wendling286a0542008-12-02 06:24:20 +00004530 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004531 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004532 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4533 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004534 }
4535
4536 return 0;
4537}
4538
Chris Lattner7e708292002-06-25 16:13:24 +00004539Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004540 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004541 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004542
Chris Lattner42593e62007-03-24 23:56:43 +00004543 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004544 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004545
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004546 // or X, X = X
4547 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004548 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004549
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004550 // See if we can simplify any instructions used by the instruction whose sole
4551 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004552 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004553 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004554 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004555 } else if (isa<ConstantAggregateZero>(Op1)) {
4556 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4557 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4558 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4559 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004560 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004561
4562
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004563
Chris Lattner3f5b8772002-05-06 16:14:14 +00004564 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004566 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004567 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4568 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004569 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004570 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004571 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004572 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004573 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004574 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004575
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004576 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4577 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004578 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004579 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004580 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004581 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004582 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004583 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004584
4585 // Try to fold constant and into select arguments.
4586 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004587 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004588 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004589 if (isa<PHINode>(Op0))
4590 if (Instruction *NV = FoldOpIntoPhi(I))
4591 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004592 }
4593
Chris Lattner4f637d42006-01-06 17:59:59 +00004594 Value *A = 0, *B = 0;
4595 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004596
4597 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4598 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4599 return ReplaceInstUsesWith(I, Op1);
4600 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4601 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4602 return ReplaceInstUsesWith(I, Op0);
4603
Chris Lattner6423d4c2006-07-10 20:25:24 +00004604 // (A | B) | C and A | (B | C) -> bswap if possible.
4605 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004606 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004607 match(Op1, m_Or(m_Value(), m_Value())) ||
4608 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4609 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004610 if (Instruction *BSwap = MatchBSwap(I))
4611 return BSwap;
4612 }
4613
Chris Lattner6e4c6492005-05-09 04:58:36 +00004614 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4615 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004616 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004617 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004618 InsertNewInstBefore(NOr, I);
4619 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004620 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004621 }
4622
4623 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4624 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004625 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004626 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004627 InsertNewInstBefore(NOr, I);
4628 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004629 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004630 }
4631
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004632 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004633 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004634 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4635 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004636 Value *V1 = 0, *V2 = 0, *V3 = 0;
4637 C1 = dyn_cast<ConstantInt>(C);
4638 C2 = dyn_cast<ConstantInt>(D);
4639 if (C1 && C2) { // (A & C1)|(B & C2)
4640 // If we have: ((V + N) & C1) | (V & C2)
4641 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4642 // replace with V+N.
4643 if (C1->getValue() == ~C2->getValue()) {
4644 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4645 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4646 // Add commutes, try both ways.
4647 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4648 return ReplaceInstUsesWith(I, A);
4649 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4650 return ReplaceInstUsesWith(I, A);
4651 }
4652 // Or commutes, try both ways.
4653 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4654 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4655 // Add commutes, try both ways.
4656 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4657 return ReplaceInstUsesWith(I, B);
4658 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4659 return ReplaceInstUsesWith(I, B);
4660 }
4661 }
Chris Lattner044e5332007-04-08 08:01:49 +00004662 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004663 }
4664
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004665 // Check to see if we have any common things being and'ed. If so, find the
4666 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004667 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4668 if (A == B) // (A & C)|(A & D) == A & (C|D)
4669 V1 = A, V2 = C, V3 = D;
4670 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4671 V1 = A, V2 = B, V3 = C;
4672 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4673 V1 = C, V2 = A, V3 = D;
4674 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4675 V1 = C, V2 = A, V3 = B;
4676
4677 if (V1) {
4678 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004679 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4680 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004681 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004682 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004683
Dan Gohman1975d032008-10-30 20:40:10 +00004684 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004685 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4686 return Match;
4687 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4688 return Match;
4689 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4690 return Match;
4691 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4692 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004693
Bill Wendlingb01865c2008-11-30 13:52:49 +00004694 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004695 if ((match(C, m_Not(m_Specific(D))) &&
4696 match(B, m_Not(m_Specific(A)))))
4697 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004698 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004699 if ((match(A, m_Not(m_Specific(D))) &&
4700 match(B, m_Not(m_Specific(C)))))
4701 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004702 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004703 if ((match(C, m_Not(m_Specific(B))) &&
4704 match(D, m_Not(m_Specific(A)))))
4705 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004706 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004707 if ((match(A, m_Not(m_Specific(B))) &&
4708 match(D, m_Not(m_Specific(C)))))
4709 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004710 }
Chris Lattnere511b742006-11-14 07:46:50 +00004711
4712 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004713 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4714 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4715 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004716 SI0->getOperand(1) == SI1->getOperand(1) &&
4717 (SI0->hasOneUse() || SI1->hasOneUse())) {
4718 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004720 SI1->getOperand(0),
4721 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004722 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004723 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004724 }
4725 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004726
Bill Wendlingb3833d12008-12-01 01:07:11 +00004727 // ((A|B)&1)|(B&-2) -> (A&1) | B
4728 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4729 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004730 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004731 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004732 }
4733 // (B&-2)|((A|B)&1) -> (A&1) | B
4734 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4735 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004736 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004737 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004738 }
4739
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004740 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4741 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004742 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004743 } else {
4744 A = 0;
4745 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004746 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004747 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4748 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004749 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004750
Misha Brukmancb6267b2004-07-30 12:50:08 +00004751 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004752 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004753 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004754 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004756 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004757 }
Chris Lattnera2881962003-02-18 19:28:33 +00004758
Reid Spencere4d87aa2006-12-23 06:05:41 +00004759 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4760 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4761 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004762 return R;
4763
Chris Lattner69d4ced2008-11-16 05:20:07 +00004764 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4765 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4766 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004767 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004768
4769 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004770 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004771 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004772 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004773 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4774 !isa<ICmpInst>(Op1C->getOperand(0))) {
4775 const Type *SrcTy = Op0C->getOperand(0)->getType();
4776 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4777 // Only do this if the casts both really cause code to be
4778 // generated.
4779 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4780 I.getType(), TD) &&
4781 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4782 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004783 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004784 Op1C->getOperand(0),
4785 I.getName());
4786 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004787 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004788 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004789 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004790 }
Chris Lattner99c65742007-10-24 05:38:08 +00004791 }
4792
4793
4794 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4795 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4796 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4797 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004798 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004799 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004800 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4801 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4802 // If either of the constants are nans, then the whole thing returns
4803 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004804 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004805 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4806
4807 // Otherwise, no need to compare the two constants, compare the
4808 // rest.
4809 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4810 RHS->getOperand(0));
4811 }
Evan Cheng40300622008-10-14 18:44:08 +00004812 } else {
4813 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4814 FCmpInst::Predicate Op0CC, Op1CC;
4815 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4816 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4817 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4818 // Swap RHS operands to match LHS.
4819 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4820 std::swap(Op1LHS, Op1RHS);
4821 }
4822 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4823 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4824 if (Op0CC == Op1CC)
4825 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4826 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4827 Op1CC == FCmpInst::FCMP_TRUE)
4828 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4829 else if (Op0CC == FCmpInst::FCMP_FALSE)
4830 return ReplaceInstUsesWith(I, Op1);
4831 else if (Op1CC == FCmpInst::FCMP_FALSE)
4832 return ReplaceInstUsesWith(I, Op0);
4833 bool Op0Ordered;
4834 bool Op1Ordered;
4835 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4836 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4837 if (Op0Ordered == Op1Ordered) {
4838 // If both are ordered or unordered, return a new fcmp with
4839 // or'ed predicates.
4840 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4841 Op0LHS, Op0RHS);
4842 if (Instruction *I = dyn_cast<Instruction>(RV))
4843 return I;
4844 // Otherwise, it's a constant boolean value...
4845 return ReplaceInstUsesWith(I, RV);
4846 }
4847 }
4848 }
4849 }
Chris Lattner99c65742007-10-24 05:38:08 +00004850 }
4851 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004852
Chris Lattner7e708292002-06-25 16:13:24 +00004853 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004854}
4855
Dan Gohman844731a2008-05-13 00:00:25 +00004856namespace {
4857
Chris Lattnerc317d392004-02-16 01:20:27 +00004858// XorSelf - Implements: X ^ X --> 0
4859struct XorSelf {
4860 Value *RHS;
4861 XorSelf(Value *rhs) : RHS(rhs) {}
4862 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4863 Instruction *apply(BinaryOperator &Xor) const {
4864 return &Xor;
4865 }
4866};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004867
Dan Gohman844731a2008-05-13 00:00:25 +00004868}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004869
Chris Lattner7e708292002-06-25 16:13:24 +00004870Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004871 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004872 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004873
Evan Chengd34af782008-03-25 20:07:13 +00004874 if (isa<UndefValue>(Op1)) {
4875 if (isa<UndefValue>(Op0))
4876 // Handle undef ^ undef -> 0 special case. This is a common
4877 // idiom (misuse).
4878 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004879 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004880 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004881
Chris Lattnerc317d392004-02-16 01:20:27 +00004882 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4883 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004884 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004886 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004887
4888 // See if we can simplify any instructions used by the instruction whose sole
4889 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004890 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004891 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004892 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004893 } else if (isa<ConstantAggregateZero>(Op1)) {
4894 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004895 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004896
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004897 // Is this a ~ operation?
4898 if (Value *NotOp = dyn_castNotVal(&I)) {
4899 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4900 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4901 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4902 if (Op0I->getOpcode() == Instruction::And ||
4903 Op0I->getOpcode() == Instruction::Or) {
4904 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4905 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4906 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004907 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004908 Op0I->getOperand(1)->getName()+".not");
4909 InsertNewInstBefore(NotY, I);
4910 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004911 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004912 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004913 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004914 }
4915 }
4916 }
4917 }
4918
4919
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004920 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004921 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004922 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004923 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004924 return new ICmpInst(ICI->getInversePredicate(),
4925 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004926
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004927 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4928 return new FCmpInst(FCI->getInversePredicate(),
4929 FCI->getOperand(0), FCI->getOperand(1));
4930 }
4931
Nick Lewycky517e1f52008-05-31 19:01:33 +00004932 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4933 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4934 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4935 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4936 Instruction::CastOps Opcode = Op0C->getOpcode();
4937 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4938 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4939 Op0C->getDestTy())) {
4940 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4941 CI->getOpcode(), CI->getInversePredicate(),
4942 CI->getOperand(0), CI->getOperand(1)), I);
4943 NewCI->takeName(CI);
4944 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4945 }
4946 }
4947 }
4948 }
4949 }
4950
Reid Spencere4d87aa2006-12-23 06:05:41 +00004951 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004952 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004953 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4954 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004955 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4956 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004957 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004958 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004959 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004960
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004961 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004962 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004963 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004964 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004965 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004966 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004967 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004968 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004969 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004970 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004971 // (X + C) ^ signbit -> (X + C + signbit)
4972 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004973 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004974
Chris Lattner7c4049c2004-01-12 19:35:11 +00004975 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004976 } else if (Op0I->getOpcode() == Instruction::Or) {
4977 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004978 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004979 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4980 // Anything in both C1 and C2 is known to be zero, remove it from
4981 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004982 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004983 NewRHS = ConstantExpr::getAnd(NewRHS,
4984 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004985 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004986 I.setOperand(0, Op0I->getOperand(0));
4987 I.setOperand(1, NewRHS);
4988 return &I;
4989 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004990 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004991 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004992 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004993
4994 // Try to fold constant and into select arguments.
4995 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004996 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004997 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004998 if (isa<PHINode>(Op0))
4999 if (Instruction *NV = FoldOpIntoPhi(I))
5000 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005001 }
5002
Chris Lattner8d969642003-03-10 23:06:50 +00005003 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005004 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005005 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005006
Chris Lattner8d969642003-03-10 23:06:50 +00005007 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005008 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005009 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005010
Chris Lattner318bf792007-03-18 22:51:34 +00005011
5012 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5013 if (Op1I) {
5014 Value *A, *B;
5015 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5016 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005017 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005018 I.swapOperands();
5019 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005020 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005021 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005022 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005023 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005024 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5025 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5026 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5027 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005028 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005029 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005030 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005031 std::swap(A, B);
5032 }
Chris Lattner318bf792007-03-18 22:51:34 +00005033 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005034 I.swapOperands(); // Simplified below.
5035 std::swap(Op0, Op1);
5036 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005037 }
Chris Lattner318bf792007-03-18 22:51:34 +00005038 }
5039
5040 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5041 if (Op0I) {
5042 Value *A, *B;
5043 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5044 if (A == Op1) // (B|A)^B == (A|B)^B
5045 std::swap(A, B);
5046 if (B == Op1) { // (A|B)^B == A & ~B
5047 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005048 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5049 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005050 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005051 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5052 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5053 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5054 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005055 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5056 if (A == Op1) // (A&B)^A -> (B&A)^A
5057 std::swap(A, B);
5058 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005059 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005060 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005061 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5062 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005063 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005064 }
Chris Lattner318bf792007-03-18 22:51:34 +00005065 }
5066
5067 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5068 if (Op0I && Op1I && Op0I->isShift() &&
5069 Op0I->getOpcode() == Op1I->getOpcode() &&
5070 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5071 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5072 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005073 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005074 Op1I->getOperand(0),
5075 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005076 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005077 Op1I->getOperand(1));
5078 }
5079
5080 if (Op0I && Op1I) {
5081 Value *A, *B, *C, *D;
5082 // (A & B)^(A | B) -> A ^ B
5083 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5084 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5085 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005086 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005087 }
5088 // (A | B)^(A & B) -> A ^ B
5089 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5090 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5091 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005092 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005093 }
5094
5095 // (A & B)^(C & D)
5096 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5097 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5098 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5099 // (X & Y)^(X & Y) -> (Y^Z) & X
5100 Value *X = 0, *Y = 0, *Z = 0;
5101 if (A == C)
5102 X = A, Y = B, Z = D;
5103 else if (A == D)
5104 X = A, Y = B, Z = C;
5105 else if (B == C)
5106 X = B, Y = A, Z = D;
5107 else if (B == D)
5108 X = B, Y = A, Z = C;
5109
5110 if (X) {
5111 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005112 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5113 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005114 }
5115 }
5116 }
5117
Reid Spencere4d87aa2006-12-23 06:05:41 +00005118 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5119 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5120 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005121 return R;
5122
Chris Lattner6fc205f2006-05-05 06:39:07 +00005123 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005124 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005125 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005126 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5127 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005128 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005129 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005130 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5131 I.getType(), TD) &&
5132 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5133 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005134 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005135 Op1C->getOperand(0),
5136 I.getName());
5137 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005138 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005139 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005140 }
Chris Lattner99c65742007-10-24 05:38:08 +00005141 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005142
Chris Lattner7e708292002-06-25 16:13:24 +00005143 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005144}
5145
Chris Lattnera96879a2004-09-29 17:40:11 +00005146/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5147/// overflowed for this type.
5148static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005149 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005150 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005151
Reid Spencere4e40032007-03-21 23:19:50 +00005152 if (IsSigned)
5153 if (In2->getValue().isNegative())
5154 return Result->getValue().sgt(In1->getValue());
5155 else
5156 return Result->getValue().slt(In1->getValue());
5157 else
5158 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005159}
5160
Dan Gohman1df3fd62008-09-10 23:30:57 +00005161/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5162/// overflowed for this type.
5163static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5164 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005165 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005166
5167 if (IsSigned)
5168 if (In2->getValue().isNegative())
5169 return Result->getValue().slt(In1->getValue());
5170 else
5171 return Result->getValue().sgt(In1->getValue());
5172 else
5173 return Result->getValue().ugt(In1->getValue());
5174}
5175
Chris Lattner574da9b2005-01-13 20:14:25 +00005176/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5177/// code necessary to compute the offset from the base pointer (without adding
5178/// in the base pointer). Return the result as a signed integer of intptr size.
5179static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5180 TargetData &TD = IC.getTargetData();
5181 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 const Type *IntPtrTy = TD.getIntPtrType();
5183 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005184
5185 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005186 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005187 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005188
Gabor Greif177dd3f2008-06-12 21:37:33 +00005189 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5190 ++i, ++GTI) {
5191 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005192 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005193 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5194 if (OpC->isZero()) continue;
5195
5196 // Handle a struct index, which adds its field offset to the pointer.
5197 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5198 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5199
5200 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5201 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005202 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005203 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005204 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005205 ConstantInt::get(IntPtrTy, Size),
5206 GEP->getName()+".offs"), I);
5207 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005208 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005209
5210 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5211 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5212 Scale = ConstantExpr::getMul(OC, Scale);
5213 if (Constant *RC = dyn_cast<Constant>(Result))
5214 Result = ConstantExpr::getAdd(RC, Scale);
5215 else {
5216 // Emit an add instruction.
5217 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005218 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005219 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005220 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005221 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005222 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005223 // Convert to correct type.
5224 if (Op->getType() != IntPtrTy) {
5225 if (Constant *OpC = dyn_cast<Constant>(Op))
5226 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5227 else
5228 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5229 Op->getName()+".c"), I);
5230 }
5231 if (Size != 1) {
5232 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5233 if (Constant *OpC = dyn_cast<Constant>(Op))
5234 Op = ConstantExpr::getMul(OpC, Scale);
5235 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005236 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005237 GEP->getName()+".idx"), I);
5238 }
5239
5240 // Emit an add instruction.
5241 if (isa<Constant>(Op) && isa<Constant>(Result))
5242 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5243 cast<Constant>(Result));
5244 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005245 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005246 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005247 }
5248 return Result;
5249}
5250
Chris Lattner10c0d912008-04-22 02:53:33 +00005251
5252/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5253/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5254/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5255/// complex, and scales are involved. The above expression would also be legal
5256/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5257/// later form is less amenable to optimization though, and we are allowed to
5258/// generate the first by knowing that pointer arithmetic doesn't overflow.
5259///
5260/// If we can't emit an optimized form for this expression, this returns null.
5261///
5262static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5263 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005264 TargetData &TD = IC.getTargetData();
5265 gep_type_iterator GTI = gep_type_begin(GEP);
5266
5267 // Check to see if this gep only has a single variable index. If so, and if
5268 // any constant indices are a multiple of its scale, then we can compute this
5269 // in terms of the scale of the variable index. For example, if the GEP
5270 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5271 // because the expression will cross zero at the same point.
5272 unsigned i, e = GEP->getNumOperands();
5273 int64_t Offset = 0;
5274 for (i = 1; i != e; ++i, ++GTI) {
5275 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5276 // Compute the aggregate offset of constant indices.
5277 if (CI->isZero()) continue;
5278
5279 // Handle a struct index, which adds its field offset to the pointer.
5280 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5281 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5282 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005283 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005284 Offset += Size*CI->getSExtValue();
5285 }
5286 } else {
5287 // Found our variable index.
5288 break;
5289 }
5290 }
5291
5292 // If there are no variable indices, we must have a constant offset, just
5293 // evaluate it the general way.
5294 if (i == e) return 0;
5295
5296 Value *VariableIdx = GEP->getOperand(i);
5297 // Determine the scale factor of the variable element. For example, this is
5298 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005299 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005300
5301 // Verify that there are no other variable indices. If so, emit the hard way.
5302 for (++i, ++GTI; i != e; ++i, ++GTI) {
5303 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5304 if (!CI) return 0;
5305
5306 // Compute the aggregate offset of constant indices.
5307 if (CI->isZero()) continue;
5308
5309 // Handle a struct index, which adds its field offset to the pointer.
5310 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5311 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5312 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005313 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005314 Offset += Size*CI->getSExtValue();
5315 }
5316 }
5317
5318 // Okay, we know we have a single variable index, which must be a
5319 // pointer/array/vector index. If there is no offset, life is simple, return
5320 // the index.
5321 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5322 if (Offset == 0) {
5323 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5324 // we don't need to bother extending: the extension won't affect where the
5325 // computation crosses zero.
5326 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5327 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5328 VariableIdx->getNameStart(), &I);
5329 return VariableIdx;
5330 }
5331
5332 // Otherwise, there is an index. The computation we will do will be modulo
5333 // the pointer size, so get it.
5334 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5335
5336 Offset &= PtrSizeMask;
5337 VariableScale &= PtrSizeMask;
5338
5339 // To do this transformation, any constant index must be a multiple of the
5340 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5341 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5342 // multiple of the variable scale.
5343 int64_t NewOffs = Offset / (int64_t)VariableScale;
5344 if (Offset != NewOffs*(int64_t)VariableScale)
5345 return 0;
5346
5347 // Okay, we can do this evaluation. Start by converting the index to intptr.
5348 const Type *IntPtrTy = TD.getIntPtrType();
5349 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005350 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005351 true /*SExt*/,
5352 VariableIdx->getNameStart(), &I);
5353 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005354 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005355}
5356
5357
Reid Spencere4d87aa2006-12-23 06:05:41 +00005358/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005359/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005360Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5361 ICmpInst::Predicate Cond,
5362 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005363 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005364
Chris Lattner10c0d912008-04-22 02:53:33 +00005365 // Look through bitcasts.
5366 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5367 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005368
Chris Lattner574da9b2005-01-13 20:14:25 +00005369 Value *PtrBase = GEPLHS->getOperand(0);
5370 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005371 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005372 // This transformation (ignoring the base and scales) is valid because we
5373 // know pointers can't overflow. See if we can output an optimized form.
5374 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5375
5376 // If not, synthesize the offset the hard way.
5377 if (Offset == 0)
5378 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005379 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5380 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005381 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005382 // If the base pointers are different, but the indices are the same, just
5383 // compare the base pointer.
5384 if (PtrBase != GEPRHS->getOperand(0)) {
5385 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005386 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005387 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005388 if (IndicesTheSame)
5389 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5390 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5391 IndicesTheSame = false;
5392 break;
5393 }
5394
5395 // If all indices are the same, just compare the base pointers.
5396 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005397 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5398 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005399
5400 // Otherwise, the base pointers are different and the indices are
5401 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005402 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005403 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005404
Chris Lattnere9d782b2005-01-13 22:25:21 +00005405 // If one of the GEPs has all zero indices, recurse.
5406 bool AllZeros = true;
5407 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5408 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5409 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5410 AllZeros = false;
5411 break;
5412 }
5413 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005414 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5415 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005416
5417 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005418 AllZeros = true;
5419 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5420 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5421 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5422 AllZeros = false;
5423 break;
5424 }
5425 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005426 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005427
Chris Lattner4401c9c2005-01-14 00:20:05 +00005428 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5429 // If the GEPs only differ by one index, compare it.
5430 unsigned NumDifferences = 0; // Keep track of # differences.
5431 unsigned DiffOperand = 0; // The operand that differs.
5432 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5433 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005434 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5435 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005436 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005437 NumDifferences = 2;
5438 break;
5439 } else {
5440 if (NumDifferences++) break;
5441 DiffOperand = i;
5442 }
5443 }
5444
5445 if (NumDifferences == 0) // SAME GEP?
5446 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005447 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005448 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005449
Chris Lattner4401c9c2005-01-14 00:20:05 +00005450 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005451 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5452 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005453 // Make sure we do a signed comparison here.
5454 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005455 }
5456 }
5457
Reid Spencere4d87aa2006-12-23 06:05:41 +00005458 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005459 // the result to fold to a constant!
5460 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5461 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5462 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5463 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5464 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005465 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005466 }
5467 }
5468 return 0;
5469}
5470
Chris Lattnera5406232008-05-19 20:18:56 +00005471/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5472///
5473Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5474 Instruction *LHSI,
5475 Constant *RHSC) {
5476 if (!isa<ConstantFP>(RHSC)) return 0;
5477 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5478
5479 // Get the width of the mantissa. We don't want to hack on conversions that
5480 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005481 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005482 if (MantissaWidth == -1) return 0; // Unknown.
5483
5484 // Check to see that the input is converted from an integer type that is small
5485 // enough that preserves all bits. TODO: check here for "known" sign bits.
5486 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5487 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5488
5489 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005490 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5491 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005492 ++InputSize;
5493
5494 // If the conversion would lose info, don't hack on this.
5495 if ((int)InputSize > MantissaWidth)
5496 return 0;
5497
5498 // Otherwise, we can potentially simplify the comparison. We know that it
5499 // will always come through as an integer value and we know the constant is
5500 // not a NAN (it would have been previously simplified).
5501 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5502
5503 ICmpInst::Predicate Pred;
5504 switch (I.getPredicate()) {
5505 default: assert(0 && "Unexpected predicate!");
5506 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005507 case FCmpInst::FCMP_OEQ:
5508 Pred = ICmpInst::ICMP_EQ;
5509 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005510 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005511 case FCmpInst::FCMP_OGT:
5512 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5513 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005514 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005515 case FCmpInst::FCMP_OGE:
5516 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5517 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005518 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005519 case FCmpInst::FCMP_OLT:
5520 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5521 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005522 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005523 case FCmpInst::FCMP_OLE:
5524 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5525 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005526 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005527 case FCmpInst::FCMP_ONE:
5528 Pred = ICmpInst::ICMP_NE;
5529 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005530 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005531 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005532 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005533 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005534 }
5535
5536 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5537
5538 // Now we know that the APFloat is a normal number, zero or inf.
5539
Chris Lattner85162782008-05-20 03:50:52 +00005540 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005541 // comparing an i8 to 300.0.
5542 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5543
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005544 if (!LHSUnsigned) {
5545 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5546 // and large values.
5547 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5548 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5549 APFloat::rmNearestTiesToEven);
5550 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5551 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5552 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005553 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5554 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005555 }
5556 } else {
5557 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5558 // +INF and large values.
5559 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5560 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5561 APFloat::rmNearestTiesToEven);
5562 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5563 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5564 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005565 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5566 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005567 }
Chris Lattnera5406232008-05-19 20:18:56 +00005568 }
5569
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005570 if (!LHSUnsigned) {
5571 // See if the RHS value is < SignedMin.
5572 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5573 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5574 APFloat::rmNearestTiesToEven);
5575 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5576 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5577 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005578 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5579 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005580 }
Chris Lattnera5406232008-05-19 20:18:56 +00005581 }
5582
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005583 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5584 // [0, UMAX], but it may still be fractional. See if it is fractional by
5585 // casting the FP value to the integer value and back, checking for equality.
5586 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005587 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5588 if (!RHS.isZero() &&
5589 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005590 // If we had a comparison against a fractional value, we have to adjust the
5591 // compare predicate and sometimes the value. RHSC is rounded towards zero
5592 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005593 switch (Pred) {
5594 default: assert(0 && "Unexpected integer comparison!");
5595 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005597 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005598 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005599 case ICmpInst::ICMP_ULE:
5600 // (float)int <= 4.4 --> int <= 4
5601 // (float)int <= -4.4 --> false
5602 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005603 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005604 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005605 case ICmpInst::ICMP_SLE:
5606 // (float)int <= 4.4 --> int <= 4
5607 // (float)int <= -4.4 --> int < -4
5608 if (RHS.isNegative())
5609 Pred = ICmpInst::ICMP_SLT;
5610 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005611 case ICmpInst::ICMP_ULT:
5612 // (float)int < -4.4 --> false
5613 // (float)int < 4.4 --> int <= 4
5614 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005615 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005616 Pred = ICmpInst::ICMP_ULE;
5617 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005618 case ICmpInst::ICMP_SLT:
5619 // (float)int < -4.4 --> int < -4
5620 // (float)int < 4.4 --> int <= 4
5621 if (!RHS.isNegative())
5622 Pred = ICmpInst::ICMP_SLE;
5623 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005624 case ICmpInst::ICMP_UGT:
5625 // (float)int > 4.4 --> int > 4
5626 // (float)int > -4.4 --> true
5627 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005628 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005629 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005630 case ICmpInst::ICMP_SGT:
5631 // (float)int > 4.4 --> int > 4
5632 // (float)int > -4.4 --> int >= -4
5633 if (RHS.isNegative())
5634 Pred = ICmpInst::ICMP_SGE;
5635 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005636 case ICmpInst::ICMP_UGE:
5637 // (float)int >= -4.4 --> true
5638 // (float)int >= 4.4 --> int > 4
5639 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005640 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005641 Pred = ICmpInst::ICMP_UGT;
5642 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005643 case ICmpInst::ICMP_SGE:
5644 // (float)int >= -4.4 --> int >= -4
5645 // (float)int >= 4.4 --> int > 4
5646 if (!RHS.isNegative())
5647 Pred = ICmpInst::ICMP_SGT;
5648 break;
5649 }
5650 }
5651
5652 // Lower this FP comparison into an appropriate integer version of the
5653 // comparison.
5654 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5655}
5656
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5658 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005660
Chris Lattner58e97462007-01-14 19:42:17 +00005661 // Fold trivial predicates.
5662 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005663 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005664 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005665 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005666
5667 // Simplify 'fcmp pred X, X'
5668 if (Op0 == Op1) {
5669 switch (I.getPredicate()) {
5670 default: assert(0 && "Unknown predicate!");
5671 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5672 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5673 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005674 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005675 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5676 case FCmpInst::FCMP_OLT: // True if ordered and less than
5677 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005678 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005679
5680 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5681 case FCmpInst::FCMP_ULT: // True if unordered or less than
5682 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5683 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5684 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5685 I.setPredicate(FCmpInst::FCMP_UNO);
5686 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5687 return &I;
5688
5689 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5690 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5691 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5692 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5693 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5694 I.setPredicate(FCmpInst::FCMP_ORD);
5695 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5696 return &I;
5697 }
5698 }
5699
Reid Spencere4d87aa2006-12-23 06:05:41 +00005700 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005701 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005702
Reid Spencere4d87aa2006-12-23 06:05:41 +00005703 // Handle fcmp with constant RHS
5704 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005705 // If the constant is a nan, see if we can fold the comparison based on it.
5706 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5707 if (CFP->getValueAPF().isNaN()) {
5708 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005709 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005710 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5711 "Comparison must be either ordered or unordered!");
5712 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005713 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005714 }
5715 }
5716
Reid Spencere4d87aa2006-12-23 06:05:41 +00005717 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5718 switch (LHSI->getOpcode()) {
5719 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005720 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5721 // block. If in the same block, we're encouraging jump threading. If
5722 // not, we are just pessimizing the code by making an i1 phi.
5723 if (LHSI->getParent() == I.getParent())
5724 if (Instruction *NV = FoldOpIntoPhi(I))
5725 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005726 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005727 case Instruction::SIToFP:
5728 case Instruction::UIToFP:
5729 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5730 return NV;
5731 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005732 case Instruction::Select:
5733 // If either operand of the select is a constant, we can fold the
5734 // comparison into the select arms, which will cause one to be
5735 // constant folded and the select turned into a bitwise or.
5736 Value *Op1 = 0, *Op2 = 0;
5737 if (LHSI->hasOneUse()) {
5738 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5739 // Fold the known value into the constant operand.
5740 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5741 // Insert a new FCmp of the other select operand.
5742 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5743 LHSI->getOperand(2), RHSC,
5744 I.getName()), I);
5745 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5746 // Fold the known value into the constant operand.
5747 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5748 // Insert a new FCmp of the other select operand.
5749 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5750 LHSI->getOperand(1), RHSC,
5751 I.getName()), I);
5752 }
5753 }
5754
5755 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005756 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005757 break;
5758 }
5759 }
5760
5761 return Changed ? &I : 0;
5762}
5763
5764Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5765 bool Changed = SimplifyCompare(I);
5766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5767 const Type *Ty = Op0->getType();
5768
5769 // icmp X, X
5770 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005771 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005772 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005773
5774 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005775 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005776
Reid Spencere4d87aa2006-12-23 06:05:41 +00005777 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005778 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005779 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5780 isa<ConstantPointerNull>(Op0)) &&
5781 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005782 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005783 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005784 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005785
Reid Spencere4d87aa2006-12-23 06:05:41 +00005786 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005787 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005788 switch (I.getPredicate()) {
5789 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005790 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005791 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005792 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005793 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005794 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005795 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005796 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005797
Reid Spencere4d87aa2006-12-23 06:05:41 +00005798 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005799 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005800 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005801 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005802 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005803 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005804 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005805 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005806 case ICmpInst::ICMP_SGT:
5807 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005808 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005809 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5810 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5811 InsertNewInstBefore(Not, I);
5812 return BinaryOperator::CreateAnd(Not, Op0);
5813 }
5814 case ICmpInst::ICMP_UGE:
5815 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5816 // FALL THROUGH
5817 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005818 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005819 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005820 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005821 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005822 case ICmpInst::ICMP_SGE:
5823 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5824 // FALL THROUGH
5825 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5826 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5827 InsertNewInstBefore(Not, I);
5828 return BinaryOperator::CreateOr(Not, Op0);
5829 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005830 }
Chris Lattner8b170942002-08-09 23:47:40 +00005831 }
5832
Dan Gohman81b28ce2008-09-16 18:46:06 +00005833 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005834 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005835 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005836
Chris Lattnerb6566012008-01-05 01:18:20 +00005837 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5838 if (I.isEquality() && CI->isNullValue() &&
5839 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5840 // (icmp cond A B) if cond is equality
5841 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005842 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005843
Dan Gohman81b28ce2008-09-16 18:46:06 +00005844 // If we have an icmp le or icmp ge instruction, turn it into the
5845 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5846 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005847 switch (I.getPredicate()) {
5848 default: break;
5849 case ICmpInst::ICMP_ULE:
5850 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5851 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5852 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5853 case ICmpInst::ICMP_SLE:
5854 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5855 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5856 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5857 case ICmpInst::ICMP_UGE:
5858 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5859 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5860 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5861 case ICmpInst::ICMP_SGE:
5862 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5863 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5864 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5865 }
5866
Chris Lattner183661e2008-07-11 05:40:05 +00005867 // See if we can fold the comparison based on range information we can get
5868 // by checking whether bits are known to be zero or one in the input.
5869 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5870 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5871
5872 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005873 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005874 bool UnusedBit;
5875 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5876
Chris Lattner886ab6c2009-01-31 08:15:18 +00005877 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005878 isSignBit ? APInt::getSignBit(BitWidth)
5879 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005880 KnownZero, KnownOne, 0))
5881 return &I;
5882
5883 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005884 // in. Compute the Min, Max and RHS values based on the known bits. For the
5885 // EQ and NE we use unsigned values.
5886 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005887 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5888 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5889 else
5890 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5891
Chris Lattner183661e2008-07-11 05:40:05 +00005892 // If Min and Max are known to be the same, then SimplifyDemandedBits
5893 // figured out that the LHS is a constant. Just constant fold this now so
5894 // that code below can assume that Min != Max.
5895 if (Min == Max)
5896 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5897 ConstantInt::get(Min),
5898 CI));
5899
5900 // Based on the range information we know about the LHS, see if we can
5901 // simplify this comparison. For example, (x&4) < 8 is always true.
5902 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005903 switch (I.getPredicate()) { // LE/GE have been folded already.
5904 default: assert(0 && "Unknown icmp opcode!");
5905 case ICmpInst::ICMP_EQ:
5906 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5907 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5908 break;
5909 case ICmpInst::ICMP_NE:
5910 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5911 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5912 break;
5913 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005914 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005915 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005916 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005917 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005918 if (RHSVal == Max) // A <u MAX -> A != MAX
5919 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5920 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5921 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5922
5923 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5924 if (CI->isMinValue(true))
5925 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5926 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005927 break;
5928 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005929 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005930 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005931 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005932 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005933
5934 if (RHSVal == Min) // A >u MIN -> A != MIN
5935 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5936 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5937 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5938
5939 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5940 if (CI->isMaxValue(true))
5941 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5942 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005943 break;
5944 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005945 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005946 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005947 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005948 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005949 if (RHSVal == Max) // A <s MAX -> A != MAX
5950 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005951 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005952 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005953 break;
5954 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005955 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005956 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005957 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005959
5960 if (RHSVal == Min) // A >s MIN -> A != MIN
5961 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5962 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5963 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005964 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005965 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005966 }
5967
5968 // Test if the ICmpInst instruction is used exclusively by a select as
5969 // part of a minimum or maximum operation. If so, refrain from doing
5970 // any other folding. This helps out other analyses which understand
5971 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5972 // and CodeGen. And in this case, at least one of the comparison
5973 // operands has at least one user besides the compare (the select),
5974 // which would often largely negate the benefit of folding anyway.
5975 if (I.hasOneUse())
5976 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5977 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5978 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5979 return 0;
5980
5981 // See if we are doing a comparison between a constant and an instruction that
5982 // can be folded into the comparison.
5983 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005985 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005987 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005988 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5989 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005990 }
5991
Chris Lattner01deb9d2007-04-03 17:43:25 +00005992 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005993 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5994 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5995 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005996 case Instruction::GetElementPtr:
5997 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005998 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005999 bool isAllZeros = true;
6000 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6001 if (!isa<Constant>(LHSI->getOperand(i)) ||
6002 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6003 isAllZeros = false;
6004 break;
6005 }
6006 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006008 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6009 }
6010 break;
6011
Chris Lattner6970b662005-04-23 15:31:55 +00006012 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006013 // Only fold icmp into the PHI if the phi and fcmp are in the same
6014 // block. If in the same block, we're encouraging jump threading. If
6015 // not, we are just pessimizing the code by making an i1 phi.
6016 if (LHSI->getParent() == I.getParent())
6017 if (Instruction *NV = FoldOpIntoPhi(I))
6018 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006019 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006020 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006021 // If either operand of the select is a constant, we can fold the
6022 // comparison into the select arms, which will cause one to be
6023 // constant folded and the select turned into a bitwise or.
6024 Value *Op1 = 0, *Op2 = 0;
6025 if (LHSI->hasOneUse()) {
6026 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6027 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006028 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6029 // Insert a new ICmp of the other select operand.
6030 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6031 LHSI->getOperand(2), RHSC,
6032 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006033 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6034 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006035 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6036 // Insert a new ICmp of the other select operand.
6037 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6038 LHSI->getOperand(1), RHSC,
6039 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006040 }
6041 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006042
Chris Lattner6970b662005-04-23 15:31:55 +00006043 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006044 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006045 break;
6046 }
Chris Lattner4802d902007-04-06 18:57:34 +00006047 case Instruction::Malloc:
6048 // If we have (malloc != null), and if the malloc has a single use, we
6049 // can assume it is successful and remove the malloc.
6050 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6051 AddToWorkList(LHSI);
6052 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006053 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006054 }
6055 break;
6056 }
Chris Lattner6970b662005-04-23 15:31:55 +00006057 }
6058
Reid Spencere4d87aa2006-12-23 06:05:41 +00006059 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006060 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006061 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006062 return NI;
6063 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006064 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6065 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006066 return NI;
6067
Reid Spencere4d87aa2006-12-23 06:05:41 +00006068 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006069 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6070 // now.
6071 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6072 if (isa<PointerType>(Op0->getType()) &&
6073 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006074 // We keep moving the cast from the left operand over to the right
6075 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006076 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006077
Chris Lattner57d86372007-01-06 01:45:59 +00006078 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6079 // so eliminate it as well.
6080 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6081 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006082
Chris Lattnerde90b762003-11-03 04:25:02 +00006083 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006084 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006085 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006086 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006087 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006088 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006089 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006090 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006091 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006092 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006093 }
Chris Lattner57d86372007-01-06 01:45:59 +00006094 }
6095
6096 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006097 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006098 // This comes up when you have code like
6099 // int X = A < B;
6100 // if (X) ...
6101 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006102 // with a constant or another cast from the same type.
6103 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006104 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006105 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006106 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006107
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006108 // See if it's the same type of instruction on the left and right.
6109 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6110 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006111 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006112 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006113 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006114 default: break;
6115 case Instruction::Add:
6116 case Instruction::Sub:
6117 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006118 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006119 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6120 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006121 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6122 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6123 if (CI->getValue().isSignBit()) {
6124 ICmpInst::Predicate Pred = I.isSignedPredicate()
6125 ? I.getUnsignedPredicate()
6126 : I.getSignedPredicate();
6127 return new ICmpInst(Pred, Op0I->getOperand(0),
6128 Op1I->getOperand(0));
6129 }
6130
6131 if (CI->getValue().isMaxSignedValue()) {
6132 ICmpInst::Predicate Pred = I.isSignedPredicate()
6133 ? I.getUnsignedPredicate()
6134 : I.getSignedPredicate();
6135 Pred = I.getSwappedPredicate(Pred);
6136 return new ICmpInst(Pred, Op0I->getOperand(0),
6137 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006138 }
6139 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006140 break;
6141 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006142 if (!I.isEquality())
6143 break;
6144
Nick Lewycky5d52c452008-08-21 05:56:10 +00006145 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6146 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6147 // Mask = -1 >> count-trailing-zeros(Cst).
6148 if (!CI->isZero() && !CI->isOne()) {
6149 const APInt &AP = CI->getValue();
6150 ConstantInt *Mask = ConstantInt::get(
6151 APInt::getLowBitsSet(AP.getBitWidth(),
6152 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006153 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006154 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6155 Mask);
6156 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6157 Mask);
6158 InsertNewInstBefore(And1, I);
6159 InsertNewInstBefore(And2, I);
6160 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006161 }
6162 }
6163 break;
6164 }
6165 }
6166 }
6167 }
6168
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006169 // ~x < ~y --> y < x
6170 { Value *A, *B;
6171 if (match(Op0, m_Not(m_Value(A))) &&
6172 match(Op1, m_Not(m_Value(B))))
6173 return new ICmpInst(I.getPredicate(), B, A);
6174 }
6175
Chris Lattner65b72ba2006-09-18 04:22:48 +00006176 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006177 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006178
6179 // -x == -y --> x == y
6180 if (match(Op0, m_Neg(m_Value(A))) &&
6181 match(Op1, m_Neg(m_Value(B))))
6182 return new ICmpInst(I.getPredicate(), A, B);
6183
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006184 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6185 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6186 Value *OtherVal = A == Op1 ? B : A;
6187 return new ICmpInst(I.getPredicate(), OtherVal,
6188 Constant::getNullValue(A->getType()));
6189 }
6190
6191 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6192 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006193 ConstantInt *C1, *C2;
6194 if (match(B, m_ConstantInt(C1)) &&
6195 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6196 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6197 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6198 return new ICmpInst(I.getPredicate(), A,
6199 InsertNewInstBefore(Xor, I));
6200 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006201
6202 // A^B == A^D -> B == D
6203 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6204 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6205 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6206 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6207 }
6208 }
6209
6210 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6211 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006212 // A == (A^B) -> B == 0
6213 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006214 return new ICmpInst(I.getPredicate(), OtherVal,
6215 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006216 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006217
6218 // (A-B) == A -> B == 0
6219 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6220 return new ICmpInst(I.getPredicate(), B,
6221 Constant::getNullValue(B->getType()));
6222
6223 // A == (A-B) -> B == 0
6224 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006225 return new ICmpInst(I.getPredicate(), B,
6226 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006227
Chris Lattner9c2328e2006-11-14 06:06:06 +00006228 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6229 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6230 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6231 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6232 Value *X = 0, *Y = 0, *Z = 0;
6233
6234 if (A == C) {
6235 X = B; Y = D; Z = A;
6236 } else if (A == D) {
6237 X = B; Y = C; Z = A;
6238 } else if (B == C) {
6239 X = A; Y = D; Z = B;
6240 } else if (B == D) {
6241 X = A; Y = C; Z = B;
6242 }
6243
6244 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006245 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6246 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006247 I.setOperand(0, Op1);
6248 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6249 return &I;
6250 }
6251 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006252 }
Chris Lattner7e708292002-06-25 16:13:24 +00006253 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006254}
6255
Chris Lattner562ef782007-06-20 23:46:26 +00006256
6257/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6258/// and CmpRHS are both known to be integer constants.
6259Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6260 ConstantInt *DivRHS) {
6261 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6262 const APInt &CmpRHSV = CmpRHS->getValue();
6263
6264 // FIXME: If the operand types don't match the type of the divide
6265 // then don't attempt this transform. The code below doesn't have the
6266 // logic to deal with a signed divide and an unsigned compare (and
6267 // vice versa). This is because (x /s C1) <s C2 produces different
6268 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6269 // (x /u C1) <u C2. Simply casting the operands and result won't
6270 // work. :( The if statement below tests that condition and bails
6271 // if it finds it.
6272 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6273 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6274 return 0;
6275 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006276 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006277 if (DivIsSigned && DivRHS->isAllOnesValue())
6278 return 0; // The overflow computation also screws up here
6279 if (DivRHS->isOne())
6280 return 0; // Not worth bothering, and eliminates some funny cases
6281 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006282
6283 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6284 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6285 // C2 (CI). By solving for X we can turn this into a range check
6286 // instead of computing a divide.
6287 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6288
6289 // Determine if the product overflows by seeing if the product is
6290 // not equal to the divide. Make sure we do the same kind of divide
6291 // as in the LHS instruction that we're folding.
6292 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6293 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6294
6295 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006296 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006297
Chris Lattner1dbfd482007-06-21 18:11:19 +00006298 // Figure out the interval that is being checked. For example, a comparison
6299 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6300 // Compute this interval based on the constants involved and the signedness of
6301 // the compare/divide. This computes a half-open interval, keeping track of
6302 // whether either value in the interval overflows. After analysis each
6303 // overflow variable is set to 0 if it's corresponding bound variable is valid
6304 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6305 int LoOverflow = 0, HiOverflow = 0;
6306 ConstantInt *LoBound = 0, *HiBound = 0;
6307
Chris Lattner562ef782007-06-20 23:46:26 +00006308 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006309 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006310 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006311 HiOverflow = LoOverflow = ProdOV;
6312 if (!HiOverflow)
6313 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006314 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006315 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006316 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006317 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6318 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006319 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006320 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6321 HiOverflow = LoOverflow = ProdOV;
6322 if (!HiOverflow)
6323 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006324 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006325 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006326 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006327 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6328 if (!LoOverflow) {
6329 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6330 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6331 true) ? -1 : 0;
6332 }
Chris Lattner562ef782007-06-20 23:46:26 +00006333 }
Dan Gohman76491272008-02-13 22:09:18 +00006334 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006335 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006336 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006337 LoBound = AddOne(DivRHS);
6338 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006339 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6340 HiOverflow = 1; // [INTMIN+1, overflow)
6341 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6342 }
Dan Gohman76491272008-02-13 22:09:18 +00006343 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006344 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006345 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006346 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006347 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006348 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006349 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006350 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6351 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006352 if (!HiOverflow)
6353 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006354 }
6355
Chris Lattner1dbfd482007-06-21 18:11:19 +00006356 // Dividing by a negative swaps the condition. LT <-> GT
6357 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006358 }
6359
6360 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006361 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006362 default: assert(0 && "Unhandled icmp opcode!");
6363 case ICmpInst::ICMP_EQ:
6364 if (LoOverflow && HiOverflow)
6365 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6366 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006367 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006368 ICmpInst::ICMP_UGE, X, LoBound);
6369 else if (LoOverflow)
6370 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6371 ICmpInst::ICMP_ULT, X, HiBound);
6372 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006373 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006374 case ICmpInst::ICMP_NE:
6375 if (LoOverflow && HiOverflow)
6376 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6377 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006378 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006379 ICmpInst::ICMP_ULT, X, LoBound);
6380 else if (LoOverflow)
6381 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6382 ICmpInst::ICMP_UGE, X, HiBound);
6383 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006384 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006385 case ICmpInst::ICMP_ULT:
6386 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006387 if (LoOverflow == +1) // Low bound is greater than input range.
6388 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6389 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006390 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006391 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006392 case ICmpInst::ICMP_UGT:
6393 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006394 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006395 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006396 else if (HiOverflow == -1) // High bound less than input range.
6397 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6398 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006399 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6400 else
6401 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6402 }
6403}
6404
6405
Chris Lattner01deb9d2007-04-03 17:43:25 +00006406/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6407///
6408Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6409 Instruction *LHSI,
6410 ConstantInt *RHS) {
6411 const APInt &RHSV = RHS->getValue();
6412
6413 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006414 case Instruction::Trunc:
6415 if (ICI.isEquality() && LHSI->hasOneUse()) {
6416 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6417 // of the high bits truncated out of x are known.
6418 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6419 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6420 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6421 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6422 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6423
6424 // If all the high bits are known, we can do this xform.
6425 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6426 // Pull in the high bits from known-ones set.
6427 APInt NewRHS(RHS->getValue());
6428 NewRHS.zext(SrcBits);
6429 NewRHS |= KnownOne;
6430 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6431 ConstantInt::get(NewRHS));
6432 }
6433 }
6434 break;
6435
Duncan Sands0091bf22007-04-04 06:42:45 +00006436 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006437 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6438 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6439 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006440 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6441 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006442 Value *CompareVal = LHSI->getOperand(0);
6443
6444 // If the sign bit of the XorCST is not set, there is no change to
6445 // the operation, just stop using the Xor.
6446 if (!XorCST->getValue().isNegative()) {
6447 ICI.setOperand(0, CompareVal);
6448 AddToWorkList(LHSI);
6449 return &ICI;
6450 }
6451
6452 // Was the old condition true if the operand is positive?
6453 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6454
6455 // If so, the new one isn't.
6456 isTrueIfPositive ^= true;
6457
6458 if (isTrueIfPositive)
6459 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6460 else
6461 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6462 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006463
6464 if (LHSI->hasOneUse()) {
6465 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6466 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6467 const APInt &SignBit = XorCST->getValue();
6468 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6469 ? ICI.getUnsignedPredicate()
6470 : ICI.getSignedPredicate();
6471 return new ICmpInst(Pred, LHSI->getOperand(0),
6472 ConstantInt::get(RHSV ^ SignBit));
6473 }
6474
6475 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006476 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006477 const APInt &NotSignBit = XorCST->getValue();
6478 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6479 ? ICI.getUnsignedPredicate()
6480 : ICI.getSignedPredicate();
6481 Pred = ICI.getSwappedPredicate(Pred);
6482 return new ICmpInst(Pred, LHSI->getOperand(0),
6483 ConstantInt::get(RHSV ^ NotSignBit));
6484 }
6485 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006486 }
6487 break;
6488 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6489 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6490 LHSI->getOperand(0)->hasOneUse()) {
6491 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6492
6493 // If the LHS is an AND of a truncating cast, we can widen the
6494 // and/compare to be the input width without changing the value
6495 // produced, eliminating a cast.
6496 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6497 // We can do this transformation if either the AND constant does not
6498 // have its sign bit set or if it is an equality comparison.
6499 // Extending a relational comparison when we're checking the sign
6500 // bit would not work.
6501 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006502 (ICI.isEquality() ||
6503 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006504 uint32_t BitWidth =
6505 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6506 APInt NewCST = AndCST->getValue();
6507 NewCST.zext(BitWidth);
6508 APInt NewCI = RHSV;
6509 NewCI.zext(BitWidth);
6510 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006511 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006512 ConstantInt::get(NewCST),LHSI->getName());
6513 InsertNewInstBefore(NewAnd, ICI);
6514 return new ICmpInst(ICI.getPredicate(), NewAnd,
6515 ConstantInt::get(NewCI));
6516 }
6517 }
6518
6519 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6520 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6521 // happens a LOT in code produced by the C front-end, for bitfield
6522 // access.
6523 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6524 if (Shift && !Shift->isShift())
6525 Shift = 0;
6526
6527 ConstantInt *ShAmt;
6528 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6529 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6530 const Type *AndTy = AndCST->getType(); // Type of the and.
6531
6532 // We can fold this as long as we can't shift unknown bits
6533 // into the mask. This can only happen with signed shift
6534 // rights, as they sign-extend.
6535 if (ShAmt) {
6536 bool CanFold = Shift->isLogicalShift();
6537 if (!CanFold) {
6538 // To test for the bad case of the signed shr, see if any
6539 // of the bits shifted in could be tested after the mask.
6540 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6541 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6542
6543 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6544 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6545 AndCST->getValue()) == 0)
6546 CanFold = true;
6547 }
6548
6549 if (CanFold) {
6550 Constant *NewCst;
6551 if (Shift->getOpcode() == Instruction::Shl)
6552 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6553 else
6554 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6555
6556 // Check to see if we are shifting out any of the bits being
6557 // compared.
6558 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6559 // If we shifted bits out, the fold is not going to work out.
6560 // As a special case, check to see if this means that the
6561 // result is always true or false now.
6562 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6563 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6564 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6565 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6566 } else {
6567 ICI.setOperand(1, NewCst);
6568 Constant *NewAndCST;
6569 if (Shift->getOpcode() == Instruction::Shl)
6570 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6571 else
6572 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6573 LHSI->setOperand(1, NewAndCST);
6574 LHSI->setOperand(0, Shift->getOperand(0));
6575 AddToWorkList(Shift); // Shift is dead.
6576 AddUsesToWorkList(ICI);
6577 return &ICI;
6578 }
6579 }
6580 }
6581
6582 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6583 // preferable because it allows the C<<Y expression to be hoisted out
6584 // of a loop if Y is invariant and X is not.
6585 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006586 ICI.isEquality() && !Shift->isArithmeticShift() &&
6587 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006588 // Compute C << Y.
6589 Value *NS;
6590 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006591 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006592 Shift->getOperand(1), "tmp");
6593 } else {
6594 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006595 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006596 Shift->getOperand(1), "tmp");
6597 }
6598 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6599
6600 // Compute X & (C << Y).
6601 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006602 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006603 InsertNewInstBefore(NewAnd, ICI);
6604
6605 ICI.setOperand(0, NewAnd);
6606 return &ICI;
6607 }
6608 }
6609 break;
6610
Chris Lattnera0141b92007-07-15 20:42:37 +00006611 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6612 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6613 if (!ShAmt) break;
6614
6615 uint32_t TypeBits = RHSV.getBitWidth();
6616
6617 // Check that the shift amount is in range. If not, don't perform
6618 // undefined shifts. When the shift is visited it will be
6619 // simplified.
6620 if (ShAmt->uge(TypeBits))
6621 break;
6622
6623 if (ICI.isEquality()) {
6624 // If we are comparing against bits always shifted out, the
6625 // comparison cannot succeed.
6626 Constant *Comp =
6627 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6628 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6629 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6630 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6631 return ReplaceInstUsesWith(ICI, Cst);
6632 }
6633
6634 if (LHSI->hasOneUse()) {
6635 // Otherwise strength reduce the shift into an and.
6636 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6637 Constant *Mask =
6638 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006639
Chris Lattnera0141b92007-07-15 20:42:37 +00006640 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006641 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006642 Mask, LHSI->getName()+".mask");
6643 Value *And = InsertNewInstBefore(AndI, ICI);
6644 return new ICmpInst(ICI.getPredicate(), And,
6645 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006646 }
6647 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006648
6649 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6650 bool TrueIfSigned = false;
6651 if (LHSI->hasOneUse() &&
6652 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6653 // (X << 31) <s 0 --> (X&1) != 0
6654 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6655 (TypeBits-ShAmt->getZExtValue()-1));
6656 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006657 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006658 Mask, LHSI->getName()+".mask");
6659 Value *And = InsertNewInstBefore(AndI, ICI);
6660
6661 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6662 And, Constant::getNullValue(And->getType()));
6663 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006664 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006665 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006666
6667 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006668 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006669 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006670 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006671 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006672
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006673 // Check that the shift amount is in range. If not, don't perform
6674 // undefined shifts. When the shift is visited it will be
6675 // simplified.
6676 uint32_t TypeBits = RHSV.getBitWidth();
6677 if (ShAmt->uge(TypeBits))
6678 break;
6679
6680 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006681
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006682 // If we are comparing against bits always shifted out, the
6683 // comparison cannot succeed.
6684 APInt Comp = RHSV << ShAmtVal;
6685 if (LHSI->getOpcode() == Instruction::LShr)
6686 Comp = Comp.lshr(ShAmtVal);
6687 else
6688 Comp = Comp.ashr(ShAmtVal);
6689
6690 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6691 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6692 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6693 return ReplaceInstUsesWith(ICI, Cst);
6694 }
6695
6696 // Otherwise, check to see if the bits shifted out are known to be zero.
6697 // If so, we can compare against the unshifted value:
6698 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006699 if (LHSI->hasOneUse() &&
6700 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006701 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6702 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6703 ConstantExpr::getShl(RHS, ShAmt));
6704 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006705
Evan Chengf30752c2008-04-23 00:38:06 +00006706 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006707 // Otherwise strength reduce the shift into an and.
6708 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6709 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006710
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006711 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006712 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006713 Mask, LHSI->getName()+".mask");
6714 Value *And = InsertNewInstBefore(AndI, ICI);
6715 return new ICmpInst(ICI.getPredicate(), And,
6716 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717 }
6718 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006719 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006720
6721 case Instruction::SDiv:
6722 case Instruction::UDiv:
6723 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6724 // Fold this div into the comparison, producing a range check.
6725 // Determine, based on the divide type, what the range is being
6726 // checked. If there is an overflow on the low or high side, remember
6727 // it, otherwise compute the range [low, hi) bounding the new value.
6728 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006729 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6730 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6731 DivRHS))
6732 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006733 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006734
6735 case Instruction::Add:
6736 // Fold: icmp pred (add, X, C1), C2
6737
6738 if (!ICI.isEquality()) {
6739 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6740 if (!LHSC) break;
6741 const APInt &LHSV = LHSC->getValue();
6742
6743 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6744 .subtract(LHSV);
6745
6746 if (ICI.isSignedPredicate()) {
6747 if (CR.getLower().isSignBit()) {
6748 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6749 ConstantInt::get(CR.getUpper()));
6750 } else if (CR.getUpper().isSignBit()) {
6751 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6752 ConstantInt::get(CR.getLower()));
6753 }
6754 } else {
6755 if (CR.getLower().isMinValue()) {
6756 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6757 ConstantInt::get(CR.getUpper()));
6758 } else if (CR.getUpper().isMinValue()) {
6759 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6760 ConstantInt::get(CR.getLower()));
6761 }
6762 }
6763 }
6764 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006765 }
6766
6767 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6768 if (ICI.isEquality()) {
6769 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6770
6771 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6772 // the second operand is a constant, simplify a bit.
6773 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6774 switch (BO->getOpcode()) {
6775 case Instruction::SRem:
6776 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6777 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6778 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6779 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6780 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006781 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 BO->getName());
6783 InsertNewInstBefore(NewRem, ICI);
6784 return new ICmpInst(ICI.getPredicate(), NewRem,
6785 Constant::getNullValue(BO->getType()));
6786 }
6787 }
6788 break;
6789 case Instruction::Add:
6790 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6791 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6792 if (BO->hasOneUse())
6793 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6794 Subtract(RHS, BOp1C));
6795 } else if (RHSV == 0) {
6796 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6797 // efficiently invertible, or if the add has just this one use.
6798 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6799
6800 if (Value *NegVal = dyn_castNegVal(BOp1))
6801 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6802 else if (Value *NegVal = dyn_castNegVal(BOp0))
6803 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6804 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006805 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006806 InsertNewInstBefore(Neg, ICI);
6807 Neg->takeName(BO);
6808 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6809 }
6810 }
6811 break;
6812 case Instruction::Xor:
6813 // For the xor case, we can xor two constants together, eliminating
6814 // the explicit xor.
6815 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6816 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6817 ConstantExpr::getXor(RHS, BOC));
6818
6819 // FALLTHROUGH
6820 case Instruction::Sub:
6821 // Replace (([sub|xor] A, B) != 0) with (A != B)
6822 if (RHSV == 0)
6823 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6824 BO->getOperand(1));
6825 break;
6826
6827 case Instruction::Or:
6828 // If bits are being or'd in that are not present in the constant we
6829 // are comparing against, then the comparison could never succeed!
6830 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6831 Constant *NotCI = ConstantExpr::getNot(RHS);
6832 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6833 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6834 isICMP_NE));
6835 }
6836 break;
6837
6838 case Instruction::And:
6839 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6840 // If bits are being compared against that are and'd out, then the
6841 // comparison can never succeed!
6842 if ((RHSV & ~BOC->getValue()) != 0)
6843 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6844 isICMP_NE));
6845
6846 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6847 if (RHS == BOC && RHSV.isPowerOf2())
6848 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6849 ICmpInst::ICMP_NE, LHSI,
6850 Constant::getNullValue(RHS->getType()));
6851
6852 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006853 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 Value *X = BO->getOperand(0);
6855 Constant *Zero = Constant::getNullValue(X->getType());
6856 ICmpInst::Predicate pred = isICMP_NE ?
6857 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6858 return new ICmpInst(pred, X, Zero);
6859 }
6860
6861 // ((X & ~7) == 0) --> X < 8
6862 if (RHSV == 0 && isHighOnes(BOC)) {
6863 Value *X = BO->getOperand(0);
6864 Constant *NegX = ConstantExpr::getNeg(BOC);
6865 ICmpInst::Predicate pred = isICMP_NE ?
6866 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6867 return new ICmpInst(pred, X, NegX);
6868 }
6869 }
6870 default: break;
6871 }
6872 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6873 // Handle icmp {eq|ne} <intrinsic>, intcst.
6874 if (II->getIntrinsicID() == Intrinsic::bswap) {
6875 AddToWorkList(II);
6876 ICI.setOperand(0, II->getOperand(1));
6877 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6878 return &ICI;
6879 }
6880 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006881 }
6882 return 0;
6883}
6884
6885/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6886/// We only handle extending casts so far.
6887///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006888Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6889 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006890 Value *LHSCIOp = LHSCI->getOperand(0);
6891 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006892 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006893 Value *RHSCIOp;
6894
Chris Lattner8c756c12007-05-05 22:41:33 +00006895 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6896 // integer type is the same size as the pointer type.
6897 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6898 getTargetData().getPointerSizeInBits() ==
6899 cast<IntegerType>(DestTy)->getBitWidth()) {
6900 Value *RHSOp = 0;
6901 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006902 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006903 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6904 RHSOp = RHSC->getOperand(0);
6905 // If the pointer types don't match, insert a bitcast.
6906 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006907 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006908 }
6909
6910 if (RHSOp)
6911 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6912 }
6913
6914 // The code below only handles extension cast instructions, so far.
6915 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006916 if (LHSCI->getOpcode() != Instruction::ZExt &&
6917 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006918 return 0;
6919
Reid Spencere4d87aa2006-12-23 06:05:41 +00006920 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6921 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006922
Reid Spencere4d87aa2006-12-23 06:05:41 +00006923 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006924 // Not an extension from the same type?
6925 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006926 if (RHSCIOp->getType() != LHSCIOp->getType())
6927 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006928
Nick Lewycky4189a532008-01-28 03:48:02 +00006929 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006930 // and the other is a zext), then we can't handle this.
6931 if (CI->getOpcode() != LHSCI->getOpcode())
6932 return 0;
6933
Nick Lewycky4189a532008-01-28 03:48:02 +00006934 // Deal with equality cases early.
6935 if (ICI.isEquality())
6936 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6937
6938 // A signed comparison of sign extended values simplifies into a
6939 // signed comparison.
6940 if (isSignedCmp && isSignedExt)
6941 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6942
6943 // The other three cases all fold into an unsigned comparison.
6944 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006945 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006946
Reid Spencere4d87aa2006-12-23 06:05:41 +00006947 // If we aren't dealing with a constant on the RHS, exit early
6948 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6949 if (!CI)
6950 return 0;
6951
6952 // Compute the constant that would happen if we truncated to SrcTy then
6953 // reextended to DestTy.
6954 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6955 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6956
6957 // If the re-extended constant didn't change...
6958 if (Res2 == CI) {
6959 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6960 // For example, we might have:
6961 // %A = sext short %X to uint
6962 // %B = icmp ugt uint %A, 1330
6963 // It is incorrect to transform this into
6964 // %B = icmp ugt short %X, 1330
6965 // because %A may have negative value.
6966 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006967 // However, we allow this when the compare is EQ/NE, because they are
6968 // signless.
6969 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006970 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006971 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006972 }
6973
6974 // The re-extended constant changed so the constant cannot be represented
6975 // in the shorter type. Consequently, we cannot emit a simple comparison.
6976
6977 // First, handle some easy cases. We know the result cannot be equal at this
6978 // point so handle the ICI.isEquality() cases
6979 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006980 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006981 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006982 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006983
6984 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6985 // should have been folded away previously and not enter in here.
6986 Value *Result;
6987 if (isSignedCmp) {
6988 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006989 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006990 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006991 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006992 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006993 } else {
6994 // We're performing an unsigned comparison.
6995 if (isSignedExt) {
6996 // We're performing an unsigned comp with a sign extended value.
6997 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006998 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006999 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7000 NegOne, ICI.getName()), ICI);
7001 } else {
7002 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007003 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007004 }
7005 }
7006
7007 // Finally, return the value computed.
7008 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007009 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007010 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007011
7012 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7013 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7014 "ICmp should be folded!");
7015 if (Constant *CI = dyn_cast<Constant>(Result))
7016 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7017 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007018}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007019
Reid Spencer832254e2007-02-02 02:16:23 +00007020Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7021 return commonShiftTransforms(I);
7022}
7023
7024Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7025 return commonShiftTransforms(I);
7026}
7027
7028Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007029 if (Instruction *R = commonShiftTransforms(I))
7030 return R;
7031
7032 Value *Op0 = I.getOperand(0);
7033
7034 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7035 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7036 if (CSI->isAllOnesValue())
7037 return ReplaceInstUsesWith(I, CSI);
7038
7039 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb44b3662009-03-18 16:32:19 +00007040 if (!isa<VectorType>(I.getType())) {
7041 if (MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007042 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Chris Lattnerb44b3662009-03-18 16:32:19 +00007043 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman0001e562009-02-24 02:00:40 +00007044
Chris Lattnerb44b3662009-03-18 16:32:19 +00007045 // Arithmetic shifting an all-sign-bit value is a no-op.
7046 unsigned NumSignBits = ComputeNumSignBits(Op0);
7047 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7048 return ReplaceInstUsesWith(I, Op0);
7049 }
Dan Gohman0001e562009-02-24 02:00:40 +00007050
Chris Lattner348f6652007-12-06 01:59:46 +00007051 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007052}
7053
7054Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7055 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007056 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007057
7058 // shl X, 0 == X and shr X, 0 == X
7059 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007060 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007061 Op0 == Constant::getNullValue(Op0->getType()))
7062 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007063
Reid Spencere4d87aa2006-12-23 06:05:41 +00007064 if (isa<UndefValue>(Op0)) {
7065 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007066 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007067 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007068 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7069 }
7070 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007071 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7072 return ReplaceInstUsesWith(I, Op0);
7073 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007074 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007075 }
7076
Chris Lattner2eefe512004-04-09 19:05:30 +00007077 // Try to fold constant and into select arguments.
7078 if (isa<Constant>(Op0))
7079 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007081 return R;
7082
Reid Spencerb83eb642006-10-20 07:07:24 +00007083 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007084 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7085 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007086 return 0;
7087}
7088
Reid Spencerb83eb642006-10-20 07:07:24 +00007089Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007090 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007091 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007092
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007093 // See if we can simplify any instructions used by the instruction whose sole
7094 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007095 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00007096 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007097 return &I;
7098
Chris Lattner4d5542c2006-01-06 07:12:35 +00007099 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7100 // of a signed value.
7101 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007102 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007103 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007104 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7105 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007106 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007107 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007108 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007109 }
7110
7111 // ((X*C1) << C2) == (X * (C1 << C2))
7112 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7113 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7114 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007115 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007116 ConstantExpr::getShl(BOOp, Op1));
7117
7118 // Try to fold constant and into select arguments.
7119 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7120 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7121 return R;
7122 if (isa<PHINode>(Op0))
7123 if (Instruction *NV = FoldOpIntoPhi(I))
7124 return NV;
7125
Chris Lattner8999dd32007-12-22 09:07:47 +00007126 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7127 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7128 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7129 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7130 // place. Don't try to do this transformation in this case. Also, we
7131 // require that the input operand is a shift-by-constant so that we have
7132 // confidence that the shifts will get folded together. We could do this
7133 // xform in more cases, but it is unlikely to be profitable.
7134 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7135 isa<ConstantInt>(TrOp->getOperand(1))) {
7136 // Okay, we'll do this xform. Make the shift of shift.
7137 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007138 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007139 I.getName());
7140 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7141
7142 // For logical shifts, the truncation has the effect of making the high
7143 // part of the register be zeros. Emulate this by inserting an AND to
7144 // clear the top bits as needed. This 'and' will usually be zapped by
7145 // other xforms later if dead.
7146 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7147 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7148 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7149
7150 // The mask we constructed says what the trunc would do if occurring
7151 // between the shifts. We want to know the effect *after* the second
7152 // shift. We know that it is a logical shift by a constant, so adjust the
7153 // mask as appropriate.
7154 if (I.getOpcode() == Instruction::Shl)
7155 MaskV <<= Op1->getZExtValue();
7156 else {
7157 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7158 MaskV = MaskV.lshr(Op1->getZExtValue());
7159 }
7160
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007161 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007162 TI->getName());
7163 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7164
7165 // Return the value truncated to the interesting size.
7166 return new TruncInst(And, I.getType());
7167 }
7168 }
7169
Chris Lattner4d5542c2006-01-06 07:12:35 +00007170 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007171 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7172 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7173 Value *V1, *V2;
7174 ConstantInt *CC;
7175 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007176 default: break;
7177 case Instruction::Add:
7178 case Instruction::And:
7179 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007180 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007181 // These operators commute.
7182 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007183 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007184 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007185 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007186 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007187 Op0BO->getName());
7188 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007189 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007190 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007191 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007192 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007193 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007194 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007195 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007196 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007197
Chris Lattner150f12a2005-09-18 06:30:59 +00007198 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007199 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007200 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007201 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007202 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7203 m_ConstantInt(CC))) &&
7204 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007205 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007206 Op0BO->getOperand(0), Op1,
7207 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007208 InsertNewInstBefore(YS, I); // (Y << C)
7209 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007210 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007211 V1->getName()+".mask");
7212 InsertNewInstBefore(XM, I); // X & (CC << C)
7213
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007214 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007215 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007216 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007217
Reid Spencera07cb7d2007-02-02 14:41:37 +00007218 // FALL THROUGH.
7219 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007220 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007221 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007222 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007223 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007224 Op0BO->getOperand(1), Op1,
7225 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007226 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007227 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007228 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007229 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007230 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007231 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007232 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007233 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007234 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007235
Chris Lattner13d4ab42006-05-31 21:14:00 +00007236 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007237 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7238 match(Op0BO->getOperand(0),
7239 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007240 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007241 cast<BinaryOperator>(Op0BO->getOperand(0))
7242 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007243 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007244 Op0BO->getOperand(1), Op1,
7245 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007246 InsertNewInstBefore(YS, I); // (Y << C)
7247 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007248 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007249 V1->getName()+".mask");
7250 InsertNewInstBefore(XM, I); // X & (CC << C)
7251
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007252 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007253 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007254
Chris Lattner11021cb2005-09-18 05:12:10 +00007255 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007256 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007257 }
7258
7259
7260 // If the operand is an bitwise operator with a constant RHS, and the
7261 // shift is the only use, we can pull it out of the shift.
7262 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7263 bool isValid = true; // Valid only for And, Or, Xor
7264 bool highBitSet = false; // Transform if high bit of constant set?
7265
7266 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007267 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007268 case Instruction::Add:
7269 isValid = isLeftShift;
7270 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007271 case Instruction::Or:
7272 case Instruction::Xor:
7273 highBitSet = false;
7274 break;
7275 case Instruction::And:
7276 highBitSet = true;
7277 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007278 }
7279
7280 // If this is a signed shift right, and the high bit is modified
7281 // by the logical operation, do not perform the transformation.
7282 // The highBitSet boolean indicates the value of the high bit of
7283 // the constant which would cause it to be modified for this
7284 // operation.
7285 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007286 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007287 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007288
7289 if (isValid) {
7290 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7291
7292 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007293 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007294 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007295 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007296
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007297 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007298 NewRHS);
7299 }
7300 }
7301 }
7302 }
7303
Chris Lattnerad0124c2006-01-06 07:52:12 +00007304 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007305 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7306 if (ShiftOp && !ShiftOp->isShift())
7307 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007308
Reid Spencerb83eb642006-10-20 07:07:24 +00007309 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007310 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007311 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7312 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007313 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7314 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7315 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007316
Zhou Sheng4351c642007-04-02 08:20:41 +00007317 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007318
7319 const IntegerType *Ty = cast<IntegerType>(I.getType());
7320
7321 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007322 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007323 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7324 // saturates.
7325 if (AmtSum >= TypeBits) {
7326 if (I.getOpcode() != Instruction::AShr)
7327 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7328 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7329 }
7330
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007331 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007332 ConstantInt::get(Ty, AmtSum));
7333 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7334 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007335 if (AmtSum >= TypeBits)
7336 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7337
Chris Lattnerb87056f2007-02-05 00:57:54 +00007338 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007339 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007340 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7341 I.getOpcode() == Instruction::LShr) {
7342 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007343 if (AmtSum >= TypeBits)
7344 AmtSum = TypeBits-1;
7345
Chris Lattnerb87056f2007-02-05 00:57:54 +00007346 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007347 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007348 InsertNewInstBefore(Shift, I);
7349
Zhou Shenge9e03f62007-03-28 15:02:20 +00007350 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007351 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007352 }
7353
Chris Lattnerb87056f2007-02-05 00:57:54 +00007354 // Okay, if we get here, one shift must be left, and the other shift must be
7355 // right. See if the amounts are equal.
7356 if (ShiftAmt1 == ShiftAmt2) {
7357 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7358 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007359 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007360 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007361 }
7362 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7363 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007364 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007365 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007366 }
7367 // We can simplify ((X << C) >>s C) into a trunc + sext.
7368 // NOTE: we could do this for any C, but that would make 'unusual' integer
7369 // types. For now, just stick to ones well-supported by the code
7370 // generators.
7371 const Type *SExtType = 0;
7372 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007373 case 1 :
7374 case 8 :
7375 case 16 :
7376 case 32 :
7377 case 64 :
7378 case 128:
7379 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7380 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007381 default: break;
7382 }
7383 if (SExtType) {
7384 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7385 InsertNewInstBefore(NewTrunc, I);
7386 return new SExtInst(NewTrunc, Ty);
7387 }
7388 // Otherwise, we can't handle it yet.
7389 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007390 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007391
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007392 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007393 if (I.getOpcode() == Instruction::Shl) {
7394 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7395 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007396 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007397 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007398 InsertNewInstBefore(Shift, I);
7399
Reid Spencer55702aa2007-03-25 21:11:44 +00007400 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007401 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007402 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007403
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007404 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007405 if (I.getOpcode() == Instruction::LShr) {
7406 assert(ShiftOp->getOpcode() == Instruction::Shl);
7407 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007408 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007409 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007410
Reid Spencerd5e30f02007-03-26 17:18:58 +00007411 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007412 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007413 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007414
7415 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7416 } else {
7417 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007418 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007419
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007420 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007421 if (I.getOpcode() == Instruction::Shl) {
7422 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7423 ShiftOp->getOpcode() == Instruction::AShr);
7424 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007425 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007426 ConstantInt::get(Ty, ShiftDiff));
7427 InsertNewInstBefore(Shift, I);
7428
Reid Spencer55702aa2007-03-25 21:11:44 +00007429 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007430 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007431 }
7432
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007433 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007434 if (I.getOpcode() == Instruction::LShr) {
7435 assert(ShiftOp->getOpcode() == Instruction::Shl);
7436 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007437 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007438 InsertNewInstBefore(Shift, I);
7439
Reid Spencer68d27cf2007-03-26 23:45:51 +00007440 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007441 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007442 }
7443
7444 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007445 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007446 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007447 return 0;
7448}
7449
Chris Lattnera1be5662002-05-02 17:06:02 +00007450
Chris Lattnercfd65102005-10-29 04:36:15 +00007451/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7452/// expression. If so, decompose it, returning some value X, such that Val is
7453/// X*Scale+Offset.
7454///
7455static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007456 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007457 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007458 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007459 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007460 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007461 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007462 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7463 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7464 if (I->getOpcode() == Instruction::Shl) {
7465 // This is a value scaled by '1 << the shift amt'.
7466 Scale = 1U << RHS->getZExtValue();
7467 Offset = 0;
7468 return I->getOperand(0);
7469 } else if (I->getOpcode() == Instruction::Mul) {
7470 // This value is scaled by 'RHS'.
7471 Scale = RHS->getZExtValue();
7472 Offset = 0;
7473 return I->getOperand(0);
7474 } else if (I->getOpcode() == Instruction::Add) {
7475 // We have X+C. Check to see if we really have (X*C2)+C1,
7476 // where C1 is divisible by C2.
7477 unsigned SubScale;
7478 Value *SubVal =
7479 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7480 Offset += RHS->getZExtValue();
7481 Scale = SubScale;
7482 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007483 }
7484 }
7485 }
7486
7487 // Otherwise, we can't look past this.
7488 Scale = 1;
7489 Offset = 0;
7490 return Val;
7491}
7492
7493
Chris Lattnerb3f83972005-10-24 06:03:58 +00007494/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7495/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007496Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007497 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007498 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007499
Chris Lattnerb53c2382005-10-24 06:22:12 +00007500 // Remove any uses of AI that are dead.
7501 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007502
Chris Lattnerb53c2382005-10-24 06:22:12 +00007503 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7504 Instruction *User = cast<Instruction>(*UI++);
7505 if (isInstructionTriviallyDead(User)) {
7506 while (UI != E && *UI == User)
7507 ++UI; // If this instruction uses AI more than once, don't break UI.
7508
Chris Lattnerb53c2382005-10-24 06:22:12 +00007509 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007510 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007511 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007512 }
7513 }
7514
Chris Lattnerb3f83972005-10-24 06:03:58 +00007515 // Get the type really allocated and the type casted to.
7516 const Type *AllocElTy = AI.getAllocatedType();
7517 const Type *CastElTy = PTy->getElementType();
7518 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007519
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007520 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7521 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007522 if (CastElTyAlign < AllocElTyAlign) return 0;
7523
Chris Lattner39387a52005-10-24 06:35:18 +00007524 // If the allocation has multiple uses, only promote it if we are strictly
7525 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007526 // same, we open the door to infinite loops of various kinds. (A reference
7527 // from a dbg.declare doesn't count as a use for this purpose.)
7528 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7529 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007530
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007531 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7532 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007533 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007534
Chris Lattner455fcc82005-10-29 03:19:53 +00007535 // See if we can satisfy the modulus by pulling a scale out of the array
7536 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007537 unsigned ArraySizeScale;
7538 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007539 Value *NumElements = // See if the array size is a decomposable linear expr.
7540 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7541
Chris Lattner455fcc82005-10-29 03:19:53 +00007542 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7543 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007544 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7545 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007546
Chris Lattner455fcc82005-10-29 03:19:53 +00007547 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7548 Value *Amt = 0;
7549 if (Scale == 1) {
7550 Amt = NumElements;
7551 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007552 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007553 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7554 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007555 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007556 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007557 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007558 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007559 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007560 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007561 }
7562
Jeff Cohen86796be2007-04-04 16:58:57 +00007563 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7564 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007565 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007566 Amt = InsertNewInstBefore(Tmp, AI);
7567 }
7568
Chris Lattnerb3f83972005-10-24 06:03:58 +00007569 AllocationInst *New;
7570 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007571 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007572 else
Chris Lattner6934a042007-02-11 01:23:03 +00007573 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007574 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007575 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007576
Dale Johannesena0a66372009-03-05 00:39:02 +00007577 // If the allocation has one real use plus a dbg.declare, just remove the
7578 // declare.
7579 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7580 EraseInstFromFunction(*DI);
7581 }
7582 // If the allocation has multiple real uses, insert a cast and change all
7583 // things that used it to use the new cast. This will also hack on CI, but it
7584 // will die soon.
7585 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007586 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007587 // New is the allocation instruction, pointer typed. AI is the original
7588 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7589 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007590 InsertNewInstBefore(NewCast, AI);
7591 AI.replaceAllUsesWith(NewCast);
7592 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007593 return ReplaceInstUsesWith(CI, New);
7594}
7595
Chris Lattner70074e02006-05-13 02:06:03 +00007596/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007597/// and return it as type Ty without inserting any new casts and without
7598/// changing the computed value. This is used by code that tries to decide
7599/// whether promoting or shrinking integer operations to wider or smaller types
7600/// will allow us to eliminate a truncate or extend.
7601///
7602/// This is a truncation operation if Ty is smaller than V->getType(), or an
7603/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007604///
7605/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7606/// should return true if trunc(V) can be computed by computing V in the smaller
7607/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7608/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7609/// efficiently truncated.
7610///
7611/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7612/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7613/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007614bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7615 unsigned CastOpc,
7616 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007617 // We can always evaluate constants in another type.
7618 if (isa<ConstantInt>(V))
7619 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007620
7621 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007622 if (!I) return false;
7623
7624 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007625
Chris Lattner951626b2007-08-02 06:11:14 +00007626 // If this is an extension or truncate, we can often eliminate it.
7627 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7628 // If this is a cast from the destination type, we can trivially eliminate
7629 // it, and this will remove a cast overall.
7630 if (I->getOperand(0)->getType() == Ty) {
7631 // If the first operand is itself a cast, and is eliminable, do not count
7632 // this as an eliminable cast. We would prefer to eliminate those two
7633 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007634 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007635 ++NumCastsRemoved;
7636 return true;
7637 }
7638 }
7639
7640 // We can't extend or shrink something that has multiple uses: doing so would
7641 // require duplicating the instruction in general, which isn't profitable.
7642 if (!I->hasOneUse()) return false;
7643
Evan Chengf35fd542009-01-15 17:01:23 +00007644 unsigned Opc = I->getOpcode();
7645 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007646 case Instruction::Add:
7647 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007648 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007649 case Instruction::And:
7650 case Instruction::Or:
7651 case Instruction::Xor:
7652 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007653 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007654 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007655 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007656 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007657
Chris Lattner46b96052006-11-29 07:18:39 +00007658 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007659 // If we are truncating the result of this SHL, and if it's a shift of a
7660 // constant amount, we can always perform a SHL in a smaller type.
7661 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007662 uint32_t BitWidth = Ty->getBitWidth();
7663 if (BitWidth < OrigTy->getBitWidth() &&
7664 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007665 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007666 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007667 }
7668 break;
7669 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007670 // If this is a truncate of a logical shr, we can truncate it to a smaller
7671 // lshr iff we know that the bits we would otherwise be shifting in are
7672 // already zeros.
7673 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007674 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7675 uint32_t BitWidth = Ty->getBitWidth();
7676 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007677 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007678 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7679 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007680 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007681 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007682 }
7683 }
Chris Lattner46b96052006-11-29 07:18:39 +00007684 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007685 case Instruction::ZExt:
7686 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007687 case Instruction::Trunc:
7688 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007689 // can safely replace it. Note that replacing it does not reduce the number
7690 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007691 if (Opc == CastOpc)
7692 return true;
7693
7694 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007695 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007696 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007697 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007698 case Instruction::Select: {
7699 SelectInst *SI = cast<SelectInst>(I);
7700 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007701 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007702 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007703 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007704 }
Chris Lattner8114b712008-06-18 04:00:49 +00007705 case Instruction::PHI: {
7706 // We can change a phi if we can change all operands.
7707 PHINode *PN = cast<PHINode>(I);
7708 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7709 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007710 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007711 return false;
7712 return true;
7713 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007714 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007715 // TODO: Can handle more cases here.
7716 break;
7717 }
7718
7719 return false;
7720}
7721
7722/// EvaluateInDifferentType - Given an expression that
7723/// CanEvaluateInDifferentType returns true for, actually insert the code to
7724/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007725Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007726 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007727 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007728 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007729
7730 // Otherwise, it must be an instruction.
7731 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007732 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007733 unsigned Opc = I->getOpcode();
7734 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007735 case Instruction::Add:
7736 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007737 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007738 case Instruction::And:
7739 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007740 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007741 case Instruction::AShr:
7742 case Instruction::LShr:
7743 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007744 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007745 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007746 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007747 break;
7748 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007749 case Instruction::Trunc:
7750 case Instruction::ZExt:
7751 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007752 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007753 // just return the source. There's no need to insert it because it is not
7754 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007755 if (I->getOperand(0)->getType() == Ty)
7756 return I->getOperand(0);
7757
Chris Lattner8114b712008-06-18 04:00:49 +00007758 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007759 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007760 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007761 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007762 case Instruction::Select: {
7763 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7764 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7765 Res = SelectInst::Create(I->getOperand(0), True, False);
7766 break;
7767 }
Chris Lattner8114b712008-06-18 04:00:49 +00007768 case Instruction::PHI: {
7769 PHINode *OPN = cast<PHINode>(I);
7770 PHINode *NPN = PHINode::Create(Ty);
7771 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7772 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7773 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7774 }
7775 Res = NPN;
7776 break;
7777 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007778 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007779 // TODO: Can handle more cases here.
7780 assert(0 && "Unreachable!");
7781 break;
7782 }
7783
Chris Lattner8114b712008-06-18 04:00:49 +00007784 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007785 return InsertNewInstBefore(Res, *I);
7786}
7787
Reid Spencer3da59db2006-11-27 01:05:10 +00007788/// @brief Implement the transforms common to all CastInst visitors.
7789Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007790 Value *Src = CI.getOperand(0);
7791
Dan Gohman23d9d272007-05-11 21:10:54 +00007792 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007793 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007794 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007795 if (Instruction::CastOps opc =
7796 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7797 // The first cast (CSrc) is eliminable so we need to fix up or replace
7798 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007799 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007800 }
7801 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007802
Reid Spencer3da59db2006-11-27 01:05:10 +00007803 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007804 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7805 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7806 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007807
7808 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007809 if (isa<PHINode>(Src))
7810 if (Instruction *NV = FoldOpIntoPhi(CI))
7811 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007812
Reid Spencer3da59db2006-11-27 01:05:10 +00007813 return 0;
7814}
7815
Chris Lattner46cd5a12009-01-09 05:44:56 +00007816/// FindElementAtOffset - Given a type and a constant offset, determine whether
7817/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007818/// the specified offset. If so, fill them into NewIndices and return the
7819/// resultant element type, otherwise return null.
7820static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7821 SmallVectorImpl<Value*> &NewIndices,
7822 const TargetData *TD) {
7823 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007824
7825 // Start with the index over the outer type. Note that the type size
7826 // might be zero (even if the offset isn't zero) if the indexed type
7827 // is something like [0 x {int, int}]
7828 const Type *IntPtrTy = TD->getIntPtrType();
7829 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007830 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007831 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007832 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007833
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007834 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007835 if (Offset < 0) {
7836 --FirstIdx;
7837 Offset += TySize;
7838 assert(Offset >= 0);
7839 }
7840 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7841 }
7842
7843 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7844
7845 // Index into the types. If we fail, set OrigBase to null.
7846 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007847 // Indexing into tail padding between struct/array elements.
7848 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007849 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007850
Chris Lattner46cd5a12009-01-09 05:44:56 +00007851 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7852 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007853 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7854 "Offset must stay within the indexed type");
7855
Chris Lattner46cd5a12009-01-09 05:44:56 +00007856 unsigned Elt = SL->getElementContainingOffset(Offset);
7857 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7858
7859 Offset -= SL->getElementOffset(Elt);
7860 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007861 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007862 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007863 assert(EltSize && "Cannot index into a zero-sized array");
7864 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7865 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007866 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007867 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007868 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007869 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007870 }
7871 }
7872
Chris Lattner3914f722009-01-24 01:00:13 +00007873 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007874}
7875
Chris Lattnerd3e28342007-04-27 17:44:50 +00007876/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7877Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7878 Value *Src = CI.getOperand(0);
7879
Chris Lattnerd3e28342007-04-27 17:44:50 +00007880 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007881 // If casting the result of a getelementptr instruction with no offset, turn
7882 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007883 if (GEP->hasAllZeroIndices()) {
7884 // Changing the cast operand is usually not a good idea but it is safe
7885 // here because the pointer operand is being replaced with another
7886 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007887 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007888 CI.setOperand(0, GEP->getOperand(0));
7889 return &CI;
7890 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007891
7892 // If the GEP has a single use, and the base pointer is a bitcast, and the
7893 // GEP computes a constant offset, see if we can convert these three
7894 // instructions into fewer. This typically happens with unions and other
7895 // non-type-safe code.
7896 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7897 if (GEP->hasAllConstantIndices()) {
7898 // We are guaranteed to get a constant from EmitGEPOffset.
7899 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7900 int64_t Offset = OffsetV->getSExtValue();
7901
7902 // Get the base pointer input of the bitcast, and the type it points to.
7903 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7904 const Type *GEPIdxTy =
7905 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007906 SmallVector<Value*, 8> NewIndices;
7907 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7908 // If we were able to index down into an element, create the GEP
7909 // and bitcast the result. This eliminates one bitcast, potentially
7910 // two.
7911 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7912 NewIndices.begin(),
7913 NewIndices.end(), "");
7914 InsertNewInstBefore(NGEP, CI);
7915 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007916
Chris Lattner46cd5a12009-01-09 05:44:56 +00007917 if (isa<BitCastInst>(CI))
7918 return new BitCastInst(NGEP, CI.getType());
7919 assert(isa<PtrToIntInst>(CI));
7920 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007921 }
7922 }
7923 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007924 }
7925
7926 return commonCastTransforms(CI);
7927}
7928
7929
Chris Lattnerc739cd62007-03-03 05:27:34 +00007930/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7931/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007932/// cases.
7933/// @brief Implement the transforms common to CastInst with integer operands
7934Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7935 if (Instruction *Result = commonCastTransforms(CI))
7936 return Result;
7937
7938 Value *Src = CI.getOperand(0);
7939 const Type *SrcTy = Src->getType();
7940 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007941 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7942 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007943
Reid Spencer3da59db2006-11-27 01:05:10 +00007944 // See if we can simplify any instructions used by the LHS whose sole
7945 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007946 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007947 return &CI;
7948
7949 // If the source isn't an instruction or has more than one use then we
7950 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007951 Instruction *SrcI = dyn_cast<Instruction>(Src);
7952 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007953 return 0;
7954
Chris Lattnerc739cd62007-03-03 05:27:34 +00007955 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007956 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007957 if (!isa<BitCastInst>(CI) &&
7958 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007959 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007960 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007961 // eliminates the cast, so it is always a win. If this is a zero-extension,
7962 // we need to do an AND to maintain the clear top-part of the computation,
7963 // so we require that the input have eliminated at least one cast. If this
7964 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007965 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007966 bool DoXForm = false;
7967 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007968 switch (CI.getOpcode()) {
7969 default:
7970 // All the others use floating point so we shouldn't actually
7971 // get here because of the check above.
7972 assert(0 && "Unknown cast type");
7973 case Instruction::Trunc:
7974 DoXForm = true;
7975 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007976 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007977 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007978 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007979 // If it's unnecessary to issue an AND to clear the high bits, it's
7980 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00007981 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007982 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7983 if (MaskedValueIsZero(TryRes, Mask))
7984 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007985
7986 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007987 if (TryI->use_empty())
7988 EraseInstFromFunction(*TryI);
7989 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007990 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007991 }
Evan Chengf35fd542009-01-15 17:01:23 +00007992 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007993 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007994 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007995 // If we do not have to emit the truncate + sext pair, then it's always
7996 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007997 //
7998 // It's not safe to eliminate the trunc + sext pair if one of the
7999 // eliminated cast is a truncate. e.g.
8000 // t2 = trunc i32 t1 to i16
8001 // t3 = sext i16 t2 to i32
8002 // !=
8003 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008004 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008005 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8006 if (NumSignBits > (DestBitSize - SrcBitSize))
8007 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008008
8009 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008010 if (TryI->use_empty())
8011 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008012 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008013 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008014 }
Evan Chengf35fd542009-01-15 17:01:23 +00008015 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008016
8017 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008018 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8019 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008020 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8021 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008022 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008023 // Just replace this cast with the result.
8024 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008025
Reid Spencer3da59db2006-11-27 01:05:10 +00008026 assert(Res->getType() == DestTy);
8027 switch (CI.getOpcode()) {
8028 default: assert(0 && "Unknown cast type!");
8029 case Instruction::Trunc:
8030 case Instruction::BitCast:
8031 // Just replace this cast with the result.
8032 return ReplaceInstUsesWith(CI, Res);
8033 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008034 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008035
8036 // If the high bits are already zero, just replace this cast with the
8037 // result.
8038 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8039 if (MaskedValueIsZero(Res, Mask))
8040 return ReplaceInstUsesWith(CI, Res);
8041
8042 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008043 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8044 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008045 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008046 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008047 case Instruction::SExt: {
8048 // If the high bits are already filled with sign bit, just replace this
8049 // cast with the result.
8050 unsigned NumSignBits = ComputeNumSignBits(Res);
8051 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008052 return ReplaceInstUsesWith(CI, Res);
8053
Reid Spencer3da59db2006-11-27 01:05:10 +00008054 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008055 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008056 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8057 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008058 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008059 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008060 }
8061 }
8062
8063 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8064 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8065
8066 switch (SrcI->getOpcode()) {
8067 case Instruction::Add:
8068 case Instruction::Mul:
8069 case Instruction::And:
8070 case Instruction::Or:
8071 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008072 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008073 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8074 // Don't insert two casts if they cannot be eliminated. We allow
8075 // two casts to be inserted if the sizes are the same. This could
8076 // only be converting signedness, which is a noop.
8077 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008078 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8079 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008080 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008081 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8082 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008083 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008084 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008085 }
8086 }
8087
8088 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8089 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8090 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008091 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008092 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008093 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008094 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 }
8096 break;
8097 case Instruction::SDiv:
8098 case Instruction::UDiv:
8099 case Instruction::SRem:
8100 case Instruction::URem:
8101 // If we are just changing the sign, rewrite.
8102 if (DestBitSize == SrcBitSize) {
8103 // Don't insert two casts if they cannot be eliminated. We allow
8104 // two casts to be inserted if the sizes are the same. This could
8105 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008106 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8107 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008108 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8109 Op0, DestTy, *SrcI);
8110 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8111 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008112 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008113 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8114 }
8115 }
8116 break;
8117
8118 case Instruction::Shl:
8119 // Allow changing the sign of the source operand. Do not allow
8120 // changing the size of the shift, UNLESS the shift amount is a
8121 // constant. We must not change variable sized shifts to a smaller
8122 // size, because it is undefined to shift more bits out than exist
8123 // in the value.
8124 if (DestBitSize == SrcBitSize ||
8125 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008126 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8127 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008128 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8129 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008130 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008131 }
8132 break;
8133 case Instruction::AShr:
8134 // If this is a signed shr, and if all bits shifted in are about to be
8135 // truncated off, turn it into an unsigned shr to allow greater
8136 // simplifications.
8137 if (DestBitSize < SrcBitSize &&
8138 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008139 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008140 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8141 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008142 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008143 }
8144 }
8145 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008146 }
8147 return 0;
8148}
8149
Chris Lattner8a9f5712007-04-11 06:57:46 +00008150Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008151 if (Instruction *Result = commonIntCastTransforms(CI))
8152 return Result;
8153
8154 Value *Src = CI.getOperand(0);
8155 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008156 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8157 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008158
8159 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8160 if (DestBitWidth == 1) {
8161 Constant *One = ConstantInt::get(Src->getType(), 1);
8162 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8163 Value *Zero = Constant::getNullValue(Src->getType());
8164 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8165 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008166
Chris Lattner4f9797d2009-03-24 18:15:30 +00008167 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8168 ConstantInt *ShAmtV = 0;
8169 Value *ShiftOp = 0;
8170 if (Src->hasOneUse() &&
8171 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8172 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8173
8174 // Get a mask for the bits shifting in.
8175 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8176 if (MaskedValueIsZero(ShiftOp, Mask)) {
8177 if (ShAmt >= DestBitWidth) // All zeros.
8178 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8179
8180 // Okay, we can shrink this. Truncate the input, then return a new
8181 // shift.
8182 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8183 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8184 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008185 }
8186 }
8187
8188 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008189}
8190
Evan Chengb98a10e2008-03-24 00:21:34 +00008191/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8192/// in order to eliminate the icmp.
8193Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8194 bool DoXform) {
8195 // If we are just checking for a icmp eq of a single bit and zext'ing it
8196 // to an integer, then shift the bit to the appropriate place and then
8197 // cast to integer to avoid the comparison.
8198 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8199 const APInt &Op1CV = Op1C->getValue();
8200
8201 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8202 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8203 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8204 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8205 if (!DoXform) return ICI;
8206
8207 Value *In = ICI->getOperand(0);
8208 Value *Sh = ConstantInt::get(In->getType(),
8209 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008210 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008211 In->getName()+".lobit"),
8212 CI);
8213 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008214 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008215 false/*ZExt*/, "tmp", &CI);
8216
8217 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8218 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008219 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008220 In->getName()+".not"),
8221 CI);
8222 }
8223
8224 return ReplaceInstUsesWith(CI, In);
8225 }
8226
8227
8228
8229 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8230 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8231 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8232 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8233 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8234 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8235 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8236 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8237 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8238 // This only works for EQ and NE
8239 ICI->isEquality()) {
8240 // If Op1C some other power of two, convert:
8241 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8242 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8243 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8244 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8245
8246 APInt KnownZeroMask(~KnownZero);
8247 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8248 if (!DoXform) return ICI;
8249
8250 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8251 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8252 // (X&4) == 2 --> false
8253 // (X&4) != 2 --> true
8254 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8255 Res = ConstantExpr::getZExt(Res, CI.getType());
8256 return ReplaceInstUsesWith(CI, Res);
8257 }
8258
8259 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8260 Value *In = ICI->getOperand(0);
8261 if (ShiftAmt) {
8262 // Perform a logical shr by shiftamt.
8263 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008264 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008265 ConstantInt::get(In->getType(), ShiftAmt),
8266 In->getName()+".lobit"), CI);
8267 }
8268
8269 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8270 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008271 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008272 InsertNewInstBefore(cast<Instruction>(In), CI);
8273 }
8274
8275 if (CI.getType() == In->getType())
8276 return ReplaceInstUsesWith(CI, In);
8277 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008278 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008279 }
8280 }
8281 }
8282
8283 return 0;
8284}
8285
Chris Lattner8a9f5712007-04-11 06:57:46 +00008286Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 // If one of the common conversion will work ..
8288 if (Instruction *Result = commonIntCastTransforms(CI))
8289 return Result;
8290
8291 Value *Src = CI.getOperand(0);
8292
Chris Lattnera84f47c2009-02-17 20:47:23 +00008293 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8294 // types and if the sizes are just right we can convert this into a logical
8295 // 'and' which will be much cheaper than the pair of casts.
8296 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8297 // Get the sizes of the types involved. We know that the intermediate type
8298 // will be smaller than A or C, but don't know the relation between A and C.
8299 Value *A = CSrc->getOperand(0);
8300 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8301 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8302 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8303 // If we're actually extending zero bits, then if
8304 // SrcSize < DstSize: zext(a & mask)
8305 // SrcSize == DstSize: a & mask
8306 // SrcSize > DstSize: trunc(a) & mask
8307 if (SrcSize < DstSize) {
8308 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8309 Constant *AndConst = ConstantInt::get(AndValue);
8310 Instruction *And =
8311 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8312 InsertNewInstBefore(And, CI);
8313 return new ZExtInst(And, CI.getType());
8314 } else if (SrcSize == DstSize) {
8315 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8316 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8317 } else if (SrcSize > DstSize) {
8318 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8319 InsertNewInstBefore(Trunc, CI);
8320 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8321 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008322 }
8323 }
8324
Evan Chengb98a10e2008-03-24 00:21:34 +00008325 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8326 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008327
Evan Chengb98a10e2008-03-24 00:21:34 +00008328 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8329 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8330 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8331 // of the (zext icmp) will be transformed.
8332 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8333 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8334 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8335 (transformZExtICmp(LHS, CI, false) ||
8336 transformZExtICmp(RHS, CI, false))) {
8337 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8338 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008339 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008340 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008341 }
8342
Reid Spencer3da59db2006-11-27 01:05:10 +00008343 return 0;
8344}
8345
Chris Lattner8a9f5712007-04-11 06:57:46 +00008346Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008347 if (Instruction *I = commonIntCastTransforms(CI))
8348 return I;
8349
Chris Lattner8a9f5712007-04-11 06:57:46 +00008350 Value *Src = CI.getOperand(0);
8351
Dan Gohman1975d032008-10-30 20:40:10 +00008352 // Canonicalize sign-extend from i1 to a select.
8353 if (Src->getType() == Type::Int1Ty)
8354 return SelectInst::Create(Src,
8355 ConstantInt::getAllOnesValue(CI.getType()),
8356 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008357
8358 // See if the value being truncated is already sign extended. If so, just
8359 // eliminate the trunc/sext pair.
8360 if (getOpcode(Src) == Instruction::Trunc) {
8361 Value *Op = cast<User>(Src)->getOperand(0);
8362 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8363 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8364 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8365 unsigned NumSignBits = ComputeNumSignBits(Op);
8366
8367 if (OpBits == DestBits) {
8368 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8369 // bits, it is already ready.
8370 if (NumSignBits > DestBits-MidBits)
8371 return ReplaceInstUsesWith(CI, Op);
8372 } else if (OpBits < DestBits) {
8373 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8374 // bits, just sext from i32.
8375 if (NumSignBits > OpBits-MidBits)
8376 return new SExtInst(Op, CI.getType(), "tmp");
8377 } else {
8378 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8379 // bits, just truncate to i32.
8380 if (NumSignBits > OpBits-MidBits)
8381 return new TruncInst(Op, CI.getType(), "tmp");
8382 }
8383 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008384
8385 // If the input is a shl/ashr pair of a same constant, then this is a sign
8386 // extension from a smaller value. If we could trust arbitrary bitwidth
8387 // integers, we could turn this into a truncate to the smaller bit and then
8388 // use a sext for the whole extension. Since we don't, look deeper and check
8389 // for a truncate. If the source and dest are the same type, eliminate the
8390 // trunc and extend and just do shifts. For example, turn:
8391 // %a = trunc i32 %i to i8
8392 // %b = shl i8 %a, 6
8393 // %c = ashr i8 %b, 6
8394 // %d = sext i8 %c to i32
8395 // into:
8396 // %a = shl i32 %i, 30
8397 // %d = ashr i32 %a, 30
8398 Value *A = 0;
8399 ConstantInt *BA = 0, *CA = 0;
8400 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8401 m_ConstantInt(CA))) &&
8402 BA == CA && isa<TruncInst>(A)) {
8403 Value *I = cast<TruncInst>(A)->getOperand(0);
8404 if (I->getType() == CI.getType()) {
8405 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8406 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8407 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8408 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8409 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8410 CI.getName()), CI);
8411 return BinaryOperator::CreateAShr(I, ShAmtV);
8412 }
8413 }
8414
Chris Lattnerba417832007-04-11 06:12:58 +00008415 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008416}
8417
Chris Lattnerb7530652008-01-27 05:29:54 +00008418/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8419/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008420static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008421 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008422 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008423 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8424 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008425 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008426 return 0;
8427}
8428
8429/// LookThroughFPExtensions - If this is an fp extension instruction, look
8430/// through it until we get the source value.
8431static Value *LookThroughFPExtensions(Value *V) {
8432 if (Instruction *I = dyn_cast<Instruction>(V))
8433 if (I->getOpcode() == Instruction::FPExt)
8434 return LookThroughFPExtensions(I->getOperand(0));
8435
8436 // If this value is a constant, return the constant in the smallest FP type
8437 // that can accurately represent it. This allows us to turn
8438 // (float)((double)X+2.0) into x+2.0f.
8439 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8440 if (CFP->getType() == Type::PPC_FP128Ty)
8441 return V; // No constant folding of this.
8442 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008443 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008444 return V;
8445 if (CFP->getType() == Type::DoubleTy)
8446 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008447 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008448 return V;
8449 // Don't try to shrink to various long double types.
8450 }
8451
8452 return V;
8453}
8454
8455Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8456 if (Instruction *I = commonCastTransforms(CI))
8457 return I;
8458
8459 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8460 // smaller than the destination type, we can eliminate the truncate by doing
8461 // the add as the smaller type. This applies to add/sub/mul/div as well as
8462 // many builtins (sqrt, etc).
8463 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8464 if (OpI && OpI->hasOneUse()) {
8465 switch (OpI->getOpcode()) {
8466 default: break;
8467 case Instruction::Add:
8468 case Instruction::Sub:
8469 case Instruction::Mul:
8470 case Instruction::FDiv:
8471 case Instruction::FRem:
8472 const Type *SrcTy = OpI->getType();
8473 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8474 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8475 if (LHSTrunc->getType() != SrcTy &&
8476 RHSTrunc->getType() != SrcTy) {
8477 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8478 // If the source types were both smaller than the destination type of
8479 // the cast, do this xform.
8480 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8481 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8482 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8483 CI.getType(), CI);
8484 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8485 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008486 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008487 }
8488 }
8489 break;
8490 }
8491 }
8492 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008493}
8494
8495Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8496 return commonCastTransforms(CI);
8497}
8498
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008499Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008500 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8501 if (OpI == 0)
8502 return commonCastTransforms(FI);
8503
8504 // fptoui(uitofp(X)) --> X
8505 // fptoui(sitofp(X)) --> X
8506 // This is safe if the intermediate type has enough bits in its mantissa to
8507 // accurately represent all values of X. For example, do not do this with
8508 // i64->float->i64. This is also safe for sitofp case, because any negative
8509 // 'X' value would cause an undefined result for the fptoui.
8510 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8511 OpI->getOperand(0)->getType() == FI.getType() &&
8512 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8513 OpI->getType()->getFPMantissaWidth())
8514 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008515
8516 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008517}
8518
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008519Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008520 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8521 if (OpI == 0)
8522 return commonCastTransforms(FI);
8523
8524 // fptosi(sitofp(X)) --> X
8525 // fptosi(uitofp(X)) --> X
8526 // This is safe if the intermediate type has enough bits in its mantissa to
8527 // accurately represent all values of X. For example, do not do this with
8528 // i64->float->i64. This is also safe for sitofp case, because any negative
8529 // 'X' value would cause an undefined result for the fptoui.
8530 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8531 OpI->getOperand(0)->getType() == FI.getType() &&
8532 (int)FI.getType()->getPrimitiveSizeInBits() <=
8533 OpI->getType()->getFPMantissaWidth())
8534 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008535
8536 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008537}
8538
8539Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8540 return commonCastTransforms(CI);
8541}
8542
8543Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8544 return commonCastTransforms(CI);
8545}
8546
Chris Lattnera0e69692009-03-24 18:35:40 +00008547Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8548 // If the destination integer type is smaller than the intptr_t type for
8549 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8550 // trunc to be exposed to other transforms. Don't do this for extending
8551 // ptrtoint's, because we don't know if the target sign or zero extends its
8552 // pointers.
8553 if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8554 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8555 TD->getIntPtrType(),
8556 "tmp"), CI);
8557 return new TruncInst(P, CI.getType());
8558 }
8559
Chris Lattnerd3e28342007-04-27 17:44:50 +00008560 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008561}
8562
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008563Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008564 // If the source integer type is larger than the intptr_t type for
8565 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8566 // allows the trunc to be exposed to other transforms. Don't do this for
8567 // extending inttoptr's, because we don't know if the target sign or zero
8568 // extends to pointers.
8569 if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8570 TD->getPointerSizeInBits()) {
8571 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8572 TD->getIntPtrType(),
8573 "tmp"), CI);
8574 return new IntToPtrInst(P, CI.getType());
8575 }
8576
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008577 if (Instruction *I = commonCastTransforms(CI))
8578 return I;
8579
8580 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8581 if (!DestPointee->isSized()) return 0;
8582
8583 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8584 ConstantInt *Cst;
8585 Value *X;
8586 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8587 m_ConstantInt(Cst)))) {
8588 // If the source and destination operands have the same type, see if this
8589 // is a single-index GEP.
8590 if (X->getType() == CI.getType()) {
8591 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008592 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008593
8594 // Convert the constant to intptr type.
8595 APInt Offset = Cst->getValue();
8596 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8597
8598 // If Offset is evenly divisible by Size, we can do this xform.
8599 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8600 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008601 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008602 }
8603 }
8604 // TODO: Could handle other cases, e.g. where add is indexing into field of
8605 // struct etc.
8606 } else if (CI.getOperand(0)->hasOneUse() &&
8607 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8608 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8609 // "inttoptr+GEP" instead of "add+intptr".
8610
8611 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008612 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008613
8614 // Convert the constant to intptr type.
8615 APInt Offset = Cst->getValue();
8616 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8617
8618 // If Offset is evenly divisible by Size, we can do this xform.
8619 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8620 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8621
8622 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8623 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008624 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008625 }
8626 }
8627 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008628}
8629
Chris Lattnerd3e28342007-04-27 17:44:50 +00008630Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008631 // If the operands are integer typed then apply the integer transforms,
8632 // otherwise just apply the common ones.
8633 Value *Src = CI.getOperand(0);
8634 const Type *SrcTy = Src->getType();
8635 const Type *DestTy = CI.getType();
8636
Chris Lattner42a75512007-01-15 02:27:26 +00008637 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008638 if (Instruction *Result = commonIntCastTransforms(CI))
8639 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008640 } else if (isa<PointerType>(SrcTy)) {
8641 if (Instruction *I = commonPointerCastTransforms(CI))
8642 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008643 } else {
8644 if (Instruction *Result = commonCastTransforms(CI))
8645 return Result;
8646 }
8647
8648
8649 // Get rid of casts from one type to the same type. These are useless and can
8650 // be replaced by the operand.
8651 if (DestTy == Src->getType())
8652 return ReplaceInstUsesWith(CI, Src);
8653
Reid Spencer3da59db2006-11-27 01:05:10 +00008654 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008655 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8656 const Type *DstElTy = DstPTy->getElementType();
8657 const Type *SrcElTy = SrcPTy->getElementType();
8658
Nate Begeman83ad90a2008-03-31 00:22:16 +00008659 // If the address spaces don't match, don't eliminate the bitcast, which is
8660 // required for changing types.
8661 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8662 return 0;
8663
Chris Lattnerd3e28342007-04-27 17:44:50 +00008664 // If we are casting a malloc or alloca to a pointer to a type of the same
8665 // size, rewrite the allocation instruction to allocate the "right" type.
8666 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8667 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8668 return V;
8669
Chris Lattnerd717c182007-05-05 22:32:24 +00008670 // If the source and destination are pointers, and this cast is equivalent
8671 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008672 // This can enhance SROA and other transforms that want type-safe pointers.
8673 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8674 unsigned NumZeros = 0;
8675 while (SrcElTy != DstElTy &&
8676 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8677 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8678 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8679 ++NumZeros;
8680 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008681
Chris Lattnerd3e28342007-04-27 17:44:50 +00008682 // If we found a path from the src to dest, create the getelementptr now.
8683 if (SrcElTy == DstElTy) {
8684 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008685 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8686 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008687 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008688 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008689
Reid Spencer3da59db2006-11-27 01:05:10 +00008690 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8691 if (SVI->hasOneUse()) {
8692 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8693 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008694 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008695 cast<VectorType>(DestTy)->getNumElements() ==
8696 SVI->getType()->getNumElements() &&
8697 SVI->getType()->getNumElements() ==
8698 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008699 CastInst *Tmp;
8700 // If either of the operands is a cast from CI.getType(), then
8701 // evaluating the shuffle in the casted destination's type will allow
8702 // us to eliminate at least one cast.
8703 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8704 Tmp->getOperand(0)->getType() == DestTy) ||
8705 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8706 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008707 Value *LHS = InsertCastBefore(Instruction::BitCast,
8708 SVI->getOperand(0), DestTy, CI);
8709 Value *RHS = InsertCastBefore(Instruction::BitCast,
8710 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008711 // Return a new shuffle vector. Use the same element ID's, as we
8712 // know the vector types match #elts.
8713 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008714 }
8715 }
8716 }
8717 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008718 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008719}
8720
Chris Lattnere576b912004-04-09 23:46:01 +00008721/// GetSelectFoldableOperands - We want to turn code that looks like this:
8722/// %C = or %A, %B
8723/// %D = select %cond, %C, %A
8724/// into:
8725/// %C = select %cond, %B, 0
8726/// %D = or %A, %C
8727///
8728/// Assuming that the specified instruction is an operand to the select, return
8729/// a bitmask indicating which operands of this instruction are foldable if they
8730/// equal the other incoming value of the select.
8731///
8732static unsigned GetSelectFoldableOperands(Instruction *I) {
8733 switch (I->getOpcode()) {
8734 case Instruction::Add:
8735 case Instruction::Mul:
8736 case Instruction::And:
8737 case Instruction::Or:
8738 case Instruction::Xor:
8739 return 3; // Can fold through either operand.
8740 case Instruction::Sub: // Can only fold on the amount subtracted.
8741 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008742 case Instruction::LShr:
8743 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008744 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008745 default:
8746 return 0; // Cannot fold
8747 }
8748}
8749
8750/// GetSelectFoldableConstant - For the same transformation as the previous
8751/// function, return the identity constant that goes into the select.
8752static Constant *GetSelectFoldableConstant(Instruction *I) {
8753 switch (I->getOpcode()) {
8754 default: assert(0 && "This cannot happen!"); abort();
8755 case Instruction::Add:
8756 case Instruction::Sub:
8757 case Instruction::Or:
8758 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008759 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008760 case Instruction::LShr:
8761 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008762 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008763 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008764 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008765 case Instruction::Mul:
8766 return ConstantInt::get(I->getType(), 1);
8767 }
8768}
8769
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008770/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8771/// have the same opcode and only one use each. Try to simplify this.
8772Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8773 Instruction *FI) {
8774 if (TI->getNumOperands() == 1) {
8775 // If this is a non-volatile load or a cast from the same type,
8776 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008777 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008778 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8779 return 0;
8780 } else {
8781 return 0; // unknown unary op.
8782 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008783
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008784 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008785 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8786 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008787 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008788 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008789 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008790 }
8791
Reid Spencer832254e2007-02-02 02:16:23 +00008792 // Only handle binary operators here.
8793 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008794 return 0;
8795
8796 // Figure out if the operations have any operands in common.
8797 Value *MatchOp, *OtherOpT, *OtherOpF;
8798 bool MatchIsOpZero;
8799 if (TI->getOperand(0) == FI->getOperand(0)) {
8800 MatchOp = TI->getOperand(0);
8801 OtherOpT = TI->getOperand(1);
8802 OtherOpF = FI->getOperand(1);
8803 MatchIsOpZero = true;
8804 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8805 MatchOp = TI->getOperand(1);
8806 OtherOpT = TI->getOperand(0);
8807 OtherOpF = FI->getOperand(0);
8808 MatchIsOpZero = false;
8809 } else if (!TI->isCommutative()) {
8810 return 0;
8811 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8812 MatchOp = TI->getOperand(0);
8813 OtherOpT = TI->getOperand(1);
8814 OtherOpF = FI->getOperand(0);
8815 MatchIsOpZero = true;
8816 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8817 MatchOp = TI->getOperand(1);
8818 OtherOpT = TI->getOperand(0);
8819 OtherOpF = FI->getOperand(1);
8820 MatchIsOpZero = true;
8821 } else {
8822 return 0;
8823 }
8824
8825 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008826 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8827 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008828 InsertNewInstBefore(NewSI, SI);
8829
8830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8831 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008832 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008833 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008834 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008835 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008836 assert(0 && "Shouldn't get here");
8837 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008838}
8839
Evan Chengde621922009-03-31 20:42:45 +00008840static bool isSelect01(Constant *C1, Constant *C2) {
8841 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8842 if (!C1I)
8843 return false;
8844 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8845 if (!C2I)
8846 return false;
8847 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8848}
8849
8850/// FoldSelectIntoOp - Try fold the select into one of the operands to
8851/// facilitate further optimization.
8852Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8853 Value *FalseVal) {
8854 // See the comment above GetSelectFoldableOperands for a description of the
8855 // transformation we are doing here.
8856 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8857 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8858 !isa<Constant>(FalseVal)) {
8859 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8860 unsigned OpToFold = 0;
8861 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8862 OpToFold = 1;
8863 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8864 OpToFold = 2;
8865 }
8866
8867 if (OpToFold) {
8868 Constant *C = GetSelectFoldableConstant(TVI);
8869 Value *OOp = TVI->getOperand(2-OpToFold);
8870 // Avoid creating select between 2 constants unless it's selecting
8871 // between 0 and 1.
8872 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8873 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8874 InsertNewInstBefore(NewSel, SI);
8875 NewSel->takeName(TVI);
8876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8877 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8878 assert(0 && "Unknown instruction!!");
8879 }
8880 }
8881 }
8882 }
8883 }
8884
8885 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8886 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8887 !isa<Constant>(TrueVal)) {
8888 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8889 unsigned OpToFold = 0;
8890 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8891 OpToFold = 1;
8892 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8893 OpToFold = 2;
8894 }
8895
8896 if (OpToFold) {
8897 Constant *C = GetSelectFoldableConstant(FVI);
8898 Value *OOp = FVI->getOperand(2-OpToFold);
8899 // Avoid creating select between 2 constants unless it's selecting
8900 // between 0 and 1.
8901 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8902 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
8903 InsertNewInstBefore(NewSel, SI);
8904 NewSel->takeName(FVI);
8905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8906 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8907 assert(0 && "Unknown instruction!!");
8908 }
8909 }
8910 }
8911 }
8912 }
8913
8914 return 0;
8915}
8916
Dan Gohman81b28ce2008-09-16 18:46:06 +00008917/// visitSelectInstWithICmp - Visit a SelectInst that has an
8918/// ICmpInst as its first operand.
8919///
8920Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8921 ICmpInst *ICI) {
8922 bool Changed = false;
8923 ICmpInst::Predicate Pred = ICI->getPredicate();
8924 Value *CmpLHS = ICI->getOperand(0);
8925 Value *CmpRHS = ICI->getOperand(1);
8926 Value *TrueVal = SI.getTrueValue();
8927 Value *FalseVal = SI.getFalseValue();
8928
8929 // Check cases where the comparison is with a constant that
8930 // can be adjusted to fit the min/max idiom. We may edit ICI in
8931 // place here, so make sure the select is the only user.
8932 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008933 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008934 switch (Pred) {
8935 default: break;
8936 case ICmpInst::ICMP_ULT:
8937 case ICmpInst::ICMP_SLT: {
8938 // X < MIN ? T : F --> F
8939 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8940 return ReplaceInstUsesWith(SI, FalseVal);
8941 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8942 Constant *AdjustedRHS = SubOne(CI);
8943 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8944 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8945 Pred = ICmpInst::getSwappedPredicate(Pred);
8946 CmpRHS = AdjustedRHS;
8947 std::swap(FalseVal, TrueVal);
8948 ICI->setPredicate(Pred);
8949 ICI->setOperand(1, CmpRHS);
8950 SI.setOperand(1, TrueVal);
8951 SI.setOperand(2, FalseVal);
8952 Changed = true;
8953 }
8954 break;
8955 }
8956 case ICmpInst::ICMP_UGT:
8957 case ICmpInst::ICMP_SGT: {
8958 // X > MAX ? T : F --> F
8959 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8960 return ReplaceInstUsesWith(SI, FalseVal);
8961 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8962 Constant *AdjustedRHS = AddOne(CI);
8963 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8964 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8965 Pred = ICmpInst::getSwappedPredicate(Pred);
8966 CmpRHS = AdjustedRHS;
8967 std::swap(FalseVal, TrueVal);
8968 ICI->setPredicate(Pred);
8969 ICI->setOperand(1, CmpRHS);
8970 SI.setOperand(1, TrueVal);
8971 SI.setOperand(2, FalseVal);
8972 Changed = true;
8973 }
8974 break;
8975 }
8976 }
8977
Dan Gohman1975d032008-10-30 20:40:10 +00008978 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8979 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008980 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008981 if (match(TrueVal, m_ConstantInt<-1>()) &&
8982 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008983 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008984 else if (match(TrueVal, m_ConstantInt<0>()) &&
8985 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008986 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8987
Dan Gohman1975d032008-10-30 20:40:10 +00008988 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8989 // If we are just checking for a icmp eq of a single bit and zext'ing it
8990 // to an integer, then shift the bit to the appropriate place and then
8991 // cast to integer to avoid the comparison.
8992 const APInt &Op1CV = CI->getValue();
8993
8994 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8995 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8996 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008997 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008998 Value *In = ICI->getOperand(0);
8999 Value *Sh = ConstantInt::get(In->getType(),
9000 In->getType()->getPrimitiveSizeInBits()-1);
9001 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9002 In->getName()+".lobit"),
9003 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009004 if (In->getType() != SI.getType())
9005 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009006 true/*SExt*/, "tmp", ICI);
9007
9008 if (Pred == ICmpInst::ICMP_SGT)
9009 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9010 In->getName()+".not"), *ICI);
9011
9012 return ReplaceInstUsesWith(SI, In);
9013 }
9014 }
9015 }
9016
Dan Gohman81b28ce2008-09-16 18:46:06 +00009017 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9018 // Transform (X == Y) ? X : Y -> Y
9019 if (Pred == ICmpInst::ICMP_EQ)
9020 return ReplaceInstUsesWith(SI, FalseVal);
9021 // Transform (X != Y) ? X : Y -> X
9022 if (Pred == ICmpInst::ICMP_NE)
9023 return ReplaceInstUsesWith(SI, TrueVal);
9024 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9025
9026 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9027 // Transform (X == Y) ? Y : X -> X
9028 if (Pred == ICmpInst::ICMP_EQ)
9029 return ReplaceInstUsesWith(SI, FalseVal);
9030 // Transform (X != Y) ? Y : X -> Y
9031 if (Pred == ICmpInst::ICMP_NE)
9032 return ReplaceInstUsesWith(SI, TrueVal);
9033 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9034 }
9035
9036 /// NOTE: if we wanted to, this is where to detect integer ABS
9037
9038 return Changed ? &SI : 0;
9039}
9040
Chris Lattner3d69f462004-03-12 05:52:32 +00009041Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009042 Value *CondVal = SI.getCondition();
9043 Value *TrueVal = SI.getTrueValue();
9044 Value *FalseVal = SI.getFalseValue();
9045
9046 // select true, X, Y -> X
9047 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009048 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009049 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009050
9051 // select C, X, X -> X
9052 if (TrueVal == FalseVal)
9053 return ReplaceInstUsesWith(SI, TrueVal);
9054
Chris Lattnere87597f2004-10-16 18:11:37 +00009055 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9056 return ReplaceInstUsesWith(SI, FalseVal);
9057 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9058 return ReplaceInstUsesWith(SI, TrueVal);
9059 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9060 if (isa<Constant>(TrueVal))
9061 return ReplaceInstUsesWith(SI, TrueVal);
9062 else
9063 return ReplaceInstUsesWith(SI, FalseVal);
9064 }
9065
Reid Spencer4fe16d62007-01-11 18:21:29 +00009066 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009067 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009068 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009069 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009070 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009071 } else {
9072 // Change: A = select B, false, C --> A = and !B, C
9073 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009074 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009075 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009076 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009077 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009078 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009079 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009080 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009081 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009082 } else {
9083 // Change: A = select B, C, true --> A = or !B, C
9084 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009085 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009086 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009087 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009088 }
9089 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009090
9091 // select a, b, a -> a&b
9092 // select a, a, b -> a|b
9093 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009094 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009095 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009096 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009097 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009098
Chris Lattner2eefe512004-04-09 19:05:30 +00009099 // Selecting between two integer constants?
9100 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9101 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009102 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009103 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009104 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009105 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009106 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009107 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009108 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009109 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009110 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009111 }
Chris Lattner457dd822004-06-09 07:59:58 +00009112
Reid Spencere4d87aa2006-12-23 06:05:41 +00009113 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009114
Reid Spencere4d87aa2006-12-23 06:05:41 +00009115 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009116 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009117 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009118 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009119 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009120 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009121 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00009122 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009123 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009124 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009125 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009126 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009127
9128 // Then cast to the appropriate width.
9129 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009130 }
9131 }
9132
9133
9134 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009135 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009136 // non-constant value, eliminate this whole mess. This corresponds to
9137 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009138 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009139 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009140 cast<Constant>(IC->getOperand(1))->isNullValue())
9141 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9142 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009143 isa<ConstantInt>(ICA->getOperand(1)) &&
9144 (ICA->getOperand(1) == TrueValC ||
9145 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009146 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9147 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009148 // know whether we have a icmp_ne or icmp_eq and whether the
9149 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009150 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009151 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009152 Value *V = ICA;
9153 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009154 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009155 Instruction::Xor, V, ICA->getOperand(1)), SI);
9156 return ReplaceInstUsesWith(SI, V);
9157 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009158 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009159 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009160
9161 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009162 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9163 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009164 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009165 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9166 // This is not safe in general for floating point:
9167 // consider X== -0, Y== +0.
9168 // It becomes safe if either operand is a nonzero constant.
9169 ConstantFP *CFPt, *CFPf;
9170 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9171 !CFPt->getValueAPF().isZero()) ||
9172 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9173 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009174 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009175 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009176 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009177 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009178 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009179 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009180
Reid Spencere4d87aa2006-12-23 06:05:41 +00009181 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009182 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009183 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9184 // This is not safe in general for floating point:
9185 // consider X== -0, Y== +0.
9186 // It becomes safe if either operand is a nonzero constant.
9187 ConstantFP *CFPt, *CFPf;
9188 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9189 !CFPt->getValueAPF().isZero()) ||
9190 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9191 !CFPf->getValueAPF().isZero()))
9192 return ReplaceInstUsesWith(SI, FalseVal);
9193 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009194 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009195 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9196 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009197 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009198 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009199 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009200 }
9201
9202 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009203 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9204 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9205 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009206
Chris Lattner87875da2005-01-13 22:52:24 +00009207 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9208 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9209 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009210 Instruction *AddOp = 0, *SubOp = 0;
9211
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009212 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9213 if (TI->getOpcode() == FI->getOpcode())
9214 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9215 return IV;
9216
9217 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9218 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009219 if (TI->getOpcode() == Instruction::Sub &&
9220 FI->getOpcode() == Instruction::Add) {
9221 AddOp = FI; SubOp = TI;
9222 } else if (FI->getOpcode() == Instruction::Sub &&
9223 TI->getOpcode() == Instruction::Add) {
9224 AddOp = TI; SubOp = FI;
9225 }
9226
9227 if (AddOp) {
9228 Value *OtherAddOp = 0;
9229 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9230 OtherAddOp = AddOp->getOperand(1);
9231 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9232 OtherAddOp = AddOp->getOperand(0);
9233 }
9234
9235 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009236 // So at this point we know we have (Y -> OtherAddOp):
9237 // select C, (add X, Y), (sub X, Z)
9238 Value *NegVal; // Compute -Z
9239 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9240 NegVal = ConstantExpr::getNeg(C);
9241 } else {
9242 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009243 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009244 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009245
9246 Value *NewTrueOp = OtherAddOp;
9247 Value *NewFalseOp = NegVal;
9248 if (AddOp != TI)
9249 std::swap(NewTrueOp, NewFalseOp);
9250 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009251 SelectInst::Create(CondVal, NewTrueOp,
9252 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009253
9254 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009255 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009256 }
9257 }
9258 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009259
Chris Lattnere576b912004-04-09 23:46:01 +00009260 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009261 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009262 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9263 if (FoldI)
9264 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009265 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009266
9267 if (BinaryOperator::isNot(CondVal)) {
9268 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9269 SI.setOperand(1, FalseVal);
9270 SI.setOperand(2, TrueVal);
9271 return &SI;
9272 }
9273
Chris Lattner3d69f462004-03-12 05:52:32 +00009274 return 0;
9275}
9276
Dan Gohmaneee962e2008-04-10 18:43:06 +00009277/// EnforceKnownAlignment - If the specified pointer points to an object that
9278/// we control, modify the object's alignment to PrefAlign. This isn't
9279/// often possible though. If alignment is important, a more reliable approach
9280/// is to simply align all global variables and allocation instructions to
9281/// their preferred alignment from the beginning.
9282///
9283static unsigned EnforceKnownAlignment(Value *V,
9284 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009285
Dan Gohmaneee962e2008-04-10 18:43:06 +00009286 User *U = dyn_cast<User>(V);
9287 if (!U) return Align;
9288
9289 switch (getOpcode(U)) {
9290 default: break;
9291 case Instruction::BitCast:
9292 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9293 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009294 // If all indexes are zero, it is just the alignment of the base pointer.
9295 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009296 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009297 if (!isa<Constant>(*i) ||
9298 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009299 AllZeroOperands = false;
9300 break;
9301 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009302
9303 if (AllZeroOperands) {
9304 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009305 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009306 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009307 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009308 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009309 }
9310
9311 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9312 // If there is a large requested alignment and we can, bump up the alignment
9313 // of the global.
9314 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009315 if (GV->getAlignment() >= PrefAlign)
9316 Align = GV->getAlignment();
9317 else {
9318 GV->setAlignment(PrefAlign);
9319 Align = PrefAlign;
9320 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009321 }
9322 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9323 // If there is a requested alignment and if this is an alloca, round up. We
9324 // don't do this for malloc, because some systems can't respect the request.
9325 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009326 if (AI->getAlignment() >= PrefAlign)
9327 Align = AI->getAlignment();
9328 else {
9329 AI->setAlignment(PrefAlign);
9330 Align = PrefAlign;
9331 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009332 }
9333 }
9334
9335 return Align;
9336}
9337
9338/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9339/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9340/// and it is more than the alignment of the ultimate object, see if we can
9341/// increase the alignment of the ultimate object, making this check succeed.
9342unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9343 unsigned PrefAlign) {
9344 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9345 sizeof(PrefAlign) * CHAR_BIT;
9346 APInt Mask = APInt::getAllOnesValue(BitWidth);
9347 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9348 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9349 unsigned TrailZ = KnownZero.countTrailingOnes();
9350 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9351
9352 if (PrefAlign > Align)
9353 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9354
9355 // We don't need to make any adjustment.
9356 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009357}
9358
Chris Lattnerf497b022008-01-13 23:50:23 +00009359Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009360 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009361 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009362 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009363 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009364
9365 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009366 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009367 return MI;
9368 }
9369
9370 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9371 // load/store.
9372 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9373 if (MemOpLength == 0) return 0;
9374
Chris Lattner37ac6082008-01-14 00:28:35 +00009375 // Source and destination pointer types are always "i8*" for intrinsic. See
9376 // if the size is something we can handle with a single primitive load/store.
9377 // A single load+store correctly handles overlapping memory in the memmove
9378 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009379 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009380 if (Size == 0) return MI; // Delete this mem transfer.
9381
9382 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009383 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009384
Chris Lattner37ac6082008-01-14 00:28:35 +00009385 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009386 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009387
9388 // Memcpy forces the use of i8* for the source and destination. That means
9389 // that if you're using memcpy to move one double around, you'll get a cast
9390 // from double* to i8*. We'd much rather use a double load+store rather than
9391 // an i64 load+store, here because this improves the odds that the source or
9392 // dest address will be promotable. See if we can find a better type than the
9393 // integer datatype.
9394 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9395 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9396 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9397 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9398 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009399 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009400 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9401 if (STy->getNumElements() == 1)
9402 SrcETy = STy->getElementType(0);
9403 else
9404 break;
9405 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9406 if (ATy->getNumElements() == 1)
9407 SrcETy = ATy->getElementType();
9408 else
9409 break;
9410 } else
9411 break;
9412 }
9413
Dan Gohman8f8e2692008-05-23 01:52:21 +00009414 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009415 NewPtrTy = PointerType::getUnqual(SrcETy);
9416 }
9417 }
9418
9419
Chris Lattnerf497b022008-01-13 23:50:23 +00009420 // If the memcpy/memmove provides better alignment info than we can
9421 // infer, use it.
9422 SrcAlign = std::max(SrcAlign, CopyAlign);
9423 DstAlign = std::max(DstAlign, CopyAlign);
9424
9425 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9426 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009427 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9428 InsertNewInstBefore(L, *MI);
9429 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9430
9431 // Set the size of the copy to 0, it will be deleted on the next iteration.
9432 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9433 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009434}
Chris Lattner3d69f462004-03-12 05:52:32 +00009435
Chris Lattner69ea9d22008-04-30 06:39:11 +00009436Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9437 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009438 if (MI->getAlignment() < Alignment) {
9439 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009440 return MI;
9441 }
9442
9443 // Extract the length and alignment and fill if they are constant.
9444 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9445 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9446 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9447 return 0;
9448 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009449 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009450
9451 // If the length is zero, this is a no-op
9452 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9453
9454 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9455 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9456 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9457
9458 Value *Dest = MI->getDest();
9459 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9460
9461 // Alignment 0 is identity for alignment 1 for memset, but not store.
9462 if (Alignment == 0) Alignment = 1;
9463
9464 // Extract the fill value and store.
9465 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9466 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9467 Alignment), *MI);
9468
9469 // Set the size of the copy to 0, it will be deleted on the next iteration.
9470 MI->setLength(Constant::getNullValue(LenC->getType()));
9471 return MI;
9472 }
9473
9474 return 0;
9475}
9476
9477
Chris Lattner8b0ea312006-01-13 20:11:04 +00009478/// visitCallInst - CallInst simplification. This mostly only handles folding
9479/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9480/// the heavy lifting.
9481///
Chris Lattner9fe38862003-06-19 17:00:31 +00009482Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009483 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9484 if (!II) return visitCallSite(&CI);
9485
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009486 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9487 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009488 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009489 bool Changed = false;
9490
9491 // memmove/cpy/set of zero bytes is a noop.
9492 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9493 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9494
Chris Lattner35b9e482004-10-12 04:52:52 +00009495 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009496 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009497 // Replace the instruction with just byte operations. We would
9498 // transform other cases to loads/stores, but we don't know if
9499 // alignment is sufficient.
9500 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009501 }
9502
Chris Lattner35b9e482004-10-12 04:52:52 +00009503 // If we have a memmove and the source operation is a constant global,
9504 // then the source and dest pointers can't alias, so we can change this
9505 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009506 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009507 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9508 if (GVSrc->isConstant()) {
9509 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009510 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9511 const Type *Tys[1];
9512 Tys[0] = CI.getOperand(3)->getType();
9513 CI.setOperand(0,
9514 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009515 Changed = true;
9516 }
Chris Lattnera935db82008-05-28 05:30:41 +00009517
9518 // memmove(x,x,size) -> noop.
9519 if (MMI->getSource() == MMI->getDest())
9520 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009521 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009522
Chris Lattner95a959d2006-03-06 20:18:44 +00009523 // If we can determine a pointer alignment that is bigger than currently
9524 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009525 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009526 if (Instruction *I = SimplifyMemTransfer(MI))
9527 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009528 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9529 if (Instruction *I = SimplifyMemSet(MSI))
9530 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009531 }
9532
Chris Lattner8b0ea312006-01-13 20:11:04 +00009533 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009534 }
9535
9536 switch (II->getIntrinsicID()) {
9537 default: break;
9538 case Intrinsic::bswap:
9539 // bswap(bswap(x)) -> x
9540 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9541 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9542 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9543 break;
9544 case Intrinsic::ppc_altivec_lvx:
9545 case Intrinsic::ppc_altivec_lvxl:
9546 case Intrinsic::x86_sse_loadu_ps:
9547 case Intrinsic::x86_sse2_loadu_pd:
9548 case Intrinsic::x86_sse2_loadu_dq:
9549 // Turn PPC lvx -> load if the pointer is known aligned.
9550 // Turn X86 loadups -> load if the pointer is known aligned.
9551 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9552 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9553 PointerType::getUnqual(II->getType()),
9554 CI);
9555 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009556 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009557 break;
9558 case Intrinsic::ppc_altivec_stvx:
9559 case Intrinsic::ppc_altivec_stvxl:
9560 // Turn stvx -> store if the pointer is known aligned.
9561 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9562 const Type *OpPtrTy =
9563 PointerType::getUnqual(II->getOperand(1)->getType());
9564 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9565 return new StoreInst(II->getOperand(1), Ptr);
9566 }
9567 break;
9568 case Intrinsic::x86_sse_storeu_ps:
9569 case Intrinsic::x86_sse2_storeu_pd:
9570 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009571 // Turn X86 storeu -> store if the pointer is known aligned.
9572 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9573 const Type *OpPtrTy =
9574 PointerType::getUnqual(II->getOperand(2)->getType());
9575 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9576 return new StoreInst(II->getOperand(2), Ptr);
9577 }
9578 break;
9579
9580 case Intrinsic::x86_sse_cvttss2si: {
9581 // These intrinsics only demands the 0th element of its input vector. If
9582 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009583 unsigned VWidth =
9584 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9585 APInt DemandedElts(VWidth, 1);
9586 APInt UndefElts(VWidth, 0);
9587 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009588 UndefElts)) {
9589 II->setOperand(1, V);
9590 return II;
9591 }
9592 break;
9593 }
9594
9595 case Intrinsic::ppc_altivec_vperm:
9596 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9597 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9598 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009599
Chris Lattner0521e3c2008-06-18 04:33:20 +00009600 // Check that all of the elements are integer constants or undefs.
9601 bool AllEltsOk = true;
9602 for (unsigned i = 0; i != 16; ++i) {
9603 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9604 !isa<UndefValue>(Mask->getOperand(i))) {
9605 AllEltsOk = false;
9606 break;
9607 }
9608 }
9609
9610 if (AllEltsOk) {
9611 // Cast the input vectors to byte vectors.
9612 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9613 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9614 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009615
Chris Lattner0521e3c2008-06-18 04:33:20 +00009616 // Only extract each element once.
9617 Value *ExtractedElts[32];
9618 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9619
Chris Lattnere2ed0572006-04-06 19:19:17 +00009620 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009621 if (isa<UndefValue>(Mask->getOperand(i)))
9622 continue;
9623 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9624 Idx &= 31; // Match the hardware behavior.
9625
9626 if (ExtractedElts[Idx] == 0) {
9627 Instruction *Elt =
9628 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9629 InsertNewInstBefore(Elt, CI);
9630 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009631 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009632
Chris Lattner0521e3c2008-06-18 04:33:20 +00009633 // Insert this value into the result vector.
9634 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9635 i, "tmp");
9636 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009637 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009638 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009639 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009640 }
9641 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009642
Chris Lattner0521e3c2008-06-18 04:33:20 +00009643 case Intrinsic::stackrestore: {
9644 // If the save is right next to the restore, remove the restore. This can
9645 // happen when variable allocas are DCE'd.
9646 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9647 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9648 BasicBlock::iterator BI = SS;
9649 if (&*++BI == II)
9650 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009651 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009652 }
9653
9654 // Scan down this block to see if there is another stack restore in the
9655 // same block without an intervening call/alloca.
9656 BasicBlock::iterator BI = II;
9657 TerminatorInst *TI = II->getParent()->getTerminator();
9658 bool CannotRemove = false;
9659 for (++BI; &*BI != TI; ++BI) {
9660 if (isa<AllocaInst>(BI)) {
9661 CannotRemove = true;
9662 break;
9663 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009664 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9665 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9666 // If there is a stackrestore below this one, remove this one.
9667 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9668 return EraseInstFromFunction(CI);
9669 // Otherwise, ignore the intrinsic.
9670 } else {
9671 // If we found a non-intrinsic call, we can't remove the stack
9672 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009673 CannotRemove = true;
9674 break;
9675 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009676 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009677 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009678
9679 // If the stack restore is in a return/unwind block and if there are no
9680 // allocas or calls between the restore and the return, nuke the restore.
9681 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9682 return EraseInstFromFunction(CI);
9683 break;
9684 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009685 }
9686
Chris Lattner8b0ea312006-01-13 20:11:04 +00009687 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009688}
9689
9690// InvokeInst simplification
9691//
9692Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009693 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009694}
9695
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009696/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9697/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009698static bool isSafeToEliminateVarargsCast(const CallSite CS,
9699 const CastInst * const CI,
9700 const TargetData * const TD,
9701 const int ix) {
9702 if (!CI->isLosslessCast())
9703 return false;
9704
9705 // The size of ByVal arguments is derived from the type, so we
9706 // can't change to a type with a different size. If the size were
9707 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009708 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009709 return true;
9710
9711 const Type* SrcTy =
9712 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9713 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9714 if (!SrcTy->isSized() || !DstTy->isSized())
9715 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009716 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009717 return false;
9718 return true;
9719}
9720
Chris Lattnera44d8a22003-10-07 22:32:43 +00009721// visitCallSite - Improvements for call and invoke instructions.
9722//
9723Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009724 bool Changed = false;
9725
9726 // If the callee is a constexpr cast of a function, attempt to move the cast
9727 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009728 if (transformConstExprCastCall(CS)) return 0;
9729
Chris Lattner6c266db2003-10-07 22:54:13 +00009730 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009731
Chris Lattner08b22ec2005-05-13 07:09:09 +00009732 if (Function *CalleeF = dyn_cast<Function>(Callee))
9733 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9734 Instruction *OldCall = CS.getInstruction();
9735 // If the call and callee calling conventions don't match, this call must
9736 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009737 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009738 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9739 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009740 if (!OldCall->use_empty())
9741 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9742 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9743 return EraseInstFromFunction(*OldCall);
9744 return 0;
9745 }
9746
Chris Lattner17be6352004-10-18 02:59:09 +00009747 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9748 // This instruction is not reachable, just remove it. We insert a store to
9749 // undef so that we know that this code is not reachable, despite the fact
9750 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009751 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009752 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009753 CS.getInstruction());
9754
9755 if (!CS.getInstruction()->use_empty())
9756 CS.getInstruction()->
9757 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9758
9759 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9760 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009761 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9762 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009763 }
Chris Lattner17be6352004-10-18 02:59:09 +00009764 return EraseInstFromFunction(*CS.getInstruction());
9765 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009766
Duncan Sandscdb6d922007-09-17 10:26:40 +00009767 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9768 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9769 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9770 return transformCallThroughTrampoline(CS);
9771
Chris Lattner6c266db2003-10-07 22:54:13 +00009772 const PointerType *PTy = cast<PointerType>(Callee->getType());
9773 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9774 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009775 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009776 // See if we can optimize any arguments passed through the varargs area of
9777 // the call.
9778 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009779 E = CS.arg_end(); I != E; ++I, ++ix) {
9780 CastInst *CI = dyn_cast<CastInst>(*I);
9781 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9782 *I = CI->getOperand(0);
9783 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009784 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009785 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009786 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009787
Duncan Sandsf0c33542007-12-19 21:13:37 +00009788 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009789 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009790 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009791 Changed = true;
9792 }
9793
Chris Lattner6c266db2003-10-07 22:54:13 +00009794 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009795}
9796
Chris Lattner9fe38862003-06-19 17:00:31 +00009797// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9798// attempt to move the cast to the arguments of the call/invoke.
9799//
9800bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9801 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9802 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009803 if (CE->getOpcode() != Instruction::BitCast ||
9804 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009805 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009806 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009807 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009808 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009809
9810 // Okay, this is a cast from a function to a different type. Unless doing so
9811 // would cause a type conversion of one of our arguments, change this call to
9812 // be a direct call with arguments casted to the appropriate types.
9813 //
9814 const FunctionType *FT = Callee->getFunctionType();
9815 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009816 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009817
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009818 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009819 return false; // TODO: Handle multiple return values.
9820
Chris Lattnerf78616b2004-01-14 06:06:08 +00009821 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009822 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009823 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009824 // Conversion is ok if changing from one pointer type to another or from
9825 // a pointer to an integer of the same size.
9826 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009827 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009828 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009829
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009830 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009831 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009832 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009833 return false; // Cannot transform this return value.
9834
Chris Lattner58d74912008-03-12 17:45:29 +00009835 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009836 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009837 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009838 return false; // Attribute not compatible with transformed value.
9839 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009840
Chris Lattnerf78616b2004-01-14 06:06:08 +00009841 // If the callsite is an invoke instruction, and the return value is used by
9842 // a PHI node in a successor, we cannot change the return type of the call
9843 // because there is no place to put the cast instruction (without breaking
9844 // the critical edge). Bail out in this case.
9845 if (!Caller->use_empty())
9846 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9847 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9848 UI != E; ++UI)
9849 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9850 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009851 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009852 return false;
9853 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009854
9855 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9856 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009857
Chris Lattner9fe38862003-06-19 17:00:31 +00009858 CallSite::arg_iterator AI = CS.arg_begin();
9859 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9860 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009861 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009862
9863 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009864 return false; // Cannot transform this parameter value.
9865
Devang Patel19c87462008-09-26 22:53:05 +00009866 if (CallerPAL.getParamAttributes(i + 1)
9867 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009868 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009869
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009870 // Converting from one pointer type to another or between a pointer and an
9871 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009872 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009873 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9874 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009875 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009876 }
9877
9878 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009879 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009880 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009881
Chris Lattner58d74912008-03-12 17:45:29 +00009882 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9883 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009884 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009885 // won't be dropping them. Check that these extra arguments have attributes
9886 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009887 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9888 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009889 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009890 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009891 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009892 return false;
9893 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009894
Chris Lattner9fe38862003-06-19 17:00:31 +00009895 // Okay, we decided that this is a safe thing to do: go ahead and start
9896 // inserting cast instructions as necessary...
9897 std::vector<Value*> Args;
9898 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009899 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009900 attrVec.reserve(NumCommonArgs);
9901
9902 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009903 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009904
9905 // If the return value is not being used, the type may not be compatible
9906 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009907 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009908
9909 // Add the new return attributes.
9910 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009911 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009912
9913 AI = CS.arg_begin();
9914 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9915 const Type *ParamTy = FT->getParamType(i);
9916 if ((*AI)->getType() == ParamTy) {
9917 Args.push_back(*AI);
9918 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009919 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009920 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009921 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009922 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009923 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009924
9925 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009926 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009927 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009928 }
9929
9930 // If the function takes more arguments than the call was taking, add them
9931 // now...
9932 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9933 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9934
9935 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009936 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009937 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009938 cerr << "WARNING: While resolving call to function '"
9939 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009940 } else {
9941 // Add all of the arguments in their promoted form to the arg list...
9942 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9943 const Type *PTy = getPromotedType((*AI)->getType());
9944 if (PTy != (*AI)->getType()) {
9945 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009946 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9947 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009948 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009949 InsertNewInstBefore(Cast, *Caller);
9950 Args.push_back(Cast);
9951 } else {
9952 Args.push_back(*AI);
9953 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009954
Duncan Sandse1e520f2008-01-13 08:02:44 +00009955 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009956 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009957 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009958 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009959 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009960 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009961
Devang Patel19c87462008-09-26 22:53:05 +00009962 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9963 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9964
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009965 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009966 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009967
Devang Patel05988662008-09-25 21:00:45 +00009968 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009969
Chris Lattner9fe38862003-06-19 17:00:31 +00009970 Instruction *NC;
9971 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009972 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009973 Args.begin(), Args.end(),
9974 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009975 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009976 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009977 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009978 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9979 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009980 CallInst *CI = cast<CallInst>(Caller);
9981 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009982 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009983 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009984 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009985 }
9986
Chris Lattner6934a042007-02-11 01:23:03 +00009987 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009988 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009989 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009990 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009991 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009992 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009993 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009994
9995 // If this is an invoke instruction, we should insert it after the first
9996 // non-phi, instruction in the normal successor block.
9997 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009998 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009999 InsertNewInstBefore(NC, *I);
10000 } else {
10001 // Otherwise, it's a call, just insert cast right after the call instr
10002 InsertNewInstBefore(NC, *Caller);
10003 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010004 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010005 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +000010006 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010007 }
10008 }
10009
10010 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10011 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010012 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010013 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010014 return true;
10015}
10016
Duncan Sandscdb6d922007-09-17 10:26:40 +000010017// transformCallThroughTrampoline - Turn a call to a function created by the
10018// init_trampoline intrinsic into a direct call to the underlying function.
10019//
10020Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10021 Value *Callee = CS.getCalledValue();
10022 const PointerType *PTy = cast<PointerType>(Callee->getType());
10023 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010024 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010025
10026 // If the call already has the 'nest' attribute somewhere then give up -
10027 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010028 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010029 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010030
10031 IntrinsicInst *Tramp =
10032 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10033
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010034 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010035 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10036 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10037
Devang Patel05988662008-09-25 21:00:45 +000010038 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010039 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010040 unsigned NestIdx = 1;
10041 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010042 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010043
10044 // Look for a parameter marked with the 'nest' attribute.
10045 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10046 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010047 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010048 // Record the parameter type and any other attributes.
10049 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010050 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010051 break;
10052 }
10053
10054 if (NestTy) {
10055 Instruction *Caller = CS.getInstruction();
10056 std::vector<Value*> NewArgs;
10057 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10058
Devang Patel05988662008-09-25 21:00:45 +000010059 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010060 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010061
Duncan Sandscdb6d922007-09-17 10:26:40 +000010062 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010063 // mean appending it. Likewise for attributes.
10064
Devang Patel19c87462008-09-26 22:53:05 +000010065 // Add any result attributes.
10066 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010067 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010068
Duncan Sandscdb6d922007-09-17 10:26:40 +000010069 {
10070 unsigned Idx = 1;
10071 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10072 do {
10073 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010074 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010075 Value *NestVal = Tramp->getOperand(3);
10076 if (NestVal->getType() != NestTy)
10077 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10078 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010079 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010080 }
10081
10082 if (I == E)
10083 break;
10084
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010085 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010086 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010087 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010088 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010089 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010090
10091 ++Idx, ++I;
10092 } while (1);
10093 }
10094
Devang Patel19c87462008-09-26 22:53:05 +000010095 // Add any function attributes.
10096 if (Attributes Attr = Attrs.getFnAttributes())
10097 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10098
Duncan Sandscdb6d922007-09-17 10:26:40 +000010099 // The trampoline may have been bitcast to a bogus type (FTy).
10100 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010101 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010102
Duncan Sandscdb6d922007-09-17 10:26:40 +000010103 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010104 NewTypes.reserve(FTy->getNumParams()+1);
10105
Duncan Sandscdb6d922007-09-17 10:26:40 +000010106 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010107 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010108 {
10109 unsigned Idx = 1;
10110 FunctionType::param_iterator I = FTy->param_begin(),
10111 E = FTy->param_end();
10112
10113 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010114 if (Idx == NestIdx)
10115 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010116 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010117
10118 if (I == E)
10119 break;
10120
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010121 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010122 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010123
10124 ++Idx, ++I;
10125 } while (1);
10126 }
10127
10128 // Replace the trampoline call with a direct call. Let the generic
10129 // code sort out any function type mismatches.
10130 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010131 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010132 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10133 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010134 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010135
10136 Instruction *NewCaller;
10137 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010138 NewCaller = InvokeInst::Create(NewCallee,
10139 II->getNormalDest(), II->getUnwindDest(),
10140 NewArgs.begin(), NewArgs.end(),
10141 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010142 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010143 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010144 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010145 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10146 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010147 if (cast<CallInst>(Caller)->isTailCall())
10148 cast<CallInst>(NewCaller)->setTailCall();
10149 cast<CallInst>(NewCaller)->
10150 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010151 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010152 }
10153 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10154 Caller->replaceAllUsesWith(NewCaller);
10155 Caller->eraseFromParent();
10156 RemoveFromWorkList(Caller);
10157 return 0;
10158 }
10159 }
10160
10161 // Replace the trampoline call with a direct call. Since there is no 'nest'
10162 // parameter, there is no need to adjust the argument list. Let the generic
10163 // code sort out any function type mismatches.
10164 Constant *NewCallee =
10165 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10166 CS.setCalledFunction(NewCallee);
10167 return CS.getInstruction();
10168}
10169
Chris Lattner7da52b22006-11-01 04:51:18 +000010170/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10171/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10172/// and a single binop.
10173Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10174 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010175 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010176 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010177 Value *LHSVal = FirstInst->getOperand(0);
10178 Value *RHSVal = FirstInst->getOperand(1);
10179
10180 const Type *LHSType = LHSVal->getType();
10181 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010182
10183 // Scan to see if all operands are the same opcode, all have one use, and all
10184 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010185 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010186 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010187 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010188 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010189 // types or GEP's with different index types.
10190 I->getOperand(0)->getType() != LHSType ||
10191 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010192 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010193
10194 // If they are CmpInst instructions, check their predicates
10195 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10196 if (cast<CmpInst>(I)->getPredicate() !=
10197 cast<CmpInst>(FirstInst)->getPredicate())
10198 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010199
10200 // Keep track of which operand needs a phi node.
10201 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10202 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010203 }
10204
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010205 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010206
Chris Lattner7da52b22006-11-01 04:51:18 +000010207 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010208 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010209 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010210 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010211 NewLHS = PHINode::Create(LHSType,
10212 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010213 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10214 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010215 InsertNewInstBefore(NewLHS, PN);
10216 LHSVal = NewLHS;
10217 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010218
10219 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010220 NewRHS = PHINode::Create(RHSType,
10221 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010222 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10223 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010224 InsertNewInstBefore(NewRHS, PN);
10225 RHSVal = NewRHS;
10226 }
10227
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010228 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010229 if (NewLHS || NewRHS) {
10230 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10231 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10232 if (NewLHS) {
10233 Value *NewInLHS = InInst->getOperand(0);
10234 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10235 }
10236 if (NewRHS) {
10237 Value *NewInRHS = InInst->getOperand(1);
10238 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10239 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010240 }
10241 }
10242
Chris Lattner7da52b22006-11-01 04:51:18 +000010243 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010244 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010245 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10246 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10247 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010248}
10249
Chris Lattner05f18922008-12-01 02:34:36 +000010250Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10251 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10252
10253 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10254 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010255 // This is true if all GEP bases are allocas and if all indices into them are
10256 // constants.
10257 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010258
10259 // Scan to see if all operands are the same opcode, all have one use, and all
10260 // kill their operands (i.e. the operands have one use).
10261 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10262 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10263 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10264 GEP->getNumOperands() != FirstInst->getNumOperands())
10265 return 0;
10266
Chris Lattner36d3e322009-02-21 00:46:50 +000010267 // Keep track of whether or not all GEPs are of alloca pointers.
10268 if (AllBasePointersAreAllocas &&
10269 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10270 !GEP->hasAllConstantIndices()))
10271 AllBasePointersAreAllocas = false;
10272
Chris Lattner05f18922008-12-01 02:34:36 +000010273 // Compare the operand lists.
10274 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10275 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10276 continue;
10277
10278 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10279 // if one of the PHIs has a constant for the index. The index may be
10280 // substantially cheaper to compute for the constants, so making it a
10281 // variable index could pessimize the path. This also handles the case
10282 // for struct indices, which must always be constant.
10283 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10284 isa<ConstantInt>(GEP->getOperand(op)))
10285 return 0;
10286
10287 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10288 return 0;
10289 FixedOperands[op] = 0; // Needs a PHI.
10290 }
10291 }
10292
Chris Lattner36d3e322009-02-21 00:46:50 +000010293 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010294 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010295 // offset calculation, but all the predecessors will have to materialize the
10296 // stack address into a register anyway. We'd actually rather *clone* the
10297 // load up into the predecessors so that we have a load of a gep of an alloca,
10298 // which can usually all be folded into the load.
10299 if (AllBasePointersAreAllocas)
10300 return 0;
10301
Chris Lattner05f18922008-12-01 02:34:36 +000010302 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10303 // that is variable.
10304 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10305
10306 bool HasAnyPHIs = false;
10307 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10308 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10309 Value *FirstOp = FirstInst->getOperand(i);
10310 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10311 FirstOp->getName()+".pn");
10312 InsertNewInstBefore(NewPN, PN);
10313
10314 NewPN->reserveOperandSpace(e);
10315 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10316 OperandPhis[i] = NewPN;
10317 FixedOperands[i] = NewPN;
10318 HasAnyPHIs = true;
10319 }
10320
10321
10322 // Add all operands to the new PHIs.
10323 if (HasAnyPHIs) {
10324 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10325 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10326 BasicBlock *InBB = PN.getIncomingBlock(i);
10327
10328 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10329 if (PHINode *OpPhi = OperandPhis[op])
10330 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10331 }
10332 }
10333
10334 Value *Base = FixedOperands[0];
10335 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10336 FixedOperands.end());
10337}
10338
10339
Chris Lattner21550882009-02-23 05:56:17 +000010340/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10341/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010342/// obvious the value of the load is not changed from the point of the load to
10343/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010344///
10345/// Finally, it is safe, but not profitable, to sink a load targetting a
10346/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10347/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010348static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010349 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10350
10351 for (++BBI; BBI != E; ++BBI)
10352 if (BBI->mayWriteToMemory())
10353 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010354
10355 // Check for non-address taken alloca. If not address-taken already, it isn't
10356 // profitable to do this xform.
10357 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10358 bool isAddressTaken = false;
10359 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10360 UI != E; ++UI) {
10361 if (isa<LoadInst>(UI)) continue;
10362 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10363 // If storing TO the alloca, then the address isn't taken.
10364 if (SI->getOperand(1) == AI) continue;
10365 }
10366 isAddressTaken = true;
10367 break;
10368 }
10369
Chris Lattner36d3e322009-02-21 00:46:50 +000010370 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010371 return false;
10372 }
10373
Chris Lattner36d3e322009-02-21 00:46:50 +000010374 // If this load is a load from a GEP with a constant offset from an alloca,
10375 // then we don't want to sink it. In its present form, it will be
10376 // load [constant stack offset]. Sinking it will cause us to have to
10377 // materialize the stack addresses in each predecessor in a register only to
10378 // do a shared load from register in the successor.
10379 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10380 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10381 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10382 return false;
10383
Chris Lattner76c73142006-11-01 07:13:54 +000010384 return true;
10385}
10386
Chris Lattner9fe38862003-06-19 17:00:31 +000010387
Chris Lattnerbac32862004-11-14 19:13:23 +000010388// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10389// operator and they all are only used by the PHI, PHI together their
10390// inputs, and do the operation once, to the result of the PHI.
10391Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10392 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10393
10394 // Scan the instruction, looking for input operations that can be folded away.
10395 // If all input operands to the phi are the same instruction (e.g. a cast from
10396 // the same type or "+42") we can pull the operation through the PHI, reducing
10397 // code size and simplifying code.
10398 Constant *ConstantOp = 0;
10399 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010400 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010401 if (isa<CastInst>(FirstInst)) {
10402 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010403 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010404 // Can fold binop, compare or shift here if the RHS is a constant,
10405 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010406 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010407 if (ConstantOp == 0)
10408 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010409 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10410 isVolatile = LI->isVolatile();
10411 // We can't sink the load if the loaded value could be modified between the
10412 // load and the PHI.
10413 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010414 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010415 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010416
10417 // If the PHI is of volatile loads and the load block has multiple
10418 // successors, sinking it would remove a load of the volatile value from
10419 // the path through the other successor.
10420 if (isVolatile &&
10421 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10422 return 0;
10423
Chris Lattner9c080502006-11-01 07:43:41 +000010424 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010425 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010426 } else {
10427 return 0; // Cannot fold this operation.
10428 }
10429
10430 // Check to see if all arguments are the same operation.
10431 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10432 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10433 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010434 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010435 return 0;
10436 if (CastSrcTy) {
10437 if (I->getOperand(0)->getType() != CastSrcTy)
10438 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010439 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010440 // We can't sink the load if the loaded value could be modified between
10441 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010442 if (LI->isVolatile() != isVolatile ||
10443 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010444 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010445 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010446
Chris Lattner71042962008-07-08 17:18:32 +000010447 // If the PHI is of volatile loads and the load block has multiple
10448 // successors, sinking it would remove a load of the volatile value from
10449 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010450 if (isVolatile &&
10451 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10452 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010453
Chris Lattnerbac32862004-11-14 19:13:23 +000010454 } else if (I->getOperand(1) != ConstantOp) {
10455 return 0;
10456 }
10457 }
10458
10459 // Okay, they are all the same operation. Create a new PHI node of the
10460 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010461 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10462 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010463 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010464
10465 Value *InVal = FirstInst->getOperand(0);
10466 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010467
10468 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010469 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10470 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10471 if (NewInVal != InVal)
10472 InVal = 0;
10473 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10474 }
10475
10476 Value *PhiVal;
10477 if (InVal) {
10478 // The new PHI unions all of the same values together. This is really
10479 // common, so we handle it intelligently here for compile-time speed.
10480 PhiVal = InVal;
10481 delete NewPN;
10482 } else {
10483 InsertNewInstBefore(NewPN, PN);
10484 PhiVal = NewPN;
10485 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010486
Chris Lattnerbac32862004-11-14 19:13:23 +000010487 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010488 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010489 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010490 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010491 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010492 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010493 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010494 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010495 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10496
10497 // If this was a volatile load that we are merging, make sure to loop through
10498 // and mark all the input loads as non-volatile. If we don't do this, we will
10499 // insert a new volatile load and the old ones will not be deletable.
10500 if (isVolatile)
10501 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10502 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10503
10504 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010505}
Chris Lattnera1be5662002-05-02 17:06:02 +000010506
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010507/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10508/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010509static bool DeadPHICycle(PHINode *PN,
10510 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010511 if (PN->use_empty()) return true;
10512 if (!PN->hasOneUse()) return false;
10513
10514 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010515 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010516 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010517
10518 // Don't scan crazily complex things.
10519 if (PotentiallyDeadPHIs.size() == 16)
10520 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010521
10522 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10523 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010524
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010525 return false;
10526}
10527
Chris Lattnercf5008a2007-11-06 21:52:06 +000010528/// PHIsEqualValue - Return true if this phi node is always equal to
10529/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10530/// z = some value; x = phi (y, z); y = phi (x, z)
10531static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10532 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10533 // See if we already saw this PHI node.
10534 if (!ValueEqualPHIs.insert(PN))
10535 return true;
10536
10537 // Don't scan crazily complex things.
10538 if (ValueEqualPHIs.size() == 16)
10539 return false;
10540
10541 // Scan the operands to see if they are either phi nodes or are equal to
10542 // the value.
10543 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10544 Value *Op = PN->getIncomingValue(i);
10545 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10546 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10547 return false;
10548 } else if (Op != NonPhiInVal)
10549 return false;
10550 }
10551
10552 return true;
10553}
10554
10555
Chris Lattner473945d2002-05-06 18:06:38 +000010556// PHINode simplification
10557//
Chris Lattner7e708292002-06-25 16:13:24 +000010558Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010559 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010560 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010561
Owen Anderson7e057142006-07-10 22:03:18 +000010562 if (Value *V = PN.hasConstantValue())
10563 return ReplaceInstUsesWith(PN, V);
10564
Owen Anderson7e057142006-07-10 22:03:18 +000010565 // If all PHI operands are the same operation, pull them through the PHI,
10566 // reducing code size.
10567 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010568 isa<Instruction>(PN.getIncomingValue(1)) &&
10569 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10570 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10571 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10572 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010573 PN.getIncomingValue(0)->hasOneUse())
10574 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10575 return Result;
10576
10577 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10578 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10579 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010580 if (PN.hasOneUse()) {
10581 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10582 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010583 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010584 PotentiallyDeadPHIs.insert(&PN);
10585 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10586 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10587 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010588
10589 // If this phi has a single use, and if that use just computes a value for
10590 // the next iteration of a loop, delete the phi. This occurs with unused
10591 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10592 // common case here is good because the only other things that catch this
10593 // are induction variable analysis (sometimes) and ADCE, which is only run
10594 // late.
10595 if (PHIUser->hasOneUse() &&
10596 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10597 PHIUser->use_back() == &PN) {
10598 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10599 }
10600 }
Owen Anderson7e057142006-07-10 22:03:18 +000010601
Chris Lattnercf5008a2007-11-06 21:52:06 +000010602 // We sometimes end up with phi cycles that non-obviously end up being the
10603 // same value, for example:
10604 // z = some value; x = phi (y, z); y = phi (x, z)
10605 // where the phi nodes don't necessarily need to be in the same block. Do a
10606 // quick check to see if the PHI node only contains a single non-phi value, if
10607 // so, scan to see if the phi cycle is actually equal to that value.
10608 {
10609 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10610 // Scan for the first non-phi operand.
10611 while (InValNo != NumOperandVals &&
10612 isa<PHINode>(PN.getIncomingValue(InValNo)))
10613 ++InValNo;
10614
10615 if (InValNo != NumOperandVals) {
10616 Value *NonPhiInVal = PN.getOperand(InValNo);
10617
10618 // Scan the rest of the operands to see if there are any conflicts, if so
10619 // there is no need to recursively scan other phis.
10620 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10621 Value *OpVal = PN.getIncomingValue(InValNo);
10622 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10623 break;
10624 }
10625
10626 // If we scanned over all operands, then we have one unique value plus
10627 // phi values. Scan PHI nodes to see if they all merge in each other or
10628 // the value.
10629 if (InValNo == NumOperandVals) {
10630 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10631 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10632 return ReplaceInstUsesWith(PN, NonPhiInVal);
10633 }
10634 }
10635 }
Chris Lattner60921c92003-12-19 05:58:40 +000010636 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010637}
10638
Reid Spencer17212df2006-12-12 09:18:51 +000010639static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10640 Instruction *InsertPoint,
10641 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010642 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10643 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010644 // We must cast correctly to the pointer type. Ensure that we
10645 // sign extend the integer value if it is smaller as this is
10646 // used for address computation.
10647 Instruction::CastOps opcode =
10648 (VTySize < PtrSize ? Instruction::SExt :
10649 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10650 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010651}
10652
Chris Lattnera1be5662002-05-02 17:06:02 +000010653
Chris Lattner7e708292002-06-25 16:13:24 +000010654Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010655 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010656 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010657 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010658 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010659 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010660
Chris Lattnere87597f2004-10-16 18:11:37 +000010661 if (isa<UndefValue>(GEP.getOperand(0)))
10662 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10663
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010664 bool HasZeroPointerIndex = false;
10665 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10666 HasZeroPointerIndex = C->isNullValue();
10667
10668 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010669 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010670
Chris Lattner28977af2004-04-05 01:30:19 +000010671 // Eliminate unneeded casts for indices.
10672 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010673
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010674 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010675 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10676 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010677 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010678 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010679 if (CI->getOpcode() == Instruction::ZExt ||
10680 CI->getOpcode() == Instruction::SExt) {
10681 const Type *SrcTy = CI->getOperand(0)->getType();
10682 // We can eliminate a cast from i32 to i64 iff the target
10683 // is a 32-bit pointer target.
10684 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10685 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010686 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010687 }
10688 }
10689 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010690 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010691 // to what we need. If narrower, sign-extend it to what we need.
10692 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010693 // insert it. This explicit cast can make subsequent optimizations more
10694 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010695 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010696 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010697 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010698 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010699 MadeChange = true;
10700 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010701 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10702 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010703 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010704 MadeChange = true;
10705 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010706 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10707 if (Constant *C = dyn_cast<Constant>(Op)) {
10708 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10709 MadeChange = true;
10710 } else {
10711 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10712 GEP);
10713 *i = Op;
10714 MadeChange = true;
10715 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010716 }
Chris Lattner28977af2004-04-05 01:30:19 +000010717 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010718 }
Chris Lattner28977af2004-04-05 01:30:19 +000010719 if (MadeChange) return &GEP;
10720
Chris Lattner90ac28c2002-08-02 19:29:35 +000010721 // Combine Indices - If the source pointer to this getelementptr instruction
10722 // is a getelementptr instruction, combine the indices of the two
10723 // getelementptr instructions into a single instruction.
10724 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010725 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010726 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010727 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010728
10729 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010730 // Note that if our source is a gep chain itself that we wait for that
10731 // chain to be resolved before we perform this transformation. This
10732 // avoids us creating a TON of code in some cases.
10733 //
10734 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10735 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10736 return 0; // Wait until our source is folded to completion.
10737
Chris Lattner72588fc2007-02-15 22:48:32 +000010738 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010739
10740 // Find out whether the last index in the source GEP is a sequential idx.
10741 bool EndsWithSequential = false;
10742 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10743 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010744 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010745
Chris Lattner90ac28c2002-08-02 19:29:35 +000010746 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010747 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010748 // Replace: gep (gep %P, long B), long A, ...
10749 // With: T = long A+B; gep %P, T, ...
10750 //
Chris Lattner620ce142004-05-07 22:09:22 +000010751 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010752 if (SO1 == Constant::getNullValue(SO1->getType())) {
10753 Sum = GO1;
10754 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10755 Sum = SO1;
10756 } else {
10757 // If they aren't the same type, convert both to an integer of the
10758 // target's pointer size.
10759 if (SO1->getType() != GO1->getType()) {
10760 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010761 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010762 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010763 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010764 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010765 unsigned PS = TD->getPointerSizeInBits();
10766 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010767 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010768 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010769
Duncan Sands514ab342007-11-01 20:53:16 +000010770 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010771 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010772 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010773 } else {
10774 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010775 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10776 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010777 }
10778 }
10779 }
Chris Lattner620ce142004-05-07 22:09:22 +000010780 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10781 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10782 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010783 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010784 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010785 }
Chris Lattner28977af2004-04-05 01:30:19 +000010786 }
Chris Lattner620ce142004-05-07 22:09:22 +000010787
10788 // Recycle the GEP we already have if possible.
10789 if (SrcGEPOperands.size() == 2) {
10790 GEP.setOperand(0, SrcGEPOperands[0]);
10791 GEP.setOperand(1, Sum);
10792 return &GEP;
10793 } else {
10794 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10795 SrcGEPOperands.end()-1);
10796 Indices.push_back(Sum);
10797 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10798 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010799 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010800 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010801 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010802 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010803 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10804 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010805 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10806 }
10807
10808 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010809 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10810 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010811
Chris Lattner620ce142004-05-07 22:09:22 +000010812 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010813 // GEP of global variable. If all of the indices for this GEP are
10814 // constants, we can promote this to a constexpr instead of an instruction.
10815
10816 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010817 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010818 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10819 for (; I != E && isa<Constant>(*I); ++I)
10820 Indices.push_back(cast<Constant>(*I));
10821
10822 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010823 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10824 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010825
10826 // Replace all uses of the GEP with the new constexpr...
10827 return ReplaceInstUsesWith(GEP, CE);
10828 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010829 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010830 if (!isa<PointerType>(X->getType())) {
10831 // Not interesting. Source pointer must be a cast from pointer.
10832 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010833 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10834 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010835 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010836 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10837 // into : GEP i8* X, ...
10838 //
Chris Lattnereed48272005-09-13 00:40:14 +000010839 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010840 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10841 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010842 if (const ArrayType *CATy =
10843 dyn_cast<ArrayType>(CPTy->getElementType())) {
10844 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10845 if (CATy->getElementType() == XTy->getElementType()) {
10846 // -> GEP i8* X, ...
10847 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10848 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10849 GEP.getName());
10850 } else if (const ArrayType *XATy =
10851 dyn_cast<ArrayType>(XTy->getElementType())) {
10852 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010853 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010854 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010855 // At this point, we know that the cast source type is a pointer
10856 // to an array of the same type as the destination pointer
10857 // array. Because the array type is never stepped over (there
10858 // is a leading zero) we can fold the cast into this GEP.
10859 GEP.setOperand(0, X);
10860 return &GEP;
10861 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010862 }
10863 }
Chris Lattnereed48272005-09-13 00:40:14 +000010864 } else if (GEP.getNumOperands() == 2) {
10865 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010866 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10867 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010868 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10869 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10870 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010871 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10872 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010873 Value *Idx[2];
10874 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10875 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010876 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010877 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010878 // V and GEP are both pointer types --> BitCast
10879 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010880 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010881
10882 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010883 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010884 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010885 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010886
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010887 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010888 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010889 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010890
10891 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10892 // allow either a mul, shift, or constant here.
10893 Value *NewIdx = 0;
10894 ConstantInt *Scale = 0;
10895 if (ArrayEltSize == 1) {
10896 NewIdx = GEP.getOperand(1);
10897 Scale = ConstantInt::get(NewIdx->getType(), 1);
10898 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010899 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010900 Scale = CI;
10901 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10902 if (Inst->getOpcode() == Instruction::Shl &&
10903 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010904 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10905 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10906 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010907 NewIdx = Inst->getOperand(0);
10908 } else if (Inst->getOpcode() == Instruction::Mul &&
10909 isa<ConstantInt>(Inst->getOperand(1))) {
10910 Scale = cast<ConstantInt>(Inst->getOperand(1));
10911 NewIdx = Inst->getOperand(0);
10912 }
10913 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010914
Chris Lattner7835cdd2005-09-13 18:36:04 +000010915 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010916 // out, perform the transformation. Note, we don't know whether Scale is
10917 // signed or not. We'll use unsigned version of division/modulo
10918 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000010919 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010920 Scale->getZExtValue() % ArrayEltSize == 0) {
10921 Scale = ConstantInt::get(Scale->getType(),
10922 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010923 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010924 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010925 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010926 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010927 NewIdx = InsertNewInstBefore(Sc, GEP);
10928 }
10929
10930 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010931 Value *Idx[2];
10932 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10933 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010934 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010935 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010936 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10937 // The NewGEP must be pointer typed, so must the old one -> BitCast
10938 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010939 }
10940 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010941 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010942 }
Chris Lattner58407792009-01-09 04:53:57 +000010943
Chris Lattner46cd5a12009-01-09 05:44:56 +000010944 /// See if we can simplify:
10945 /// X = bitcast A to B*
10946 /// Y = gep X, <...constant indices...>
10947 /// into a gep of the original struct. This is important for SROA and alias
10948 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010949 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010950 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10951 // Determine how much the GEP moves the pointer. We are guaranteed to get
10952 // a constant back from EmitGEPOffset.
10953 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10954 int64_t Offset = OffsetV->getSExtValue();
10955
10956 // If this GEP instruction doesn't move the pointer, just replace the GEP
10957 // with a bitcast of the real input to the dest type.
10958 if (Offset == 0) {
10959 // If the bitcast is of an allocation, and the allocation will be
10960 // converted to match the type of the cast, don't touch this.
10961 if (isa<AllocationInst>(BCI->getOperand(0))) {
10962 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10963 if (Instruction *I = visitBitCast(*BCI)) {
10964 if (I != BCI) {
10965 I->takeName(BCI);
10966 BCI->getParent()->getInstList().insert(BCI, I);
10967 ReplaceInstUsesWith(*BCI, I);
10968 }
10969 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010970 }
Chris Lattner58407792009-01-09 04:53:57 +000010971 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010972 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010973 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010974
10975 // Otherwise, if the offset is non-zero, we need to find out if there is a
10976 // field at Offset in 'A's type. If so, we can pull the cast through the
10977 // GEP.
10978 SmallVector<Value*, 8> NewIndices;
10979 const Type *InTy =
10980 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10981 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10982 Instruction *NGEP =
10983 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10984 NewIndices.end());
10985 if (NGEP->getType() == GEP.getType()) return NGEP;
10986 InsertNewInstBefore(NGEP, GEP);
10987 NGEP->takeName(&GEP);
10988 return new BitCastInst(NGEP, GEP.getType());
10989 }
Chris Lattner58407792009-01-09 04:53:57 +000010990 }
10991 }
10992
Chris Lattner8a2a3112001-12-14 16:52:21 +000010993 return 0;
10994}
10995
Chris Lattner0864acf2002-11-04 16:18:53 +000010996Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10997 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010998 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010999 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11000 const Type *NewTy =
11001 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011002 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011003
11004 // Create and insert the replacement instruction...
11005 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011006 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011007 else {
11008 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011009 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011010 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011011
11012 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011013
Chris Lattner0864acf2002-11-04 16:18:53 +000011014 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011015 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011016 //
11017 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011018 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011019
11020 // Now that I is pointing to the first non-allocation-inst in the block,
11021 // insert our getelementptr instruction...
11022 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000011023 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011024 Value *Idx[2];
11025 Idx[0] = NullIdx;
11026 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011027 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11028 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011029
11030 // Now make everything use the getelementptr instead of the original
11031 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011032 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011033 } else if (isa<UndefValue>(AI.getArraySize())) {
11034 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011035 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011036 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011037
Dan Gohman6893cd72009-01-13 20:18:38 +000011038 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11039 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011040 // Note that we only do this for alloca's, because malloc should allocate
11041 // and return a unique pointer, even for a zero byte allocation.
Dan Gohman6893cd72009-01-13 20:18:38 +000011042 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
11043 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11044
11045 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11046 if (AI.getAlignment() == 0)
11047 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11048 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011049
Chris Lattner0864acf2002-11-04 16:18:53 +000011050 return 0;
11051}
11052
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011053Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11054 Value *Op = FI.getOperand(0);
11055
Chris Lattner17be6352004-10-18 02:59:09 +000011056 // free undef -> unreachable.
11057 if (isa<UndefValue>(Op)) {
11058 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011059 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011060 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011061 return EraseInstFromFunction(FI);
11062 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011063
Chris Lattner6160e852004-02-28 04:57:37 +000011064 // If we have 'free null' delete the instruction. This can happen in stl code
11065 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011066 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011067 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011068
11069 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11070 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11071 FI.setOperand(0, CI->getOperand(0));
11072 return &FI;
11073 }
11074
11075 // Change free (gep X, 0,0,0,0) into free(X)
11076 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11077 if (GEPI->hasAllZeroIndices()) {
11078 AddToWorkList(GEPI);
11079 FI.setOperand(0, GEPI->getOperand(0));
11080 return &FI;
11081 }
11082 }
11083
11084 // Change free(malloc) into nothing, if the malloc has a single use.
11085 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11086 if (MI->hasOneUse()) {
11087 EraseInstFromFunction(FI);
11088 return EraseInstFromFunction(*MI);
11089 }
Chris Lattner6160e852004-02-28 04:57:37 +000011090
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011091 return 0;
11092}
11093
11094
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011095/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011096static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011097 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011098 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011099 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011100
Devang Patel99db6ad2007-10-18 19:52:32 +000011101 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11102 // Instead of loading constant c string, use corresponding integer value
11103 // directly if string length is small enough.
Bill Wendling0582ae92009-03-13 04:39:26 +000011104 std::string Str;
11105 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11106 unsigned len = Str.length();
Devang Patel99db6ad2007-10-18 19:52:32 +000011107 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11108 unsigned numBits = Ty->getPrimitiveSizeInBits();
11109 // Replace LI with immediate integer store.
11110 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000011111 APInt StrVal(numBits, 0);
11112 APInt SingleChar(numBits, 0);
11113 if (TD->isLittleEndian()) {
11114 for (signed i = len-1; i >= 0; i--) {
Nick Lewycky2ec0dbf2009-02-21 20:50:42 +000011115 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling587c01d2008-02-26 10:53:30 +000011116 StrVal = (StrVal << 8) | SingleChar;
11117 }
11118 } else {
11119 for (unsigned i = 0; i < len; i++) {
Nick Lewycky2ec0dbf2009-02-21 20:50:42 +000011120 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling587c01d2008-02-26 10:53:30 +000011121 StrVal = (StrVal << 8) | SingleChar;
11122 }
11123 // Append NULL at the end.
11124 SingleChar = 0;
11125 StrVal = (StrVal << 8) | SingleChar;
11126 }
11127 Value *NL = ConstantInt::get(StrVal);
11128 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000011129 }
11130 }
11131 }
11132
Mon P Wang6753f952009-02-07 22:19:29 +000011133 const PointerType *DestTy = cast<PointerType>(CI->getType());
11134 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011135 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011136
11137 // If the address spaces don't match, don't eliminate the cast.
11138 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11139 return 0;
11140
Chris Lattnerb89e0712004-07-13 01:49:43 +000011141 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011142
Reid Spencer42230162007-01-22 05:51:25 +000011143 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011144 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011145 // If the source is an array, the code below will not succeed. Check to
11146 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11147 // constants.
11148 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11149 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11150 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011151 Value *Idxs[2];
11152 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11153 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011154 SrcTy = cast<PointerType>(CastOp->getType());
11155 SrcPTy = SrcTy->getElementType();
11156 }
11157
Reid Spencer42230162007-01-22 05:51:25 +000011158 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011159 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011160 // Do not allow turning this into a load of an integer, which is then
11161 // casted to a pointer, this pessimizes pointer analysis a lot.
11162 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011163 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11164 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011165
Chris Lattnerf9527852005-01-31 04:50:46 +000011166 // Okay, we are casting from one integer or pointer type to another of
11167 // the same size. Instead of casting the pointer before the load, cast
11168 // the result of the loaded value.
11169 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11170 CI->getName(),
11171 LI.isVolatile()),LI);
11172 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011173 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011174 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011175 }
11176 }
11177 return 0;
11178}
11179
Chris Lattnerc10aced2004-09-19 18:43:46 +000011180/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011181/// from this value cannot trap. If it is not obviously safe to load from the
11182/// specified pointer, we do a quick local scan of the basic block containing
11183/// ScanFrom, to determine if the address is already accessed.
11184static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011185 // If it is an alloca it is always safe to load from.
11186 if (isa<AllocaInst>(V)) return true;
11187
Duncan Sands46318cd2007-09-19 10:25:38 +000011188 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011189 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011190 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011191 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011192
11193 // Otherwise, be a little bit agressive by scanning the local block where we
11194 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011195 // from/to. If so, the previous load or store would have already trapped,
11196 // so there is no harm doing an extra load (also, CSE will later eliminate
11197 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011198 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11199
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011200 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011201 --BBI;
11202
Chris Lattner2de3fec2008-06-20 05:12:56 +000011203 // If we see a free or a call (which might do a free) the pointer could be
11204 // marked invalid.
Dale Johannesend1c135c2009-03-13 19:23:20 +000011205 if (isa<FreeInst>(BBI) ||
11206 (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
Chris Lattner2de3fec2008-06-20 05:12:56 +000011207 return false;
11208
Chris Lattner8a375202004-09-19 19:18:10 +000011209 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11210 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011211 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011212 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011213 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011214
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011215 }
Chris Lattner8a375202004-09-19 19:18:10 +000011216 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011217}
11218
Chris Lattner833b8a42003-06-26 05:06:25 +000011219Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11220 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011221
Dan Gohman9941f742007-07-20 16:34:21 +000011222 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011223 unsigned KnownAlign =
11224 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011225 if (KnownAlign >
11226 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11227 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011228 LI.setAlignment(KnownAlign);
11229
Chris Lattner37366c12005-05-01 04:24:53 +000011230 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011231 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011232 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011233 return Res;
11234
11235 // None of the following transforms are legal for volatile loads.
11236 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011237
Dan Gohman2276a7b2008-10-15 23:19:35 +000011238 // Do really simple store-to-load forwarding and load CSE, to catch cases
11239 // where there are several consequtive memory accesses to the same location,
11240 // separated by a few arithmetic operations.
11241 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011242 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11243 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011244
Christopher Lambb15147e2007-12-29 07:56:53 +000011245 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11246 const Value *GEPI0 = GEPI->getOperand(0);
11247 // TODO: Consider a target hook for valid address spaces for this xform.
11248 if (isa<ConstantPointerNull>(GEPI0) &&
11249 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011250 // Insert a new store to null instruction before the load to indicate
11251 // that this code is not reachable. We do this instead of inserting
11252 // an unreachable instruction directly because we cannot modify the
11253 // CFG.
11254 new StoreInst(UndefValue::get(LI.getType()),
11255 Constant::getNullValue(Op->getType()), &LI);
11256 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11257 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011258 }
Chris Lattner37366c12005-05-01 04:24:53 +000011259
Chris Lattnere87597f2004-10-16 18:11:37 +000011260 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011261 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011262 // TODO: Consider a target hook for valid address spaces for this xform.
11263 if (isa<UndefValue>(C) || (C->isNullValue() &&
11264 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011265 // Insert a new store to null instruction before the load to indicate that
11266 // this code is not reachable. We do this instead of inserting an
11267 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011268 new StoreInst(UndefValue::get(LI.getType()),
11269 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011270 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011271 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011272
Chris Lattnere87597f2004-10-16 18:11:37 +000011273 // Instcombine load (constant global) into the value loaded.
11274 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011275 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011276 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011277
Chris Lattnere87597f2004-10-16 18:11:37 +000011278 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011279 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011280 if (CE->getOpcode() == Instruction::GetElementPtr) {
11281 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011282 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011283 if (Constant *V =
11284 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011285 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011286 if (CE->getOperand(0)->isNullValue()) {
11287 // Insert a new store to null instruction before the load to indicate
11288 // that this code is not reachable. We do this instead of inserting
11289 // an unreachable instruction directly because we cannot modify the
11290 // CFG.
11291 new StoreInst(UndefValue::get(LI.getType()),
11292 Constant::getNullValue(Op->getType()), &LI);
11293 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11294 }
11295
Reid Spencer3da59db2006-11-27 01:05:10 +000011296 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011297 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011298 return Res;
11299 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011300 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011301 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011302
11303 // If this load comes from anywhere in a constant global, and if the global
11304 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011305 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011306 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011307 if (GV->getInitializer()->isNullValue())
11308 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11309 else if (isa<UndefValue>(GV->getInitializer()))
11310 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11311 }
11312 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011313
Chris Lattner37366c12005-05-01 04:24:53 +000011314 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011315 // Change select and PHI nodes to select values instead of addresses: this
11316 // helps alias analysis out a lot, allows many others simplifications, and
11317 // exposes redundancy in the code.
11318 //
11319 // Note that we cannot do the transformation unless we know that the
11320 // introduced loads cannot trap! Something like this is valid as long as
11321 // the condition is always false: load (select bool %C, int* null, int* %G),
11322 // but it would not be valid if we transformed it to load from null
11323 // unconditionally.
11324 //
11325 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11326 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011327 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11328 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011329 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011330 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011331 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011332 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011333 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011334 }
11335
Chris Lattner684fe212004-09-23 15:46:00 +000011336 // load (select (cond, null, P)) -> load P
11337 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11338 if (C->isNullValue()) {
11339 LI.setOperand(0, SI->getOperand(2));
11340 return &LI;
11341 }
11342
11343 // load (select (cond, P, null)) -> load P
11344 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11345 if (C->isNullValue()) {
11346 LI.setOperand(0, SI->getOperand(1));
11347 return &LI;
11348 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011349 }
11350 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011351 return 0;
11352}
11353
Reid Spencer55af2b52007-01-19 21:20:31 +000011354/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011355/// when possible. This makes it generally easy to do alias analysis and/or
11356/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011357static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11358 User *CI = cast<User>(SI.getOperand(1));
11359 Value *CastOp = CI->getOperand(0);
11360
11361 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011362 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11363 if (SrcTy == 0) return 0;
11364
11365 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011366
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011367 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11368 return 0;
11369
Chris Lattner3914f722009-01-24 01:00:13 +000011370 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11371 /// to its first element. This allows us to handle things like:
11372 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11373 /// on 32-bit hosts.
11374 SmallVector<Value*, 4> NewGEPIndices;
11375
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011376 // If the source is an array, the code below will not succeed. Check to
11377 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11378 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011379 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11380 // Index through pointer.
11381 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11382 NewGEPIndices.push_back(Zero);
11383
11384 while (1) {
11385 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011386 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011387 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011388 NewGEPIndices.push_back(Zero);
11389 SrcPTy = STy->getElementType(0);
11390 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11391 NewGEPIndices.push_back(Zero);
11392 SrcPTy = ATy->getElementType();
11393 } else {
11394 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011395 }
Chris Lattner3914f722009-01-24 01:00:13 +000011396 }
11397
11398 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11399 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011400
11401 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11402 return 0;
11403
Chris Lattner71759c42009-01-16 20:12:52 +000011404 // If the pointers point into different address spaces or if they point to
11405 // values with different sizes, we can't do the transformation.
11406 if (SrcTy->getAddressSpace() !=
11407 cast<PointerType>(CI->getType())->getAddressSpace() ||
11408 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011409 IC.getTargetData().getTypeSizeInBits(DestPTy))
11410 return 0;
11411
11412 // Okay, we are casting from one integer or pointer type to another of
11413 // the same size. Instead of casting the pointer before
11414 // the store, cast the value to be stored.
11415 Value *NewCast;
11416 Value *SIOp0 = SI.getOperand(0);
11417 Instruction::CastOps opcode = Instruction::BitCast;
11418 const Type* CastSrcTy = SIOp0->getType();
11419 const Type* CastDstTy = SrcPTy;
11420 if (isa<PointerType>(CastDstTy)) {
11421 if (CastSrcTy->isInteger())
11422 opcode = Instruction::IntToPtr;
11423 } else if (isa<IntegerType>(CastDstTy)) {
11424 if (isa<PointerType>(SIOp0->getType()))
11425 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011426 }
Chris Lattner3914f722009-01-24 01:00:13 +000011427
11428 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11429 // emit a GEP to index into its first field.
11430 if (!NewGEPIndices.empty()) {
11431 if (Constant *C = dyn_cast<Constant>(CastOp))
11432 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11433 NewGEPIndices.size());
11434 else
11435 CastOp = IC.InsertNewInstBefore(
11436 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11437 NewGEPIndices.end()), SI);
11438 }
11439
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011440 if (Constant *C = dyn_cast<Constant>(SIOp0))
11441 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11442 else
11443 NewCast = IC.InsertNewInstBefore(
11444 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11445 SI);
11446 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011447}
11448
Chris Lattner4aebaee2008-11-27 08:56:30 +000011449/// equivalentAddressValues - Test if A and B will obviously have the same
11450/// value. This includes recognizing that %t0 and %t1 will have the same
11451/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011452/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011453/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011454/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011455/// %t2 = load i32* %t1
11456///
11457static bool equivalentAddressValues(Value *A, Value *B) {
11458 // Test if the values are trivially equivalent.
11459 if (A == B) return true;
11460
11461 // Test if the values come form identical arithmetic instructions.
11462 if (isa<BinaryOperator>(A) ||
11463 isa<CastInst>(A) ||
11464 isa<PHINode>(A) ||
11465 isa<GetElementPtrInst>(A))
11466 if (Instruction *BI = dyn_cast<Instruction>(B))
11467 if (cast<Instruction>(A)->isIdenticalTo(BI))
11468 return true;
11469
11470 // Otherwise they may not be equivalent.
11471 return false;
11472}
11473
Dale Johannesen4945c652009-03-03 21:26:39 +000011474// If this instruction has two uses, one of which is a llvm.dbg.declare,
11475// return the llvm.dbg.declare.
11476DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11477 if (!V->hasNUses(2))
11478 return 0;
11479 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11480 UI != E; ++UI) {
11481 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11482 return DI;
11483 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11484 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11485 return DI;
11486 }
11487 }
11488 return 0;
11489}
11490
Chris Lattner2f503e62005-01-31 05:36:43 +000011491Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11492 Value *Val = SI.getOperand(0);
11493 Value *Ptr = SI.getOperand(1);
11494
11495 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011496 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011497 ++NumCombined;
11498 return 0;
11499 }
Chris Lattner836692d2007-01-15 06:51:56 +000011500
11501 // If the RHS is an alloca with a single use, zapify the store, making the
11502 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011503 // If the RHS is an alloca with a two uses, the other one being a
11504 // llvm.dbg.declare, zapify the store and the declare, making the
11505 // alloca dead. We must do this to prevent declare's from affecting
11506 // codegen.
11507 if (!SI.isVolatile()) {
11508 if (Ptr->hasOneUse()) {
11509 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011510 EraseInstFromFunction(SI);
11511 ++NumCombined;
11512 return 0;
11513 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011514 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11515 if (isa<AllocaInst>(GEP->getOperand(0))) {
11516 if (GEP->getOperand(0)->hasOneUse()) {
11517 EraseInstFromFunction(SI);
11518 ++NumCombined;
11519 return 0;
11520 }
11521 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11522 EraseInstFromFunction(*DI);
11523 EraseInstFromFunction(SI);
11524 ++NumCombined;
11525 return 0;
11526 }
11527 }
11528 }
11529 }
11530 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11531 EraseInstFromFunction(*DI);
11532 EraseInstFromFunction(SI);
11533 ++NumCombined;
11534 return 0;
11535 }
Chris Lattner836692d2007-01-15 06:51:56 +000011536 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011537
Dan Gohman9941f742007-07-20 16:34:21 +000011538 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011539 unsigned KnownAlign =
11540 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011541 if (KnownAlign >
11542 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11543 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011544 SI.setAlignment(KnownAlign);
11545
Dale Johannesenacb51a32009-03-03 01:43:03 +000011546 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011547 // stores to the same location, separated by a few arithmetic operations. This
11548 // situation often occurs with bitfield accesses.
11549 BasicBlock::iterator BBI = &SI;
11550 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11551 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011552 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011553 // Don't count debug info directives, lest they affect codegen,
11554 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11555 // It is necessary for correctness to skip those that feed into a
11556 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011557 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011558 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011559 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011560 continue;
11561 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011562
11563 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11564 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011565 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11566 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011567 ++NumDeadStore;
11568 ++BBI;
11569 EraseInstFromFunction(*PrevSI);
11570 continue;
11571 }
11572 break;
11573 }
11574
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011575 // If this is a load, we have to stop. However, if the loaded value is from
11576 // the pointer we're loading and is producing the pointer we're storing,
11577 // then *this* store is dead (X = load P; store X -> P).
11578 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011579 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11580 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011581 EraseInstFromFunction(SI);
11582 ++NumCombined;
11583 return 0;
11584 }
11585 // Otherwise, this is a load from some other location. Stores before it
11586 // may not be dead.
11587 break;
11588 }
11589
Chris Lattner9ca96412006-02-08 03:25:32 +000011590 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011591 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011592 break;
11593 }
11594
11595
11596 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011597
11598 // store X, null -> turns into 'unreachable' in SimplifyCFG
11599 if (isa<ConstantPointerNull>(Ptr)) {
11600 if (!isa<UndefValue>(Val)) {
11601 SI.setOperand(0, UndefValue::get(Val->getType()));
11602 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011603 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011604 ++NumCombined;
11605 }
11606 return 0; // Do not modify these!
11607 }
11608
11609 // store undef, Ptr -> noop
11610 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011611 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011612 ++NumCombined;
11613 return 0;
11614 }
11615
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011616 // If the pointer destination is a cast, see if we can fold the cast into the
11617 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011618 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011619 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11620 return Res;
11621 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011622 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011623 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11624 return Res;
11625
Chris Lattner408902b2005-09-12 23:23:25 +000011626
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011627 // If this store is the last instruction in the basic block (possibly
11628 // excepting debug info instructions and the pointer bitcasts that feed
11629 // into them), and if the block ends with an unconditional branch, try
11630 // to move it to the successor block.
11631 BBI = &SI;
11632 do {
11633 ++BBI;
11634 } while (isa<DbgInfoIntrinsic>(BBI) ||
11635 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011636 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011637 if (BI->isUnconditional())
11638 if (SimplifyStoreAtEndOfBlock(SI))
11639 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011640
Chris Lattner2f503e62005-01-31 05:36:43 +000011641 return 0;
11642}
11643
Chris Lattner3284d1f2007-04-15 00:07:55 +000011644/// SimplifyStoreAtEndOfBlock - Turn things like:
11645/// if () { *P = v1; } else { *P = v2 }
11646/// into a phi node with a store in the successor.
11647///
Chris Lattner31755a02007-04-15 01:02:18 +000011648/// Simplify things like:
11649/// *P = v1; if () { *P = v2; }
11650/// into a phi node with a store in the successor.
11651///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011652bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11653 BasicBlock *StoreBB = SI.getParent();
11654
11655 // Check to see if the successor block has exactly two incoming edges. If
11656 // so, see if the other predecessor contains a store to the same location.
11657 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011658 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011659
11660 // Determine whether Dest has exactly two predecessors and, if so, compute
11661 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011662 pred_iterator PI = pred_begin(DestBB);
11663 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011664 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011665 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011666 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011667 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011668 return false;
11669
11670 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011671 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011672 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011673 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011674 }
Chris Lattner31755a02007-04-15 01:02:18 +000011675 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011676 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011677
11678 // Bail out if all the relevant blocks aren't distinct (this can happen,
11679 // for example, if SI is in an infinite loop)
11680 if (StoreBB == DestBB || OtherBB == DestBB)
11681 return false;
11682
Chris Lattner31755a02007-04-15 01:02:18 +000011683 // Verify that the other block ends in a branch and is not otherwise empty.
11684 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011685 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011686 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011687 return false;
11688
Chris Lattner31755a02007-04-15 01:02:18 +000011689 // If the other block ends in an unconditional branch, check for the 'if then
11690 // else' case. there is an instruction before the branch.
11691 StoreInst *OtherStore = 0;
11692 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011693 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011694 // Skip over debugging info.
11695 while (isa<DbgInfoIntrinsic>(BBI) ||
11696 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11697 if (BBI==OtherBB->begin())
11698 return false;
11699 --BBI;
11700 }
11701 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011702 OtherStore = dyn_cast<StoreInst>(BBI);
11703 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11704 return false;
11705 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011706 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011707 // destinations is StoreBB, then we have the if/then case.
11708 if (OtherBr->getSuccessor(0) != StoreBB &&
11709 OtherBr->getSuccessor(1) != StoreBB)
11710 return false;
11711
11712 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011713 // if/then triangle. See if there is a store to the same ptr as SI that
11714 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011715 for (;; --BBI) {
11716 // Check to see if we find the matching store.
11717 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11718 if (OtherStore->getOperand(1) != SI.getOperand(1))
11719 return false;
11720 break;
11721 }
Eli Friedman6903a242008-06-13 22:02:12 +000011722 // If we find something that may be using or overwriting the stored
11723 // value, or if we run out of instructions, we can't do the xform.
11724 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011725 BBI == OtherBB->begin())
11726 return false;
11727 }
11728
11729 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011730 // make sure nothing reads or overwrites the stored value in
11731 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011732 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11733 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011734 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011735 return false;
11736 }
11737 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011738
Chris Lattner31755a02007-04-15 01:02:18 +000011739 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011740 Value *MergedVal = OtherStore->getOperand(0);
11741 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011742 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011743 PN->reserveOperandSpace(2);
11744 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011745 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11746 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011747 }
11748
11749 // Advance to a place where it is safe to insert the new store and
11750 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011751 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011752 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11753 OtherStore->isVolatile()), *BBI);
11754
11755 // Nuke the old stores.
11756 EraseInstFromFunction(SI);
11757 EraseInstFromFunction(*OtherStore);
11758 ++NumCombined;
11759 return true;
11760}
11761
Chris Lattner2f503e62005-01-31 05:36:43 +000011762
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011763Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11764 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011765 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011766 BasicBlock *TrueDest;
11767 BasicBlock *FalseDest;
11768 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11769 !isa<Constant>(X)) {
11770 // Swap Destinations and condition...
11771 BI.setCondition(X);
11772 BI.setSuccessor(0, FalseDest);
11773 BI.setSuccessor(1, TrueDest);
11774 return &BI;
11775 }
11776
Reid Spencere4d87aa2006-12-23 06:05:41 +000011777 // Cannonicalize fcmp_one -> fcmp_oeq
11778 FCmpInst::Predicate FPred; Value *Y;
11779 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11780 TrueDest, FalseDest)))
11781 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11782 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11783 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011784 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011785 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11786 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011787 // Swap Destinations and condition...
11788 BI.setCondition(NewSCC);
11789 BI.setSuccessor(0, FalseDest);
11790 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011791 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011792 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011793 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011794 return &BI;
11795 }
11796
11797 // Cannonicalize icmp_ne -> icmp_eq
11798 ICmpInst::Predicate IPred;
11799 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11800 TrueDest, FalseDest)))
11801 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11802 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11803 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11804 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011805 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011806 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11807 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011808 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011809 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011810 BI.setSuccessor(0, FalseDest);
11811 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011812 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011813 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011814 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011815 return &BI;
11816 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011817
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011818 return 0;
11819}
Chris Lattner0864acf2002-11-04 16:18:53 +000011820
Chris Lattner46238a62004-07-03 00:26:11 +000011821Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11822 Value *Cond = SI.getCondition();
11823 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11824 if (I->getOpcode() == Instruction::Add)
11825 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11826 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11827 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011828 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011829 AddRHS));
11830 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011831 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011832 return &SI;
11833 }
11834 }
11835 return 0;
11836}
11837
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011838Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011839 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011840
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011841 if (!EV.hasIndices())
11842 return ReplaceInstUsesWith(EV, Agg);
11843
11844 if (Constant *C = dyn_cast<Constant>(Agg)) {
11845 if (isa<UndefValue>(C))
11846 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11847
11848 if (isa<ConstantAggregateZero>(C))
11849 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11850
11851 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11852 // Extract the element indexed by the first index out of the constant
11853 Value *V = C->getOperand(*EV.idx_begin());
11854 if (EV.getNumIndices() > 1)
11855 // Extract the remaining indices out of the constant indexed by the
11856 // first index
11857 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11858 else
11859 return ReplaceInstUsesWith(EV, V);
11860 }
11861 return 0; // Can't handle other constants
11862 }
11863 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11864 // We're extracting from an insertvalue instruction, compare the indices
11865 const unsigned *exti, *exte, *insi, *inse;
11866 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11867 exte = EV.idx_end(), inse = IV->idx_end();
11868 exti != exte && insi != inse;
11869 ++exti, ++insi) {
11870 if (*insi != *exti)
11871 // The insert and extract both reference distinctly different elements.
11872 // This means the extract is not influenced by the insert, and we can
11873 // replace the aggregate operand of the extract with the aggregate
11874 // operand of the insert. i.e., replace
11875 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11876 // %E = extractvalue { i32, { i32 } } %I, 0
11877 // with
11878 // %E = extractvalue { i32, { i32 } } %A, 0
11879 return ExtractValueInst::Create(IV->getAggregateOperand(),
11880 EV.idx_begin(), EV.idx_end());
11881 }
11882 if (exti == exte && insi == inse)
11883 // Both iterators are at the end: Index lists are identical. Replace
11884 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11885 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11886 // with "i32 42"
11887 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11888 if (exti == exte) {
11889 // The extract list is a prefix of the insert list. i.e. replace
11890 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11891 // %E = extractvalue { i32, { i32 } } %I, 1
11892 // with
11893 // %X = extractvalue { i32, { i32 } } %A, 1
11894 // %E = insertvalue { i32 } %X, i32 42, 0
11895 // by switching the order of the insert and extract (though the
11896 // insertvalue should be left in, since it may have other uses).
11897 Value *NewEV = InsertNewInstBefore(
11898 ExtractValueInst::Create(IV->getAggregateOperand(),
11899 EV.idx_begin(), EV.idx_end()),
11900 EV);
11901 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11902 insi, inse);
11903 }
11904 if (insi == inse)
11905 // The insert list is a prefix of the extract list
11906 // We can simply remove the common indices from the extract and make it
11907 // operate on the inserted value instead of the insertvalue result.
11908 // i.e., replace
11909 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11910 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11911 // with
11912 // %E extractvalue { i32 } { i32 42 }, 0
11913 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11914 exti, exte);
11915 }
11916 // Can't simplify extracts from other values. Note that nested extracts are
11917 // already simplified implicitely by the above (extract ( extract (insert) )
11918 // will be translated into extract ( insert ( extract ) ) first and then just
11919 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011920 return 0;
11921}
11922
Chris Lattner220b0cf2006-03-05 00:22:33 +000011923/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11924/// is to leave as a vector operation.
11925static bool CheapToScalarize(Value *V, bool isConstant) {
11926 if (isa<ConstantAggregateZero>(V))
11927 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011928 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011929 if (isConstant) return true;
11930 // If all elts are the same, we can extract.
11931 Constant *Op0 = C->getOperand(0);
11932 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11933 if (C->getOperand(i) != Op0)
11934 return false;
11935 return true;
11936 }
11937 Instruction *I = dyn_cast<Instruction>(V);
11938 if (!I) return false;
11939
11940 // Insert element gets simplified to the inserted element or is deleted if
11941 // this is constant idx extract element and its a constant idx insertelt.
11942 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11943 isa<ConstantInt>(I->getOperand(2)))
11944 return true;
11945 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11946 return true;
11947 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11948 if (BO->hasOneUse() &&
11949 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11950 CheapToScalarize(BO->getOperand(1), isConstant)))
11951 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011952 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11953 if (CI->hasOneUse() &&
11954 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11955 CheapToScalarize(CI->getOperand(1), isConstant)))
11956 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011957
11958 return false;
11959}
11960
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011961/// Read and decode a shufflevector mask.
11962///
11963/// It turns undef elements into values that are larger than the number of
11964/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011965static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11966 unsigned NElts = SVI->getType()->getNumElements();
11967 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11968 return std::vector<unsigned>(NElts, 0);
11969 if (isa<UndefValue>(SVI->getOperand(2)))
11970 return std::vector<unsigned>(NElts, 2*NElts);
11971
11972 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011973 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011974 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11975 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011976 Result.push_back(NElts*2); // undef -> 8
11977 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011978 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011979 return Result;
11980}
11981
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011982/// FindScalarElement - Given a vector and an element number, see if the scalar
11983/// value is already around as a register, for example if it were inserted then
11984/// extracted from the vector.
11985static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011986 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11987 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011988 unsigned Width = PTy->getNumElements();
11989 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011990 return UndefValue::get(PTy->getElementType());
11991
11992 if (isa<UndefValue>(V))
11993 return UndefValue::get(PTy->getElementType());
11994 else if (isa<ConstantAggregateZero>(V))
11995 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011996 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011997 return CP->getOperand(EltNo);
11998 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11999 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012000 if (!isa<ConstantInt>(III->getOperand(2)))
12001 return 0;
12002 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012003
12004 // If this is an insert to the element we are looking for, return the
12005 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012006 if (EltNo == IIElt)
12007 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012008
12009 // Otherwise, the insertelement doesn't modify the value, recurse on its
12010 // vector input.
12011 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012012 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012013 unsigned LHSWidth =
12014 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012015 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012016 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012017 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012018 else if (InEl < LHSWidth*2)
12019 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012020 else
12021 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012022 }
12023
12024 // Otherwise, we don't know.
12025 return 0;
12026}
12027
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012028Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012029 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012030 if (isa<UndefValue>(EI.getOperand(0)))
12031 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12032
Dan Gohman07a96762007-07-16 14:29:03 +000012033 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012034 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12035 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12036
Reid Spencer9d6565a2007-02-15 02:26:10 +000012037 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012038 // If vector val is constant with all elements the same, replace EI with
12039 // that element. When the elements are not identical, we cannot replace yet
12040 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012041 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012042 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012043 if (C->getOperand(i) != op0) {
12044 op0 = 0;
12045 break;
12046 }
12047 if (op0)
12048 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012049 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012050
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012051 // If extracting a specified index from the vector, see if we can recursively
12052 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012053 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012054 unsigned IndexVal = IdxC->getZExtValue();
12055 unsigned VectorWidth =
12056 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12057
12058 // If this is extracting an invalid index, turn this into undef, to avoid
12059 // crashing the code below.
12060 if (IndexVal >= VectorWidth)
12061 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12062
Chris Lattner867b99f2006-10-05 06:55:50 +000012063 // This instruction only demands the single element from the input vector.
12064 // If the input vector has a single use, simplify it based on this use
12065 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012066 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012067 APInt UndefElts(VectorWidth, 0);
12068 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012069 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012070 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012071 EI.setOperand(0, V);
12072 return &EI;
12073 }
12074 }
12075
Reid Spencerb83eb642006-10-20 07:07:24 +000012076 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012077 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012078
12079 // If the this extractelement is directly using a bitcast from a vector of
12080 // the same number of elements, see if we can find the source element from
12081 // it. In this case, we will end up needing to bitcast the scalars.
12082 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12083 if (const VectorType *VT =
12084 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12085 if (VT->getNumElements() == VectorWidth)
12086 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12087 return new BitCastInst(Elt, EI.getType());
12088 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012089 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012090
Chris Lattner73fa49d2006-05-25 22:53:38 +000012091 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012092 if (I->hasOneUse()) {
12093 // Push extractelement into predecessor operation if legal and
12094 // profitable to do so
12095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012096 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12097 if (CheapToScalarize(BO, isConstantElt)) {
12098 ExtractElementInst *newEI0 =
12099 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12100 EI.getName()+".lhs");
12101 ExtractElementInst *newEI1 =
12102 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12103 EI.getName()+".rhs");
12104 InsertNewInstBefore(newEI0, EI);
12105 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012106 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012107 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012108 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012109 unsigned AS =
12110 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012111 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12112 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012113 GetElementPtrInst *GEP =
12114 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012115 InsertNewInstBefore(GEP, EI);
12116 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012117 }
12118 }
12119 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12120 // Extracting the inserted element?
12121 if (IE->getOperand(2) == EI.getOperand(1))
12122 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12123 // If the inserted and extracted elements are constants, they must not
12124 // be the same value, extract from the pre-inserted value instead.
12125 if (isa<Constant>(IE->getOperand(2)) &&
12126 isa<Constant>(EI.getOperand(1))) {
12127 AddUsesToWorkList(EI);
12128 EI.setOperand(0, IE->getOperand(0));
12129 return &EI;
12130 }
12131 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12132 // If this is extracting an element from a shufflevector, figure out where
12133 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012134 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12135 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012136 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012137 unsigned LHSWidth =
12138 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12139
12140 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012141 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012142 else if (SrcIdx < LHSWidth*2) {
12143 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012144 Src = SVI->getOperand(1);
12145 } else {
12146 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012147 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012148 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012149 }
12150 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012151 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012152 return 0;
12153}
12154
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012155/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12156/// elements from either LHS or RHS, return the shuffle mask and true.
12157/// Otherwise, return false.
12158static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12159 std::vector<Constant*> &Mask) {
12160 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12161 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012162 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012163
12164 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012165 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012166 return true;
12167 } else if (V == LHS) {
12168 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012169 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012170 return true;
12171 } else if (V == RHS) {
12172 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012173 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012174 return true;
12175 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12176 // If this is an insert of an extract from some other vector, include it.
12177 Value *VecOp = IEI->getOperand(0);
12178 Value *ScalarOp = IEI->getOperand(1);
12179 Value *IdxOp = IEI->getOperand(2);
12180
Chris Lattnerd929f062006-04-27 21:14:21 +000012181 if (!isa<ConstantInt>(IdxOp))
12182 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012183 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012184
12185 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12186 // Okay, we can handle this if the vector we are insertinting into is
12187 // transitively ok.
12188 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12189 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012190 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012191 return true;
12192 }
12193 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12194 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012195 EI->getOperand(0)->getType() == V->getType()) {
12196 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012197 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012198
12199 // This must be extracting from either LHS or RHS.
12200 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12201 // Okay, we can handle this if the vector we are insertinting into is
12202 // transitively ok.
12203 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12204 // If so, update the mask to reflect the inserted value.
12205 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012206 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012207 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012208 } else {
12209 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012210 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012211 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012212
12213 }
12214 return true;
12215 }
12216 }
12217 }
12218 }
12219 }
12220 // TODO: Handle shufflevector here!
12221
12222 return false;
12223}
12224
12225/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12226/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12227/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012228static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012229 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012230 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012231 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012232 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012233 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012234
12235 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012236 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012237 return V;
12238 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012239 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012240 return V;
12241 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12242 // If this is an insert of an extract from some other vector, include it.
12243 Value *VecOp = IEI->getOperand(0);
12244 Value *ScalarOp = IEI->getOperand(1);
12245 Value *IdxOp = IEI->getOperand(2);
12246
12247 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12248 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12249 EI->getOperand(0)->getType() == V->getType()) {
12250 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012251 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12252 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012253
12254 // Either the extracted from or inserted into vector must be RHSVec,
12255 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012256 if (EI->getOperand(0) == RHS || RHS == 0) {
12257 RHS = EI->getOperand(0);
12258 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012259 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012260 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012261 return V;
12262 }
12263
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012264 if (VecOp == RHS) {
12265 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012266 // Everything but the extracted element is replaced with the RHS.
12267 for (unsigned i = 0; i != NumElts; ++i) {
12268 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012269 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012270 }
12271 return V;
12272 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012273
12274 // If this insertelement is a chain that comes from exactly these two
12275 // vectors, return the vector and the effective shuffle.
12276 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12277 return EI->getOperand(0);
12278
Chris Lattnerefb47352006-04-15 01:39:45 +000012279 }
12280 }
12281 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012282 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012283
12284 // Otherwise, can't do anything fancy. Return an identity vector.
12285 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012286 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012287 return V;
12288}
12289
12290Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12291 Value *VecOp = IE.getOperand(0);
12292 Value *ScalarOp = IE.getOperand(1);
12293 Value *IdxOp = IE.getOperand(2);
12294
Chris Lattner599ded12007-04-09 01:11:16 +000012295 // Inserting an undef or into an undefined place, remove this.
12296 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12297 ReplaceInstUsesWith(IE, VecOp);
12298
Chris Lattnerefb47352006-04-15 01:39:45 +000012299 // If the inserted element was extracted from some other vector, and if the
12300 // indexes are constant, try to turn this into a shufflevector operation.
12301 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12302 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12303 EI->getOperand(0)->getType() == IE.getType()) {
12304 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012305 unsigned ExtractedIdx =
12306 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012307 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012308
12309 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12310 return ReplaceInstUsesWith(IE, VecOp);
12311
12312 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12313 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12314
12315 // If we are extracting a value from a vector, then inserting it right
12316 // back into the same place, just use the input vector.
12317 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12318 return ReplaceInstUsesWith(IE, VecOp);
12319
12320 // We could theoretically do this for ANY input. However, doing so could
12321 // turn chains of insertelement instructions into a chain of shufflevector
12322 // instructions, and right now we do not merge shufflevectors. As such,
12323 // only do this in a situation where it is clear that there is benefit.
12324 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12325 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12326 // the values of VecOp, except then one read from EIOp0.
12327 // Build a new shuffle mask.
12328 std::vector<Constant*> Mask;
12329 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012330 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012331 else {
12332 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012333 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012334 NumVectorElts));
12335 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012336 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012337 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012338 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012339 }
12340
12341 // If this insertelement isn't used by some other insertelement, turn it
12342 // (and any insertelements it points to), into one big shuffle.
12343 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12344 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012345 Value *RHS = 0;
12346 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12347 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12348 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012349 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012350 }
12351 }
12352 }
12353
12354 return 0;
12355}
12356
12357
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012358Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12359 Value *LHS = SVI.getOperand(0);
12360 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012361 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012362
12363 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012364
Chris Lattner867b99f2006-10-05 06:55:50 +000012365 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012366 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012367 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012368
Dan Gohman488fbfc2008-09-09 18:11:14 +000012369 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012370
12371 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12372 return 0;
12373
Evan Cheng388df622009-02-03 10:05:09 +000012374 APInt UndefElts(VWidth, 0);
12375 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12376 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012377 LHS = SVI.getOperand(0);
12378 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012379 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012380 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012381
Chris Lattner863bcff2006-05-25 23:48:38 +000012382 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12383 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12384 if (LHS == RHS || isa<UndefValue>(LHS)) {
12385 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012386 // shuffle(undef,undef,mask) -> undef.
12387 return ReplaceInstUsesWith(SVI, LHS);
12388 }
12389
Chris Lattner863bcff2006-05-25 23:48:38 +000012390 // Remap any references to RHS to use LHS.
12391 std::vector<Constant*> Elts;
12392 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012393 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012394 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012395 else {
12396 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012397 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012398 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012399 Elts.push_back(UndefValue::get(Type::Int32Ty));
12400 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012401 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012402 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12403 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012404 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012405 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012406 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012407 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012408 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012409 LHS = SVI.getOperand(0);
12410 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012411 MadeChange = true;
12412 }
12413
Chris Lattner7b2e27922006-05-26 00:29:06 +000012414 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012415 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012416
Chris Lattner863bcff2006-05-25 23:48:38 +000012417 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12418 if (Mask[i] >= e*2) continue; // Ignore undef values.
12419 // Is this an identity shuffle of the LHS value?
12420 isLHSID &= (Mask[i] == i);
12421
12422 // Is this an identity shuffle of the RHS value?
12423 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012424 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012425
Chris Lattner863bcff2006-05-25 23:48:38 +000012426 // Eliminate identity shuffles.
12427 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12428 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012429
Chris Lattner7b2e27922006-05-26 00:29:06 +000012430 // If the LHS is a shufflevector itself, see if we can combine it with this
12431 // one without producing an unusual shuffle. Here we are really conservative:
12432 // we are absolutely afraid of producing a shuffle mask not in the input
12433 // program, because the code gen may not be smart enough to turn a merged
12434 // shuffle into two specific shuffles: it may produce worse code. As such,
12435 // we only merge two shuffles if the result is one of the two input shuffle
12436 // masks. In this case, merging the shuffles just removes one instruction,
12437 // which we know is safe. This is good for things like turning:
12438 // (splat(splat)) -> splat.
12439 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12440 if (isa<UndefValue>(RHS)) {
12441 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12442
12443 std::vector<unsigned> NewMask;
12444 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12445 if (Mask[i] >= 2*e)
12446 NewMask.push_back(2*e);
12447 else
12448 NewMask.push_back(LHSMask[Mask[i]]);
12449
12450 // If the result mask is equal to the src shuffle or this shuffle mask, do
12451 // the replacement.
12452 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012453 unsigned LHSInNElts =
12454 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012455 std::vector<Constant*> Elts;
12456 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012457 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012458 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012459 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012460 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012461 }
12462 }
12463 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12464 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012465 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012466 }
12467 }
12468 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012469
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012470 return MadeChange ? &SVI : 0;
12471}
12472
12473
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012474
Chris Lattnerea1c4542004-12-08 23:43:58 +000012475
12476/// TryToSinkInstruction - Try to move the specified instruction from its
12477/// current block into the beginning of DestBlock, which can only happen if it's
12478/// safe to move the instruction past all of the instructions between it and the
12479/// end of its block.
12480static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12481 assert(I->hasOneUse() && "Invariants didn't hold!");
12482
Chris Lattner108e9022005-10-27 17:13:11 +000012483 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012484 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12485 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012486
Chris Lattnerea1c4542004-12-08 23:43:58 +000012487 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012488 if (isa<AllocaInst>(I) && I->getParent() ==
12489 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012490 return false;
12491
Chris Lattner96a52a62004-12-09 07:14:34 +000012492 // We can only sink load instructions if there is nothing between the load and
12493 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012494 if (I->mayReadFromMemory()) {
12495 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012496 Scan != E; ++Scan)
12497 if (Scan->mayWriteToMemory())
12498 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012499 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012500
Dan Gohman02dea8b2008-05-23 21:05:58 +000012501 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012502
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012503 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012504 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012505 ++NumSunkInst;
12506 return true;
12507}
12508
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012509
12510/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12511/// all reachable code to the worklist.
12512///
12513/// This has a couple of tricks to make the code faster and more powerful. In
12514/// particular, we constant fold and DCE instructions as we go, to avoid adding
12515/// them to the worklist (this significantly speeds up instcombine on code where
12516/// many instructions are dead or constant). Additionally, if we find a branch
12517/// whose condition is a known constant, we only visit the reachable successors.
12518///
12519static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012520 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012521 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012522 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012523 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012524 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012525
Chris Lattner2c7718a2007-03-23 19:17:18 +000012526 while (!Worklist.empty()) {
12527 BB = Worklist.back();
12528 Worklist.pop_back();
12529
12530 // We have now visited this block! If we've already been here, ignore it.
12531 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012532
12533 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012534 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12535 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012536
Chris Lattner2c7718a2007-03-23 19:17:18 +000012537 // DCE instruction if trivially dead.
12538 if (isInstructionTriviallyDead(Inst)) {
12539 ++NumDeadInst;
12540 DOUT << "IC: DCE: " << *Inst;
12541 Inst->eraseFromParent();
12542 continue;
12543 }
12544
12545 // ConstantProp instruction if trivially constant.
12546 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12547 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12548 Inst->replaceAllUsesWith(C);
12549 ++NumConstProp;
12550 Inst->eraseFromParent();
12551 continue;
12552 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012553
Devang Patel7fe1dec2008-11-19 18:56:50 +000012554 // If there are two consecutive llvm.dbg.stoppoint calls then
12555 // it is likely that the optimizer deleted code in between these
12556 // two intrinsics.
12557 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12558 if (DBI_Next) {
12559 if (DBI_Prev
12560 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12561 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12562 IC.RemoveFromWorkList(DBI_Prev);
12563 DBI_Prev->eraseFromParent();
12564 }
12565 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012566 } else {
12567 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012568 }
12569
Chris Lattner2c7718a2007-03-23 19:17:18 +000012570 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012571 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012572
12573 // Recursively visit successors. If this is a branch or switch on a
12574 // constant, only visit the reachable successor.
12575 TerminatorInst *TI = BB->getTerminator();
12576 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12577 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12578 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012579 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012580 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012581 continue;
12582 }
12583 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12584 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12585 // See if this is an explicit destination.
12586 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12587 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012588 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012589 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012590 continue;
12591 }
12592
12593 // Otherwise it is the default destination.
12594 Worklist.push_back(SI->getSuccessor(0));
12595 continue;
12596 }
12597 }
12598
12599 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12600 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012601 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012602}
12603
Chris Lattnerec9c3582007-03-03 02:04:50 +000012604bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012605 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012606 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012607
12608 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12609 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012610
Chris Lattnerb3d59702005-07-07 20:40:38 +000012611 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012612 // Do a depth-first traversal of the function, populate the worklist with
12613 // the reachable instructions. Ignore blocks that are not reachable. Keep
12614 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012615 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012616 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012617
Chris Lattnerb3d59702005-07-07 20:40:38 +000012618 // Do a quick scan over the function. If we find any blocks that are
12619 // unreachable, remove any instructions inside of them. This prevents
12620 // the instcombine code from having to deal with some bad special cases.
12621 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12622 if (!Visited.count(BB)) {
12623 Instruction *Term = BB->getTerminator();
12624 while (Term != BB->begin()) { // Remove instrs bottom-up
12625 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012626
Bill Wendlingb7427032006-11-26 09:46:52 +000012627 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012628 // A debug intrinsic shouldn't force another iteration if we weren't
12629 // going to do one without it.
12630 if (!isa<DbgInfoIntrinsic>(I)) {
12631 ++NumDeadInst;
12632 Changed = true;
12633 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012634 if (!I->use_empty())
12635 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12636 I->eraseFromParent();
12637 }
12638 }
12639 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012640
Chris Lattnerdbab3862007-03-02 21:28:56 +000012641 while (!Worklist.empty()) {
12642 Instruction *I = RemoveOneFromWorkList();
12643 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012644
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012645 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012646 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012647 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012648 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012649 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012650 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012651
Bill Wendlingb7427032006-11-26 09:46:52 +000012652 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012653
12654 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012655 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012656 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012657 continue;
12658 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012659
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012660 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012661 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012662 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012663
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012664 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012665 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012666 ReplaceInstUsesWith(*I, C);
12667
Chris Lattner62b14df2002-09-02 04:59:56 +000012668 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012669 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012670 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012671 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012672 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012673 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012674
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012675 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12676 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012677 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12678 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012679 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012680 if (NewC != CE) {
12681 i->set(NewC);
12682 Changed = true;
12683 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012684 }
12685
Chris Lattnerea1c4542004-12-08 23:43:58 +000012686 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012687 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012688 BasicBlock *BB = I->getParent();
12689 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12690 if (UserParent != BB) {
12691 bool UserIsSuccessor = false;
12692 // See if the user is one of our successors.
12693 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12694 if (*SI == UserParent) {
12695 UserIsSuccessor = true;
12696 break;
12697 }
12698
12699 // If the user is one of our immediate successors, and if that successor
12700 // only has us as a predecessors (we'd have to split the critical edge
12701 // otherwise), we can keep going.
12702 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12703 next(pred_begin(UserParent)) == pred_end(UserParent))
12704 // Okay, the CFG is simple enough, try to sink this instruction.
12705 Changed |= TryToSinkInstruction(I, UserParent);
12706 }
12707 }
12708
Chris Lattner8a2a3112001-12-14 16:52:21 +000012709 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012710#ifndef NDEBUG
12711 std::string OrigI;
12712#endif
12713 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012714 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012715 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012716 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012717 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012718 DOUT << "IC: Old = " << *I
12719 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012720
Chris Lattnerf523d062004-06-09 05:08:07 +000012721 // Everything uses the new instruction now.
12722 I->replaceAllUsesWith(Result);
12723
12724 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012725 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012726 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012727
Chris Lattner6934a042007-02-11 01:23:03 +000012728 // Move the name to the new instruction first.
12729 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012730
12731 // Insert the new instruction into the basic block...
12732 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012733 BasicBlock::iterator InsertPos = I;
12734
12735 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12736 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12737 ++InsertPos;
12738
12739 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012740
Chris Lattner00d51312004-05-01 23:27:23 +000012741 // Make sure that we reprocess all operands now that we reduced their
12742 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012743 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012744
Chris Lattnerf523d062004-06-09 05:08:07 +000012745 // Instructions can end up on the worklist more than once. Make sure
12746 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012747 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012748
12749 // Erase the old instruction.
12750 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012751 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012752#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012753 DOUT << "IC: Mod = " << OrigI
12754 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012755#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012756
Chris Lattner90ac28c2002-08-02 19:29:35 +000012757 // If the instruction was modified, it's possible that it is now dead.
12758 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012759 if (isInstructionTriviallyDead(I)) {
12760 // Make sure we process all operands now that we are reducing their
12761 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012762 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012763
Chris Lattner00d51312004-05-01 23:27:23 +000012764 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012765 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012766 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012767 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012768 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012769 AddToWorkList(I);
12770 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012771 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012772 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012773 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012774 }
12775 }
12776
Chris Lattnerec9c3582007-03-03 02:04:50 +000012777 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012778
12779 // Do an explicit clear, this shrinks the map if needed.
12780 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012781 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012782}
12783
Chris Lattnerec9c3582007-03-03 02:04:50 +000012784
12785bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012786 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12787
Chris Lattnerec9c3582007-03-03 02:04:50 +000012788 bool EverMadeChange = false;
12789
12790 // Iterate while there is work to do.
12791 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012792 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012793 EverMadeChange = true;
12794 return EverMadeChange;
12795}
12796
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012797FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012798 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012799}